#!/usr/bin/perl -w
#
# Export MythTV recordings into a variety of formats.
#
# @url       $URL$
# @date      $Date: 2010-08-16 22:11:27 -0700 (Mon, 16 Aug 2010) $
# @version   $Revision: 25709 $
# @author    $Author: beirdo $
# @license   GPL
#

# Version
    $VERSION = '0.5 0.20100817.svn';

# Autoflush buffers
    $|++;

# Set up the signal handlers
    BEGIN {
        $SIG{'INT'}  = sub { print "\n"; exit; };
        $SIG{'QUIT'} = sub { print "\n"; exit; };
    # Annoy people running as root
        if ($< < 1) {
            print "You are running nuvexport as root -- this is not advised.\nPress ENTER if you really want to do this.\n";
            <STDIN>;
        }
    }

# Add a couple of include paths so we can load the various export and gui modules
    use English;
    use File::Basename;
    use Cwd 'abs_path';
    use lib dirname(abs_path($0 or $PROGRAM_NAME)), '/usr/share/nuvexport', '/usr/local/share/nuvexport';

# Load the MythTV object
    use MythTV;
    our $Myth = new MythTV();

# Assign this globally so that other modules can access it
    $Main::Myth = $Myth;
    1 if ($Main::Myth);     # Avoid a stupid "used only once" warning

# Load the myth and nuv utilities, and connect to the database
    use Date::Manip;
    use nuv_export::shared_utils;
    use nuv_export::cli;
    use nuv_export::ui;
    use mythtv::recordings;

# Make sure that we have mythtranscode installed
    find_program('mythtranscode')
        or die "You need mythtranscode in order to use nuvexport.\n\n";

# Load the exporters based on which suite was selected above
    if ($export_prog eq 'ffmpeg') {
        find_program('ffmpeg')
            or die "You need ffmpeg in order to use nuvexport in --ffmpeg mode\n";
    # ffmpeg - seems to work better and is the default
        require export::ffmpeg::XviD;
        require export::ffmpeg::DVD;
        require export::ffmpeg::DivX;
        require export::ffmpeg::ASF;
        require export::ffmpeg::MP3;
        require export::ffmpeg::PSP;
        require export::ffmpeg::MP4;
    }
    elsif ($export_prog eq 'mencoder') {
        find_program('mencoder')
            or die "You need mencoder in order to use nuvexport in --mencoder mode\n";
    # mencoder
        require export::mencoder::XviD;
        require export::mencoder::H264MP3;
        require export::mencoder::H264AAC;

    }

# Load the other export modules
    require export::NUV_SQL;

# Load the ui
    load_cli_args();

# Now that we've loaded the cli args, we can define the exporters
    if ($export_prog eq 'ffmpeg') {
        push @Exporters, export::ffmpeg::XviD->new;
        push @Exporters, export::ffmpeg::DVD->new;
        push @Exporters, export::ffmpeg::DivX->new;
        push @Exporters, export::ffmpeg::ASF->new;
        push @Exporters, export::ffmpeg::MP3->new;
        push @Exporters, export::ffmpeg::PSP->new;
        push @Exporters, export::ffmpeg::MP4->new;
    }
    elsif ($export_prog eq 'mencoder') {
        push @Exporters, export::mencoder::XviD->new;
        push @Exporters, export::mencoder::H264MP3->new;
        push @Exporters, export::mencoder::H264AAC->new;
    }
    push @Exporters, export::NUV_SQL->new;

# Show the version?
    if (arg('version')) {
        print "nuvexport version:  $VERSION\n";
        exit;
    }

# Print the help - for now, this is just perldoc
    if (defined arg('help')) {
        require nuv_export::help;
    }

# Load the recordings, and the $video_dir variable
    load_recordings($Myth);

# Which exporter to use
    if (arg('only_save_info')) {
        $exporter = export::NUV_SQL->new;
    }
    else {
        $exporter = query_exporters($export_prog);
    }

# Load episodes from the commandline (and display/quit if this is search-only)
    @episodes = load_cli_episodes();

# Gather the episodes we want to transcode (unless we have them from the cli already)
    @episodes = &load_episodes(@episodes) unless ($is_cli);

# Gather data for this exporter
    $exporter->gather_settings();

# Encode right here?
    if (arg('noserver')) {
        foreach my $episode (@episodes) {
        # Save the info?
            if (arg('save_info') || arg('only_save_info')) {
                my $outfile = $exporter->get_outfile($episode, '.txt');
                open(DATA, ">$outfile") or die "Can't create $outfile:  $!\n";
                print DATA join("\n", 'title:       '.$episode->{'title'},
                                      'subtitle:    '.($episode->{'subtitle'}    eq 'Untitled'       ? '' : $episode->{'subtitle'}),
                                      'description: '.($episode->{'description'} eq 'No Description' ? '' : $episode->{'description'}),
                                      'starttime:   '.UnixDate("epoch $episode->{'starttime'}", '%O'),
                                      'endtime:     '.UnixDate("epoch $episode->{'endtime'}", '%O'),
                                      'category:    '.$episode->{'category'},
                                      'chanid:      '.$episode->{'chanid'},
                                      'channum:     '.$episode->{'channum'},
                                      'callsign:    '.$episode->{'callsign'},
                                      'channame:    '.$episode->{'channame'},
                                      'airdate:     '.(UnixDate('epoch '.$episode->{'airdate'}, '%O') or $episode->{'airdate'}),
                                      'stars:       '.(4 * $episode->{'stars'}),
                                      'recgroup:    '.$episode->{'recgroup'},
                                      'seriesid:    '.$episode->{'seriesid'},
                                      'programid:   '.$episode->{'programid'},
                                      ''
                               );
                close DATA;
            # Skip ahead if we're not supposed to actually export recordings
                next if (arg('only_save_info'));
            }
        # Keep track of when we started
            if ($DEBUG) {
                print "\n--------------------------------",
                      "\nTo encode:  ", $episode->{'title'};
                print ':  ', $episode->{'subtitle'} if ($episode->{'subtitle'});
                print "\nUse the following commands:\n";
            }
            else {
                print "\nNow encoding:  ", $episode->{'title'};
                print ':  ', $episode->{'subtitle'} if ($episode->{'subtitle'});
                print "\nEncode started:  ".localtime()."\n";
            }
            my $start = time();
        # Encode
            $exporter->export($episode);
        # Remove tmpfiles
            wipe_tmpfiles();
        # Report how long the encode lasted
            print "\nEncode finished:  ".localtime()."\n" unless ($DEBUG);
            my $seconds = time() - $start;
            my $timestr = '';
        # How many hours?
            my $hours = int($seconds / 3600);
            $timestr .= $hours.'h ' if ($hours > 0);
            $seconds  = $seconds % 3600;
        # Minutes
            my $minutes = int($seconds / 60);
            $timestr .= $minutes.'m ' if ($minutes > 0);
            $seconds  = $seconds % 60;
        # Generate a nice time string
            $timestr .= $seconds.'s' if ($seconds > 0 || $timestr eq '');
        # Notify the user
            print "Encode lasted: $timestr\n" unless ($DEBUG);
        }
    }
# Store in the DB
    else {
    }

# Exit gracefully
    exit;

# Escape a string for db insertion
    sub mysql_escape {
        $string = shift;
        return 'NULL' unless (defined $string);
        $string =~ s/'/\\'/sg;
        return "'$string'";
    }

# vim:ts=4:sw=4:ai:et:si:sts=4
