#
# Here's what we're a gonna do:
# - RENAME the current job table.
# - CREATE the new job table.
# - BACK-FILL the job table with previous job data.
#

use lib '/app/tools/common/lib';
use lib '/app/tools/job/lib';
use Common::RSApp;
use Common::RSDB;

my $app = Common::RSApp->new( clientID => 0 );

print "RENAME the job table\n";

print "CREATE new job table\n";

print "BACKFILL job table\n";

my $dbo = Common::RSApp::GetCommonDB();

my $sql = "SELECT * FROM job_old";
my $sth = $dbo->DoCmd($sql);
while ( my $hr = $sth->fetchrow_hashref() ) {
    my @insertPairs;
    push @insertPairs, "job_id=" . $hr->{job_id};
    push @insertPairs, "hostname=" . $dbo->DBQuote( $hr->{hostname} ) if $hr->{hostname};
    push @insertPairs, "class=" . $dbo->DBQuote( $hr->{class} ) if $hr->{class};
    push @insertPairs, "priority=" . $dbo->DBQuote( $hr->{priority} ) if $hr->{priority};
    push @insertPairs, "pid=" . $hr->{pid} if $hr->{pid};
    push @insertPairs, "job_log_id=" . $hr->{job_log_id} if $hr->{job_log_id};
    push @insertPairs, "queue_date=" . $dbo->DBQuote( $hr->{date_created} ) if $hr->{date_created};

    # Parse the client_id from the command-line
    #
    my $commandLine = $hr->{command_line};
    push @insertPairs, "command_line=" . $dbo->DBQuote( $hr->{command_line} );
    my $clientID;
    if ( 'ImportSalesFile' eq $hr->{class} ) {
        if ( $commandLine =~ /^.*file.pl (\d+)/ ) {
            $clientID = $1;
            push @insertPairs, "client_id=$clientID";
        }
    } else {
        if ( $commandLine =~ /^.*-c (\d+)/ ) {
            $clientID = $1;
            push @insertPairs, "client_id=$clientID";
        }
    }

    my $status = $hr->{status};
    if ( 'HOLD' eq $status || 'PAUS' eq $status || 'TEST' eq $status ) {
        push @insertPairs, "on_hold=1";
    } elsif ( 'IN_Q' eq $status ) {
    } elsif ( 'RUN ' eq $status ) {
        push @insertPairs, "start_date=" . $dbo->DBQuote( $hr->{date_created} ) if $hr->{date_created};
    } else {
        push @insertPairs, "start_date=" . $dbo->DBQuote( $hr->{date_created} ) if $hr->{date_created};
        push @insertPairs, "end_date=" . $dbo->DBQuote( $hr->{date_modified} )  if $hr->{date_modified};
    }

    my $insertSQL = "INSERT INTO job SET " . join( ',', @insertPairs );
    $dbo->DoCmd($insertSQL);
}
