#!/usr/bin/perl -w

use strict;

unless($ARGV[0] && $ARGV[1]) { die "Missing Input(s)\ndvRecord {minutes} {filename}"; }
my $time    = ($ARGV[0] * 60);
# my $channel = $ARGV[1];
my $file    = $ARGV[1];

my $day = `date "+%w"`;
chop($day);
my $timedOut = 0;
my $pid;
my $command1 = qq~mkdir -p "/pvr/$file"~;
my $command2 = qq~/bin/nice -n-10 /usr/bin/dvgrab --format dv2 "/pvr/$file/${file}_"~;

$SIG{ALRM} = \&timeOut;
if ($pid = fork) {
 #print "Launched pid: $pid\n";
} elsif (defined $pid)  {
  system("$command1");
  exec("$command2");
} else {
  die "Can't fork for some reason\n";
}

alarm($time);
while (1) {
 if ($timedOut == 1) {
  #print "Timeout, killing $pid\n";
  kill INT => $pid;
  exit;
 }
 select(undef, undef, undef, 0.25);
}

sub timeOut {
 $timedOut = 1;
}

