#!/usr/bin/perl
use strict;
use warnings;
use File::Copy "cp";
use threads;
use Thread::Queue;

# lastepisodemagic <startindex> <endindex>
# Lösche Inhalt von $latest
# Kopiere Index Files nach $latest
# Erstelle m3u8 File für jedes Nameschema

my $latestdir = "/var/www/live.bitsundso.de/lastepisode/";
my $sourcedir = "/var/www/live.bitsundso.de/stream/ts/";
my $debug = 0;
my $numDeleteThreads = 5;
my $numCopyThreads = 5;

my $copyqueue = Thread::Queue->new();
my $deletequeue = Thread::Queue->new();

my $controllerthread = threads->new(\&controller)->detach;

my @threads;
my $shows = {};
for (my $i = 0;$i<$numDeleteThreads;$i++)
{
    push(@threads, threads->new(\&deleteThreaded));
}

for (my $i = 0;$i<$numCopyThreads;$i++)
{
    push(@threads, threads->new(\&copyThreaded));
}


sub emptyFolder {
    # Delete Files in the supplied folder
    my $folder = shift();
    opendir(DIR,$folder) or die ("Couldn't open Dir $folder. $!");
    foreach(readdir(DIR)){
        if($_ eq "." or $_ eq ".."){ next; }
        if($_ !~ "\.ts"){ next; }
        if($_ =~ "\.m3u8"){ next; }
        my $absFileName = $folder . "/" . $_;
        $deletequeue->enqueue($absFileName);
    }
}

sub deleteThreaded{
    print "deletethread started\n";
    while(my $filename = $deletequeue->dequeue()){
        #print "deleteThread $filename\n";
        unlink $filename;
    }
    $deletequeue->enqueue(undef);
    print "deletethread ending\n";
}

sub copyThreaded{
    print "Copythread started\n";
    while(my $filehash = $copyqueue->dequeue()){
        last if !defined($filehash);
        my ($sourceAbsPath,$destinationAbsPath) = split(":::",$filehash);
        #print "copyThread $sourceAbsPath $destinationAbsPath\n";
        cp($sourceAbsPath,$destinationAbsPath);
    }
    $copyqueue->enqueue(undef);
    print "Copythread ending\n";
}

sub controller{
    print "Controller started.\n";
    while(1){
        sleep 5;
        printf("Threads %s Deletejobs %s Copyjobs %s\n",int(threads->list(threads::running)),$deletequeue->pending(),$copyqueue->pending());
    }
    
}

sub usage {
    print "Here is a help... someday\n";
    die if $_[0] == 1;
}

# Process Arguments
my $startindex = shift;
my $endindex = shift;
usage(1) unless defined($startindex);
print "Backing up Files from index $startindex to index $endindex.\n";


# Empty $latest
emptyFolder($latestdir);


# Kopiere *.ts Files nach $latest
opendir(SOURCEDIR, $sourcedir) or die ("Couldn't open Dir $sourcedir");
foreach(readdir(SOURCEDIR)){
    my $filename = $_;
    if($filename =~ /^(.+)_(.+)_(.+)k-(\d+)\.ts$/){
        my $showname    = $1;
        my $codec       = $2;
        my $bitrate     = $3;
        my $index       = int($4);
        my $sourceAbsPath;
        my $destinationAbsPath;
        
        if($index >= $startindex and (!defined($endindex) or $index <= $endindex)){
            print "$1 $2 $3 $index\n" if $debug;
            $sourceAbsPath = $sourcedir . "/" . $filename;
            $destinationAbsPath = $latestdir . "/ts/" . $filename;
        }
        else{
            next;
        }
        
        $shows->{$showname}->{$codec}->{$bitrate}->{$index} = $filename;
        print "Copying $sourceAbsPath to $destinationAbsPath\n" if $debug;
        my $joinedfiles = join(":::",$sourceAbsPath,$destinationAbsPath);
        $copyqueue->enqueue($joinedfiles);
    }
}

while (my ($showname,$codecs) = each(%$shows)){
    print "$showname\n";
    while (my ($codec, $bitrates) = each(%$codecs)){
        print "$codec\n"; 
        while (my ($bitrate, $indexes) = each(%$bitrates)){
            print "Bitrate: $bitrate \n";
            my $outfileName = $latestdir. "/" . $showname . "_" . $codec . "_" . $bitrate . "k.m3u8";
            print "Opening File $outfileName\n";
            open(M3U8,"> $outfileName") or die ("Couldn\'t open $outfileName $!");

            print M3U8 "#EXTM3U\n";
            print M3U8 "#EXT-X-TARGETDURATION: 10\n";
            print M3U8 "#EXT-X-ALLOW-CACHE: YES\n";
            
            
            #print M3U8 "#EXT-X-MEDIA-SEQUENCE: 1\n"; ## TODO 
            foreach(sort { $a <=> $b } keys (%$indexes))
            {
                print M3U8 "#EXTINF:10\n";
                print M3U8  "ts/". $shows->{$showname}->{$codec}->{$bitrate}->{$_} . "\n";
            }
            print M3U8 "#EXT-X-ENDLIST\n";
            close(M3U8);
        }
    }
}

$deletequeue->enqueue(undef);
$copyqueue->enqueue(undef);

foreach(@threads){
    $_->join;
}




