#!/usr/bin/perl

# read all mapped tvheadend channels
my @hts_channels = `grep '"name"' /home/xbmc/.hts/tvheadend/channels/* | sed 's/://g' | cut -d'"' -f1,4 | sort -k2 | sed 's/\t"/<->/g'`;
$i=0;
my $prevChannelName='';
foreach my $line (@hts_channels) {
        my ($fileid, $htsChannelName) = split("<->",$line);
        chomp($htsChannelName);
        if ($htsChannelName ne $prevChannelName) {
                $prevChannelName=$htsChannelName;
                $i++;
        }
        # For each channel list all xmltv references
        printf("\n$htsChannelName - $fileid" );
        system("cat $fileid | grep -v '\"channel_number\"' > $fileid.tmp; rm $fileid");
        open(IN, "<$fileid.tmp");
        open(OUT, ">$fileid");
        while(<IN>) {
                my($line) = $_;
                if ($line =~ m/"dvr_extra_time_post"/) {
                        print OUT $line;
                        print OUT "\t\"channel_number\": $i\n";
                }
                else {
                        print OUT $line;
                }
        }
        close(IN);
        close(OUT);
        system("rm $fileid.*");
}