#!/usr/bin/perl -w
#
#

use strict;

use Getopt::Std;
use File::Basename;

my %opt;
usage() unless getopts('n:c:qhldv', \%opt);

if( $opt{l} ) { 
    list_clients( $ARGV[0] );
}

if( $opt{h} ) { 
    usage();
}

my $cacher = new Migration( client_id    => $opt{c},
                            quiet        => $opt{q},
                            verbose      => $opt{v},
                            debug        => $opt{d} );

$cacher->run();

sub usage {
    my $prog = basename $0;

    print <<EofUSAGE;

usage: $prog [-c client_id] [-l client_name/pattern] [-h] [-d]
            -c - Client ID (if not specified then run for all clients)
            -l - List client ids (host pattern is optional)
            -d - display debug information to STDERR
            -v - display verbose debug information to STDERR
            -q - Do not output summary report
            -h - display this screen
EofUSAGE

exit 1;
}

sub list_clients {
    my $host = shift;
    my $key;
    foreach $key ( sort {$a <=> $b} keys( %Common::RSDB::CLIENT_DB ) ) {
        printf( "%-20s %-10s ID: %s\n",
                $Common::RSDB::CLIENT_DB{$key}->{db_name},
                "($Common::RSDB::CLIENT_DB{$key}->{host_id})",
                $key )
            if( ! defined($host) || $Common::RSDB::CLIENT_DB{$key}->{db_name} =~ /$host/i );
    }
    exit 1;
}


package PDDB;

use lib '/app/tools/common/lib';

use lib '/app/tools/rps/lib';
use base 'RPS::DB::Item::Album';

sub ResetDeliveries
{
   my $class = shift;

   my $sql = "UPDATE product_distribution " .
             'SET date_queued = \N, distribution_job_id = \N ' .
             "WHERE " .
                "distribution_job_id IS NOT NULL and " .
                "product_distribution.date_queued IS NOT NULL and " .
                "delivery_date IS NULL and " .
                "NOT invalid AND " .
                "denied IS NULL";
   
   my $dbo = Common::RSApp::GetClientDB();

   Common::Log::Debug( "SQL: $sql" );

   my $sth = $dbo->DoCmd( $sql );
}

sub CopyJobs
{
   my $class = shift;

   my $sql = "insert into distribution_process (created, distribution_process_id, xml_data) select created, distribution_job.distribution_job_id, xml_data from distribution_job inner join distribution_job_data USING (distribution_job_id)";
   
   my $dbo = Common::RSApp::GetClientDB();

   Common::Log::Debug( "SQL: $sql" );

   my $sth = $dbo->DoCmd( $sql );
}



package Migration;

use lib '/app/tools/common/lib';
use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::WriteXML;

use lib '/app/tools/common/lib';
use base 'Common::Script';

use lib '/app/tools/rps/lib';
use base 'RPS::Catalog::Album';
use RPS::DB::Item::Album;
use RPS::DB::Item::Product;

use Data::Dumper;

sub _process
{
    my $self = shift;

    #PDDB->ResetDeliveries();
    PDDB->CopyJobs();
}
