use strict;
use warnings;
use JSON qw(decode_json);
use File::Slurp;
use File::Copy;

my $renamed = 0;
my $dir = "/home/hts/.hts/tvheadend/dvr/log";
opendir(DIR,$dir) or die "Cannot open " . $dir;
while (my $file = readdir(DIR)) {
	next if ($file =~ m/^\./);
	next unless (-f "$dir/$file");
	my $recording = decode_json read_file "$dir/$file";
	my $desc = $recording->{"description"}->{"dut"};
	next unless ($desc);
	my $suffix = "";
# (s 1/afl 2)
	my ($s,$e) = ($desc =~ /\(s\ ([0-9]*)\/afl\ ([0-9]*)\)/);
	if ($e) {
		$suffix = "s" . $s . "e" . ($e > 9 ? $e : "0" . $e);
	} else {
# (s 1)
		($s) = ($desc =~ /\(s\ ([0-9]*)\)/);
		if ($s) {
			$suffix = "s" . $s;
		} else {
# (afl 2)
			($e) = ($desc =~ /\(afl\ ([0-9]*)\)/);
			if ($e) {
				$suffix = "e" . ($e > 9 ? $e : "0" . $e);
			} else {
# Episode 2
				($e) = ($desc =~ /Episode\ ([0-9]*)/);
				if ($e) {
					$suffix = "e" . ($e > 9 ? $e : "0" . $e);
				}
			}
		}
	}
        next unless ($suffix);
	$suffix = "." . $suffix . ".";
	my $fn = $recording->{"filename"};
	next if (!$fn || ($fn =~ /\.s[0-9]+e[0-9]+\./) || ($fn =~ /\.S[0-9]+e[0-9]+\./) || index($fn,$suffix)>0);
	my ($before,$after) = ($fn =~ /(.*)\.([a-z]*)$/);
	my $newfn = $before . $suffix . $after;
        move $fn, $newfn or print "Rename failed for $newfn \n";
	$renamed ++;
}
closedir(DIR);
print "Renamed $renamed files. \n";
exit(0);
