#!/usr/bin/env perl
#===============================================================================
#
#         FILE: load_downloads
#
#        USAGE: ./load_downloads infile
#
#  DESCRIPTION: Loads episode downloads from a file into the 'eps' table
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.0.1
#      CREATED: 2014-08-30 17:46:47
#     REVISION: 2014-08-30 17:46:52
#
#===============================================================================

use 5.010;
use strict;
use warnings;
use utf8;

use Config::General;
use Text::CSV_XS;

use DBI;

#
# Version number (manually incremented)
#
our $VERSION = '0.0.1';

#
# Script name
#
( my $PROG = $0 ) =~ s|.*/||mx;
( my $DIR  = $0 ) =~ s|/?[^/]*$||mx;
$DIR = '.' unless $DIR;

#-------------------------------------------------------------------------------
# Declarations
#-------------------------------------------------------------------------------
#
# Constants and other declarations
#
my $basedir    = "$ENV{HOME}/HPR/Database";
my $configfile = "$basedir/.hpr_db.cfg";

my ( $dbh, $sth1, $sth2, $sth3, $sth4, $h1, $h2, $rv );
my ( $infile, $row );

#
# Enable Unicode mode
#
binmode STDOUT, ":encoding(UTF-8)";
binmode STDERR, ":encoding(UTF-8)";

#
# Check the input file
#
$infile = shift;
die "Usage: $PROG input_file\n" unless $infile;
die "Unable to find/read file '$infile'\n" unless -r $infile;

#
# Load configuration data
#
my $conf = new Config::General(
    -ConfigFile      => $configfile,
    -InterPolateVars => 1,
    -ExtendedAccess  => 1
);
my %config = $conf->getall();

#-------------------------------------------------------------------------------
# Connect to the database
#-------------------------------------------------------------------------------
my $dbhost = $config{database}->{host};
my $dbname = $config{database}->{name};
my $dbuser = $config{database}->{user};
my $dbpwd  = $config{database}->{password};
$dbh = DBI->connect( "dbi:mysql:host=$dbhost;database=$dbname",
    $dbuser, $dbpwd, { AutoCommit => 1 } )
    or die $DBI::errstr;

#
# Enable client-side UTF8
#
$dbh->{mysql_enable_utf8} = 1;

$sth1 = $dbh->prepare(q{UPDATE eps SET downloads = ? WHERE id = ?});

#
# Open the input file
#
open( my $in, "<", $infile ) or die "Unable to open $infile: $!\n";

my $csv = Text::CSV_XS->new;

#
# Process all lines as CSV
#
while ( $row = $csv->getline($in) ) {
    $sth1->execute( $row->[1], $row->[0] );
    if ( $dbh->err ) {
        warn $dbh->errstr;
    }
}

close($in);

exit;

# vim: syntax=perl:ts=8:sw=4:et:ai:tw=78:fo=tcrqn21:fdm=marker

