#!/usr/bin/perl

use POSIX qw(strftime);
use Getopt::Std;

my %opts;
my $tformat;

getopts('suzf:t:h?', \%opts);

if ($opts{'h'} || $opts{'?'}) {
  print<<EOF;

  usage: unixtime [-f format] [-t timezone] [-suz] [arguments]

  options:
    -?: this help
    -h: this help
    -f: define the strftime format
    -s: add the replaced timestamp in ()
    -t: use the timezone specified
    -u: use UTC timezone
    -z: print ZULU time

  unixtime can be used as a filter:
  eg: rrdtool fetch ... | unixtime [options]

  or with filenames as arguments:
  eg: unixtime [options] file1 file2 ... filen

  or with timestamps as arguments:
  unixtime [options] 1232182800 1232182860 ...

EOF

  exit;
}

if ($opts{'f'}) {
  # use specified format
  $tformat=$opts{'f'};
} elsif ($opts{'z'}) {
  # use ZULU time
  $tformat='%FT%TZ';
} else {
  # use standard 24h local time
  $tformat='%F %T %Z';
}

if ( $opts{'t'} ) {
  $ENV{TZ} = $opts{'t'};
  POSIX::tzset();
} elsif ( $opts{'u'} || $opts{'z'} ) {
  # use UTC timezone for -u and -z
  $ENV{TZ} = 'UTC';
  POSIX::tzset();
}

sub mprint($) {
  my $line = shift;
  chomp $line;
  if ( $line =~ /^(\d+(?:\.\d+)?)(\D.*)?$/ ) {
    # add timestamp if requested (-s)
    my $st=$opts{'s'} ? " ($1)" : "";
    $line = strftime($tformat,localtime($1)) . $st . $2;
  }
  print "$line\n";
}

sub floop($) {
  if (open(FILE,shift)) {
    while (<FILE>) {
      mprint($_);
    };
    close(FILE);
  }
}

if ( scalar @ARGV ) {
  for $arg (@ARGV) {
    if ( -f $arg ) {
      floop($arg);
    } else {
      mprint($arg);
    }
  }
} else { # use sdtin by default
  floop('-');
}
