#!/usr/bin/perl
# m0j0.j0j0 
# Mythtv show verify script (Deletes incorrect files)

use DBI;
use Time::Local;

# Edit the next line to match your mythtv store directory
$path = "/pub/media/myth/"; 

$user='mythtv';
$pass='mythtv';

$dbh=DBI->connect('dbi:mysql:mythconverg',$user,$pass) || die "$DBI::errstr";

$sth = $dbh->prepare("SELECT chanid,starttime,endtime,title,subtitle FROM recorded;");
$sth->execute || die "Unable to execute query: $dbh->errstr\n";

$row=0;
while($row = $sth->fetchrow_arrayref)
{
	$chanid=$row->[0];
	$starttime=$row->[1];
	$endtime=$row->[2];
	$title=$row->[3];
	$subtitle=$row->[4];

	my $file =  $path . $chanid . "_" . $starttime . "_" . $endtime . ".nuv";
	my ($FileSize) = (stat $file)[7];
	my ($ModTime) = (stat $file)[9];

	my $Time = timelocal($seconds, $minutes, $hours, (localtime)[3,4,5]);
	my $TimeDiff = $Time - $ModTime; # Diff > 1800 --> 30Min 

	if (($FileSize < 1000) && ($TimeDiff > 1800)) { 
		print "SHOW: $title - $subtitle -- $file \n";
		print "FILE $file - $FileSize\n"; 
		
		$sth2 = $dbh->prepare("DELETE FROM recorded WHERE chanid=$chanid AND starttime=$starttime;");
		$sth2->execute || die "Unable to execute query: $dbh->errstr\n";
		unlink($file) || die("Couldn't unlink: $file $!");
	}
}
