#!/usr/bin/perl
# m0j0.j0j0

use DBI;

my $DBuser = 'mythtv';
my $DBpass = 'mythtv';
my $mythFiles = '/pub/media/myth/'; 
my $minFreeSpace = 5 * 1024 * 1024; #5GB


my $dbh = DBI->connect('dbi:mysql:mythconverg',$DBuser,$DBpass) || die "$DBI::errstr";
my $chkSpace = '1';

while ($chkSpace) {

	# check current free space
	open(HAND, "df -k $mythFiles |") || die ("Unable to list free space: $!");
	my @mythDir = <HAND>;
	($actualFreeSpace) = $mythDir[1] =~ / (\d+) *\d+%/;
	close(HAND);

	print "CURRENT FREE SPACE: $actualFreeSpace (MIN REQUIRED: $minFreeSpace)\n";
	if ($actualFreeSpace < $minFreeSpace) { deleteOldest(); }
	else { $chkSpace = 0; }

}

print "OK: Free space currently: ", $actualFreeSpace / 1024 / 1024, " GB\n"; 


sub deleteOldest {

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

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

	my $oldestFile = $mythFiles . $chanid . "_" . $starttime . "_" . $endtime . ".nuv";
	print "\tDELETING: $oldestFile --> $title - $subtitle\n";
	$sth = $dbh->prepare("DELETE FROM recorded WHERE starttime = $starttime AND chanid = $chanid;");
	$sth->execute || die "Unable to execute query: $dbh->errstr\n";
	`/bin/rm -f $oldestFile`;
}
