#!/usr/bin/perl
# mythexport_cleanup v1.0
# By: John Baab
# Email: rhpot1991@ubuntu.com 
# Purpose: Script for exporting mythtv recordings into formats used by portable devices.
# Requirements: perl and the DBI & DBD::mysql modules, MythTV perl bindings
#
# License:
#
# This Package is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# On Debian & Ubuntu systems, a complete copy of the GPL can be found under
# /usr/share/common-licenses/GPL-2, or (at your option) any later version

use DBI;
use DBD::mysql;
use Config::Simple;
use MythTV;

use strict;

my $connect = undef;

my $cfg = new Config::Simple();
$cfg->read('/etc/mythtv/mythexport/mythexport.cfg') || die "cannot read config file: /etc/mythtv/mythexport/mythexport.cfg";

my $dir = $cfg->param("dir");
$dir =~ s/\/$//;

my $myth = new MythTV();
# connect to database
$connect = $myth->{'dbh'};

# find the old recordings
my $query = "SELECT id, file FROM mythexport WHERE delDate < NOW()";
my $query_handle = $connect->prepare($query);
$query_handle->execute()  || die "Unable to query mythexport table";

while ( my ($id,$file) = $query_handle->fetchrow_array() ) {
    #remove file
    my $location = "$dir\/$file";
    unlink($location);

    #remove db entry
    my $query2 = "DELETE FROM mythexport WHERE id=?";
    my $query_handle2 = $connect->prepare($query2);
    $query_handle2->execute($id)  || die "Unable to delete entries from the mythexport table";
}

