#!/usr/bin/env perl
# Attempt to guess xmltvids for the (FTA) channels in your mythtv database.
# You'll probably find this useful for syncing the channel numbers afterwards:
#   select b.chanid,a.channum,b.channum,a.xmltvid from channel a, channel b where a.sourceid=2 and b.sourceid=3 and a.xmltvid=b.xmltvid and a.xmltvid != '' order by a.channum;

use Text::LevenshteinXS;

my $mysql = 'mysql -u mythtv -poxxzqsve mythconverg';

unless (-e 'channels.dat') {
	system("wget http://xmltv.radiotimes.com/xmltv/channels.dat") == 0 or die "wget: $!";
}

my %rtid_name = ();
open F, "<channels.dat" or die "open: $!";
while (<F>) {
	chomp;
	/^(\d+)\|(.*)$/ or die "bad line: $_";
	$rtid_name{$1} = $2;
}
close F;

my %rtid_xmltv = ();
my %name_xmltv = ();
open F, "</usr/share/xmltv/tv_grab_uk_rt/channel_ids" or die "open: $!";
while (<F>) {
	chomp;
	/^#/ and next;
	/^(.*):(\d+):(.*)$/ or die "bad line: $_";
	$rtid_xmltv{$2} = $1;
	$name_xmltv{lc $3} = $1;
}
close F;

foreach my $rtid (keys %rtid_name) {
	next if exists $rtid_xmltv{$rtid};

	my $xmltv = sprintf("C%04d.radiotimes.com", $rtid);
	$rtid_xmltv{$rtid} = $xmltv;
	$name_xmltv{lc $rtid_name{$rtid}} = $xmltv;
}

my %blacklist = ();
open F, "<blacklist" or die "open: $!";
while (<F>) {
	chomp;
	$blacklist{$_} = 1;
}
close F;

open F, "echo 'select chanid,name,xmltvid from channel order by name;' | $mysql|" or die "open: $!";
<F>;
while (<F>) {
	chomp;
	/^(\d+)\t(.*)\t(.*)$/ or die "bad line: $_";
	if (exists $blacklist{$2}) {
		print "delete from channel where chanid=$1;  -- $2\n";
	} elsif ($3 ne '') {
		$name_xmltv{lc $2} = $3;
	} else {
		push @need_xmltv, [$1, $2];
	}
}
close F;

sub print_update ($$$) {
	my ($chanid, $name, $xmltvid) = @_;

	print "update channel set xmltvid='$xmltvid' where chanid=$chanid;   -- $name\n";
}

foreach my $n (@need_xmltv) {
	my ($chanid, $name) = @$n;
	my $lname = lc $name;
	if (exists $name_xmltv{$lname}) {
		print "-- Exact:\n";
		print_update($chanid, $name, $name_xmltv{$lname});
	} else {
		my %scores = ();
		foreach my $maybe (keys %name_xmltv) {
			$scores{$maybe} = distance($lname, $maybe);
		}
		my @best = sort { $scores{$a} <=> $scores{$b} } keys %scores;
		my $best_s = $scores{$best[0]};
		my $i = 0;
		print "-- $name: no exact match: your options at distance $best_s are:\n";
		while ($scores{$best[$i]} == $best_s) {
			print_update($chanid, $best[$i], $name_xmltv{$best[$i]});
			push @options, $best[$i++];
		}
	}
}
print "update channel set useonairguide=1 where xmltvid = '';\n";
print "update channel set useonairguide=0 where xmltvid != '';\n";

