#!/usr/bin/perl -w
# dvbradioexport.pl
# By Justin Hornsby 18 August 2006
# 
# A MythTV user job script for exporting DVB radio recordings to MP3 format
#
# Usage info will be output if the script is run with no arguments (or insufficient arguments)
#
# Contains elements of mythtv.pl by Nigel Pearson
# Initial idea from nuvexport
# 
# requirements: id3tag, ffmpeg with mp3 exporting enabled, PERL and the DBI & DBD::mysql modules
#

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql

#
$host     = '127.0.0.1';
$database = 'mythconverg';
$user     = 'mythtv';
$pass     = $user;

$hostname = 'umbongo2';

$prefix = '/usr/bin';

$db = undef;
$connect = undef;
$debug = 'nodebug';
######################################
#                                    #
#        SUBROUTINES ARE HERE        #
#                                    #
######################################


# Try to find the database
#
sub findDatabase()
{
    my $found = 0;
    my @mysql = ('/usr/local/share/mythtv/mysql.txt',
        '/usr/share/mythtv/mysql.txt',
        '/etc/mythtv/mysql.txt',
        '/usr/local/etc/mythtv/mysql.txt',
        "$ENV{HOME}/.mythtv/mysql.txt",
        'mysql.txt'
    );
    foreach my $file (@mysql) {
        next unless (-e $file);
        $found = 1;
        open(CONF, $file) or die "Unable to open $file:  $!\n\n";
        while (my $line = <CONF>) {
            # Cleanup
            next if ($line =~ /^\s*#/);
            $line =~ s/^str //;
            chomp($line);

            # Split off the var=val pairs
            my ($var, $val) = split(/\=/, $line, 2);
            next unless ($var && $var =~ /\w/);
            if ($var eq 'DBHostName') {
                $host = $val;
            } elsif ($var eq 'DBUserName') {
                $user = $val;
            } elsif ($var eq 'DBName') {
                $database = $val;
            } elsif ($var eq 'DBPassword') {
                $pass = $val;
            }
        }
        close CONF;
    }

if ( ! $found )
    {   die "Unable to locate mysql.txt:  $!\n\n"  }
}


#  DB connect subroutine
# =======================
# openDatabase() - Connect or die
#

sub openDatabase()
{
    $db = DBI->connect("dbi:mysql:database=$database" .
                               ":host=$host",
                               $user, $pass)
              or die "Cannot connect to database: $!\n\n";

    return $db;
}

##################################
#                                #
#    Main code starts here !!    #
#                                #
##################################
#
#
# FIND THE DATABASE SETTINGS

$usage = "\nHow to use dvbradioexport.pl \n\ndvbradioexport.pl %CHANID% %STARTTIME% %ENDTIME% exportdir bitrate --debug\n"
        ."\n%CHANID% = channel ID associated with the recording to export\n"
        ."%STARTTIME% = recording start time in either 'yyyy-mm-dd hh:mm:ss' or 'yyyymmddhhmmss' format\n"
        ."%ENDTIME = as %STARTTIME% but for the recording end time\n"
        ."exportdir = dir to export completed MP3 files to (note the user the script runs as must have write permission on that dir\n"
        ."bitrate = CBR bitrate in kbps (e.g. 192)\n"
        ."--debug = enable debugging information - outputs which commands would be run etc\n";

findDatabase();

# get this script's ARGS
#

$num = $#ARGV + 1;

# if user hasn't passed enough arguments, die and print the usage info

if ($num le "4") {
              die "$usage";
            }

$chanid = $ARGV[0];
$starttime = $ARGV[1];
$endtime = $ARGV[2];
$exportdir = $ARGV[3];
$bitrate = $ARGV[4];


if ($num eq "6") {
                  $debug = $ARGV[5];
                 }

if($debug eq "--debug")
          {
             print "\n\n*********************************************************************************************\n";
             print "  EXPORT DVB RADIO  SCRIPT IS RUN WITH $chanid $starttime $endtime $exportdir $bitrate \n";
             print "*********************************************************************************************\n";
          }
#
# connect to database
#
$connect = openDatabase(); 

# PREPARE THE QUERY
$query = "SELECT title, subtitle, description FROM recorded WHERE chanid=$chanid AND starttime='$starttime'";

$query_handle = $connect->prepare($query);


# EXECUTE THE QUERY
$query_handle->execute() || die "Cannot connect to database \n";

# BIND TABLE COLUMNS TO VARIABLES
$query_handle->bind_columns(undef, \$title, \$subtitle, \$description);

# LOOP THROUGH RESULTS
$query_handle->fetch();

# FIND WHERE THE RECORDINGS LIVE
$query = "SELECT data FROM settings WHERE value='RecordFilePrefix' AND hostname='$hostname'";

$query_handle = $connect->prepare($query);
$query_handle->execute()  || die "Unable to query settings table";

my ($dir) = $query_handle->fetchrow_array;

# FIND OUT THE CHANNEL NAME
$query = "SELECT name FROM channel WHERE chanid=$chanid";
$query_handle = $connect->prepare($query);
$query_handle->execute()  || die "Unable to query settings table";

my ($channame) = $query_handle->fetchrow_array;

# replace whitespace in channame with dashes
$channame =~ s/\s+/-/g;

# replace whitespace in title with underscores
$title =~ s/\W+/_/g;
# replace whitespace in subtitle with underscores
$subtitle =~ s/\W+/_/g;

#
# Remove non alphanumeric chars from $starttime & $endtime
#
 
$newstarttime = $starttime;

$newstarttime =~ s/[|^\W|\s|-|]//g;

$newendtime = $endtime;
$newendtime =~ s/[|^\W|\s|-|]//g;

$filename = $dir."/".$chanid."_".$newstarttime.".mpg";

$newfilename = $exportdir."/".$channame."_".$title."_".$subtitle."_".$newstarttime.".mp3";

if ($debug eq "--debug") {
                          print "\nSource filename:$filename \nDestination filename:$newfilename\n";
                        }

#
# Estimate the final size of the MP3 file
#

# get year from starttime
$year = substr($newstarttime, 0, 4);
 
# get hour from starttime
$starthour = substr($newstarttime, 8,2);
$startminute = substr($newstarttime,10,2);
$startsecond = substr($newstarttime,12,2);

$endhour = substr($newendtime, 8,2);
$endminute = substr($newendtime,10,2);
$endsecond = substr($newendtime,12,2);

$dhours = $endhour - $starthour;
$dmins = $endminute - $startminute;
$dsecs = $endsecond - $startsecond;

$duration = ($dhours * 3600) + ($dmins * 60) + $dsecs;

$newfilesize = $bitrate * $duration /8;

# now check there is sufficient space in $exportdir (i.e. greater than $newfilesize)

open(CMD, "/bin/df -k $exportdir |");
while(<CMD>)
              {
               next unless /\d/;
               @f = split(/\s+/);
               $available = $f[3];
              }

if ( $available > $newfilesize )
   {
     if($debug eq "--debug")
               {
                 print "\nThere is $available"."KB space in $exportdir, enough for $filename of $newfilesize"."KB \n";
               }
   }

else
     {
      die "There is insufficient room for $filename of $newfilesize"."KB"." in $exportdir, which has $available"."KB free \n";
     }


#
# Now run ffmpeg to get mp3 out of the dvb radio recording
#

$command = $prefix."/nice -n19 ffmpeg -i $filename -ab 192 -acodec mp3 -f mp3 '$newfilename' 2>&1";

if ($debug eq "--debug") {
                      print "\nUSING $command \n";
                    }

system "$command";

# Now tag the finished MP3 file

$command = "id3tag --song=$title --album=$subtitle --artist=$channame --comment='$description' --year=$year $newfilename";

if ($debug eq "--debug") {
                           print "\nUsing $command \n";
                         }
system "$command";
