#!/usr/bin/perl

use DBI;
use strict;

###############################################################
# database configuration                                      #
###############################################################

my $cfg = <~/.mythtv/mysql.txt>;

my ($hostname,$database,$user,$password) = readCfg($cfg);
my $port = "3306";

my $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";

my $hostname = "mim";
my $query = "SELECT recorded.chanid chanid,starttime,endtime,title,subtitle, " .
  "description,hostname,channum,name,callsign,seriesid,programid,autoexpire " .
  "FROM recorded " .
  "LEFT JOIN channel ON recorded.chanid = channel.chanid " .
  "WHERE recorded.hostname = '" . $hostname . "' " .
  "AND autoexpire > 0 " .
  "ORDER BY autoexpire DESC, starttime ASC";
my $dbh = DBI->connect($dsn, $user, $password);
my $ssth = $dbh->prepare($query);
$ssth->execute();

my $ref;
while ($ref = $ssth->fetchrow_hashref()) {
  printf "%3d ",$ref->{'autoexpire'};
  printf "%s ",$ref->{'starttime'};
  printf "%s",$ref->{'title'};
  printf ": %s",$ref->{'subtitle'} if defined($ref->{'subtitle'}) && length($ref->{'subtitle'})>0;
  printf "\n";
}

exit;

sub readCfg {
  my ($cfg) = @_;
  my $user = "mythtv";
  my $pass = "mythtv";
  my $host = "localhost";
  my $database = "mythconverg";
  open(CFG,$cfg) || die "$0: unable to open cfg file: $!\n";
  while (<CFG>) {
    chomp;
    s/^\s+//;
    s/\s+$//;
    if (/^DBHostName\s*=\s*(.*)/i) {
      $host = $1;
    } elsif (/^DBUserName\s*=\s*(.*)/i) {
      $user = $1;
    } elsif (/^DBPassword\s*=\s*(.*)/i) {
      $pass = $1;
    } elsif (/^DBName\s*=\s*(.*)/i) {
      $database = $1;
    }
  }
  close(CFG);
  return ($host,$database,$user,$pass);
}
