#!/usr/bin/perl

use strict;
use JSON;
use LWP::UserAgent;
use open ":std", ":encoding(UTF-8)";

# you might need to
#  debian based: apt-get install libjson-perl
#  redhat based: yum install perl-JSON
#  other: perl -MCPAN -e 'install JSON'

my $host = $ARGV[0] || die "specify dvr host/ip address\n";

my $ua   = LWP::UserAgent->new(timeout => 10);
my $json = JSON->new->utf8();
my %URL  = (guide => "http://${host}:8089/devices/ANY/guide?duration=30",
            m3u   => "http://${host}:8089/devices/ANY/channels.m3u?format=ts",
           );

my %guide;
for my $channel (@{ $json->decode( hget($URL{guide})->decoded_content ) }){
    (my $title = $channel->{Airings}[0]{Title}) =~ s/-/_/g;
    $guide{ $channel->{Channel}{Number} } = $title
}

for (split /\n/, hget($URL{m3u})->decoded_content){
    chomp;
    if( /^(.+tvg-id="([^"]+)".+),(.+)/ ){
        my ($whole,$cid,$desc) = ($1,$2,$3);
        print "$whole,[${cid} $desc]: $guide{$cid}\n";
    }else{
        print "$_\n";
    }
}

sub hget {
    my $url = shift;
    my $r = $ua->get($url);
    unless( $r->is_success ){
        warn "error: ", $r->decoded_content, "\n";
        die $r->status_line;
    }
    return $r;
}
