#!/usr/bin/perl -T 
use v5.8 ; use strict ; use warnings ; 
use Getopt::Std ; #getoptions 'l' , \my %o ;
use Time::Local ; 
use Term::ANSIColor qw[:constants] ; $Term::ANSIColor::AUTORESET = 1 ;

getopts '~.:dhlmq0:',  \my %o ; 
do { select STDERR ; HELP_MESSAGE () } if ! @ARGV ; 
$o{0} //= '' ; 
my $dig = $o{'.'} // 2 ; # 小数点以下何桁まで表示をするか

& main ; 
exit ; 

sub main { 
	$"="\t" ;
    my $fmt = "%0.${dig}f" ; # "%.4g" # 出力の printf形式のフォーマット
    my $info= $o{l} ? sub { lstat $_[0] }  : sub ($) { stat $_[0] }  ;
	my $t0 = timelocal ( localtime ) ; # <---- -- ただ今の時刻
	my $fpos = $o{'~'} ? 0 : 3 ; # 出力で何列目にファイル名を挿入するか
	my $div = $o{d} ? 86400 : $o{h} ? 3600 : $o{m} ? 60 : undef ; # 秒数をいくつで割るか
	my $u = $o{d} ? '(d)' : $o{h} ? '(h)' : $o{m} ? '(m)' : '(s)' ; # 単位の表示
	if ( ! $o{q} ) {
		my @out = qw[atime mtime ctime] ;
		grep { $_ .= $u } @out ; 
		splice @out, $fpos, 0, qw[filename]; 
		print "@out\n" ;
	}
    for ( @ARGV ) { 
        do { print STDERR CYAN "$_ :- Not exists.\n" ; next } unless  -e ; 
        my @out = my @out0 = map { $t0 - $_ } @{[ $info->($_) ]}[ 8,9,10 ] ; # atime mtime ctime
        @out = map { sprintf $fmt , $_ / $div } @out0 if defined $div ; 
        @out = map { &dt ($_)} @{[ $info->($_) ]}[ 8,9,10 ]  if $o{0} =~ /[td]/i ;	
        #@out = map { &ymd ($_)} @{[ $info->($_) ]}[ 8,9,10 ]  if $o{0} =~ /d/i ;	
        $_ .= '/' if -d ; # ディレクトリには 名前の末尾に / を追加。
        splice @out , $fpos , 0 , $_  ; # ファイル名の挿入
        print "@out\n" ;
    }
}

sub dt ( $ ){
	my @T = $o{0} =~ m/u/i ? gmtime $_[0] : localtime $_[0] ; 
	my @ret ; 
	push @ret , sprintf '%02d-%02d-%02d', $T[5] % 100 , $T[4]+1, $T[3] if $o{0} =~ /d/i ; 
	push @ret , sprintf '%02d:%02d:%02d' , @T[2,1,0] if $o{0} =~/t/i ; 
	return join ' ' , @ret ;
}

## ヘルプの扱い
sub VERSION_MESSAGE {}
sub HELP_MESSAGE {
    use FindBin qw[ $Script ] ; 
    $ARGV[1] //= '' ;
    open my $FH , '<' , $0 ;
    while(<$FH>){
        s/\$0/$Script/g ;
        print $_ if s/^=head1// .. s/^=cut// and $ARGV[1] =~ /^o(p(t(i(o(ns?)?)?)?)?)?$/i ? m/^\s+\-/ : 1;
    }
    close $FH ;
    exit 0 ;
}


=encoding utf8

=head1

 $0  ファイル名のリスト

  各ファイルについて、次の時刻から現在までの秒数を出力する。Seconds after the following for each file specified.
   (1) アクセス access (2) 更新時刻 update (3) i-nodeの変更時刻

 利用例 usage : 

   $0 -m *    #  分単位でファイルの古さを表示
   $0 -0dt *  #  ファイルの時刻情報3個を，現在の日時と比較しないで出力。

 オプション options :

    -d : 日単位で出力する。 in day unit.
    -h : 時間単位で出力する。 in hour unit.
    -m : 分単位で出力する。 in minute unit.
    -l : シンボリックリンクの先のファイルの情報を取得する。

    -q : 通常の出力の1行目にある、atime, mtime, ctime, filename の情報を出力しない
    -~  : ファイル名を各行の先頭に置く。 File names put in the mostleft column.
    -. N : 小数点以下何桁まで表示をするか(秒単位なら意味なし)。 Digits after the decimal point in the output.

    -0 str: 今の瞬間までの経過時間ではなくて、ファイルの時刻情報を出す。strに含まれる文字により、dなら日付、tなら時刻、uならUTCを出力。

=cut
