#!/usr/bin/perl

die "$0 má špatný počet parametrů.\n\nSprávně má být:\n$0 Kanál norma délka_záznamu\n$0 E5 PAL-DK 01:00:00\n\n" if @ARGV != 3;


$soubor_avi=`LC_TIME="cs_CZ.UTF-8" date +%A-%d.%m.%Y-%H:%M.avi`;

if ( not (`ps -A | grep "mencoder"` or `ps -A | grep "mplayer"`)) { system "mencoder tv://$ARGV[0] -tv driver=v4l2:norm=$ARGV[1]:input=0:alsa:adevice=hw.1,0:audiorate=32000:forceaudio:immediatemode=0 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=3000 -oac mp3lame -lameopts cbr:br=128 -endpos $ARGV[2] -o /home/petr/Videa/$soubor_avi >/dev/null 2>>/home/petr/error.txt";

}

# Uzivatelsky cron podle ktereho budeme spoustet PC
$SOUBOR_CRON="/tmp/petr_crontab.txt";

# Pri debug 1 vypisujeme co delame (0 = jsme potichu)
$DEBUG=0;


system "crontab -l > /tmp/petr_crontab.txt";

open(DATA, "<", $SOUBOR_CRON) or die "Nelze otevřít soubor: $!";

$cas=0;
$starycas=0;

while ($radek=<DATA>) {

chomp $radek;

# je neco na radku - spracujeme
if (length($radek)>0) {
if ($DEBUG==1) { print $radek . "\n"; }

use Schedule::Cron::Events;

my $cron = new Schedule::Cron::Events( $radek, Seconds => time());
my ($sec, $min, $hour, $day, $month, $year) = $cron->nextEvent;
if ($DEBUG==1) { printf("Další start: %2d:%02d:%02d on %d.%02d.%d\n", $hour, $min, $sec, $day, ($month+1), ($year+1900)); }

# turn a local date into a Unix time
use Time::Local;
my $epochSecs = timelocal($sec, $min, $hour, $day, $month, $year);
if ($DEBUG==1) { print "počet " . $epochSecs . " sekund co je " . localtime($epochSecs) . "\n"; }

# Vybirame nejdrivejsi cas
if ($starycas==0) { $starycas=$epochSecs; $cas=$epochSecs; }
if ($epochSecs<$starycas) { $cas=$epochSecs; }
$starycas=$epochSecs;

# konec spracovani radku
}
# konec spracovani souboru
}
close DATA;

if ($DEBUG==1) { print "Ted je cas: " . time() . "\n"; }

# Odecteme 10 minut
$cas-=600;
if ($cas>time() and `w | grep " 1 user"` ) { exec "sudo /sbin/shutdown -h now 2>>/home/petr/error.txt"; }

