#!/usr/bin/perl

###
### (C) Thomas Köhler <jean-luc@picard.franken.de>
###
### Released under GPLv2
###
### URL: http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/shell/
### this script: http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/shell/countdown
###

use Time::HiRes qw(usleep);
use POSIX ":sys_wait_h";
use Time::Duration;

my $START=time();
my $END=$START;

$SIG{CHLD} = \&bye;

my $count=$ARGV[0] || 10;


if($count < 0) {
   $count = -$count;
}

$|=1;
my $start ="807";

print "7";
print "Starting countdown of " . duration_exact($count) . ", press enter to stop countdown immediately...\n";
print "7";

my $pid = fork();
my $lastlength=1;

if($pid) {
   <STDIN>;
   kill 9, $pid;
   exit;
} else {
   while($END-$START < $count) {
      print "$start";
      print ' 'x${lastlength};
      print "$start";
      my $t = from_now_exact($count-$END+$START);
      print $t;
      $lastlength = length($t);
      usleep(100000);
      $END=time();
   }
}


print "$start";
print "done.                      \n";

sub bye {
   my $kid;
   do {
      $kid = waitpid(-1, WNOHANG);
   } while $kid > 0;
   exit;
}
