#!/usr/bin/perl

use strict;
use warnings;
use POSIX;

# Open icecast error.log
# Scan for latest start Event
# Scan for latest end Event
# If latest end-Event is older than latest start-event and endevent is older than stored file event
#   find start index at event timestamp
#   find end index at event timestamp
#   Execute lastepisodemagic with these parameters
#   Store endindex in some file

my $icecastErrorLogFileName = "/var/log/icecast2/error.log";
my $lastLatestEndEvenFileName = "/var/run/lastLatestEvent";
my $sourceTSFileDir = "/var/www/live.bitsundso.de/stream/ts";
my $onAirYesNo = "/var/www/live.bitsundso.de/stream/onair";

my $latestStartEventTimestamp;
my $latestEndEventTimestamp;

my $debug = 0;

sub findIndexByModificationTime {
    my $modifyTime = shift;
    
    opendir(SOURCEDIR,$sourceTSFileDir) or die "Couldn't open dir $sourceTSFileDir ($!)\n";
    my %files;
    foreach (readdir(SOURCEDIR))
    {
        next if !($_ =~ /\.ts$/);
        my $filepath = $sourceTSFileDir . "/" . $_;
        my @stat = stat($filepath);
        $files{$stat[9]} = $filepath;
    }
    
    foreach(sort(keys(%files))){
        print $_ . " " . $files{$_} . "\n";
        if($_ > $modifyTime){
	    print "File $files{$_} was created after $modifyTime\n";
            if($files{$_} =~ /(\d+)\.ts$/){
                return int($1);
            }
            last;
        }
    }
    print "No matching index found for timestamp $modifyTime\n";
}




open(ICECASTLOG,$icecastErrorLogFileName) or die "Couldn't open $icecastErrorLogFileName ($!)\n";
while(<ICECASTLOG>)
{
    #[2010-01-03  15:42:23] INFO source/source_move_clients passing 1 listeners to "/plus"
    if ($_ =~ /^\[(\d\d\d\d)-(\d\d)-(\d\d)  (\d\d):(\d\d):(\d\d)\] INFO source\/source_move_clients passing \d+ listeners to "\/plus"\n$/){
        my $year    = $1;
        my $month   = $2;
        my $day     = $3;
        my $hour    = $4;
        my $minute  = $5;
        my $second  = $6;
        
        $latestStartEventTimestamp = mktime($second, $minute, $hour, $day, $month-1, $year-1900);
        print "StartEvent $latestStartEventTimestamp\n" if $debug;
    }
    elsif ($_ =~ /^\[(\d\d\d\d)-(\d\d)-(\d\d)  (\d\d):(\d\d):(\d\d)\] INFO source\/source_move_clients passing \d+ listeners to "\/fallback"\n$/){
        my $year    = $1;
        my $month   = $2;
        my $day     = $3;
        my $hour    = $4;
        my $minute  = $5;
        my $second  = $6;
        
        
        $latestEndEventTimestamp = mktime($second, $minute, $hour, $day, $month-1, $year-1900);
        print "EndEvent $latestEndEventTimestamp\n" if $debug;
    }
}
close(ICECASTLOG);

# OnAir API ;-)
if($latestStartEventTimestamp > $latestEndEventTimestamp) #Sendung laaft
{
    system("touch $onAirYesNo");
}

# Wenn diese Episode schon exitiert beende dich.
my $storedTime = 0;
if(open(STORAGE,$lastLatestEndEvenFileName))
{
    $storedTime = <STORAGE>;
}

if ($storedTime >= $latestEndEventTimestamp)
{
    exit;
}

if($latestEndEventTimestamp > $latestStartEventTimestamp){ # Aufnahme beendet. Mach deine Magie
    # Store Event in Filesystem
    open(STORAGE,"> $lastLatestEndEvenFileName") or die ("Couldn't open Storage File $lastLatestEndEvenFileName ($!)\n");
    print STORAGE $latestEndEventTimestamp;
    close(STORAGE);
    print "Off Air\n";
    unlink($onAirYesNo); # On Air API ;-)
    my $startindex = findIndexByModificationTime($latestStartEventTimestamp);
    my $endindex = findIndexByModificationTime($latestEndEventTimestamp)+1;
    print "Generating Episode from " . localtime($latestStartEventTimestamp) . " (Index $startindex) to " . localtime($latestEndEventTimestamp) . " (Index $endindex)\n";
    my $cmd = "/usr/local/bin/lastepisodemagic.pl $startindex $endindex";
    print $cmd . "\n";
    system($cmd);
}

