#! /usr/bin/env perl

use DBI;
use PS::IPP::Config 1.01 qw( :standard );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::List qw( parse_md_list );
use IPC::Cmd 0.36 qw( can_run run );
use Carp;
use Pod::Usage qw( pod2usage );

use strict;
use warnings FATAL => qw( all );
use Getopt::Long qw( GetOptions :config auto_help auto_version );
use File::Basename;
use Nebulous::Client;

use DBI;
use Nebulous::Server::SQL;


my ($host,$volume,$source,$source_vol,$dir);
GetOptions(
    'host=s' => \$host,
    'volume=s' => \$volume,

    'source=s' => \$source,
    'source_volume=s' => \$source_vol,
    'dir=s'   => \$dir) || pod2usage(2 );

my (    $db, $dbhost, $dbpass, $dbuser);
#my $conffile = "/home/panstarrs/ipp/ippconfig/nebulous.config";
my $conffile = '/data/ippc64.1/ippitc/ippconfig/nebulous.config';

if (-e $conffile) {
#    printf STDERR "found config\n";
    open(IN,$conffile);
    while(<IN>) {
        chomp;
        if ($_ =~ /NEB_DB\s+/) {
            $db = (split /\s+/,$_)[2];
        }
        elsif ($_ =~ /NEB_DBHOST/) {
            $dbhost = (split /\s+/,$_)[2];
        }
        elsif ($_ =~ /NEB_USER/) {
            $dbuser = (split /\s+/,$_)[2];
        }
        elsif ($_ =~ /NEB_PASS/) {
            $dbpass = (split /\s+/,$_)[2];
        }
    }
    close(IN);
#    print STDERR  "$db $dbhost $dbuser $dbpass\n";
}

pod2usage( -msg => "Cannot configure nebulous database", -exitval => 2) unless
    defined $host && defined $volume && defined $dir &&
    defined $db && defined $dbhost && defined $dbuser && defined $dbpass;



my $host_check = `hostname`;
chomp($host_check);
if ($host ne $host_check) {
    die "Required to run on $host.  not on $host_check\n";
}

my $server = $ENV{'NEB_SERVER'};
my $neb = Nebulous::Client->new(
    proxy => "$server",
    );

my $time = time();


#$dbhost = '166.122.172.39';
#my $dbport = '3308';
#my $dbh = DBI->connect(
#     "DBI:mysql:database=$db:host=$dbhost:port=$dbport",
#     $dbuser,
#     $dbpass,
#     {
#         RaiseError => 1,
#         PrintError => 0,
#         AutoCommit => 1,
#     },
#     );
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';

my $dbh = DBI->connect("DBI:mysql:database=${db};host=${dbhost};" .
                       "mysql_socket=" . DB_SOCKET(),
		       ${dbuser},${dbpass},
		       { RaiseError => 1, AutoCommit => 1}
    ) or die "Unable to connect to database $DBI::errstr\n";


my $logDest = "/export/${host}.${volume}/retire_rsync/restore/${host}.${volume}/${source}.${volume}/${dir}.log.${time}";

#if ((${host} eq 'ippb04')&&($volume == 2)) {
#    $logDest = "/export/${host}.0/stsci_shuffle/restore/${host}.${volume}/${source}.${volume}/${dir}.log.${time}";
#}

my $ipprc = PS::IPP::Config->new( "GPC1" ) or die "Could not create config object.\n";
$ipprc->redirect_output($logDest) or die "Could not redirect output to logfile ${logDest}\n";

my $root = "/export/${host}.${volume}/retire_rsync/data/${source}.${source_vol}/nebulous/${dir}";
my @subdirectories = <$root/*>;



# Get the vol_id of the (local) destination.

my $local_volume = "${host}.${volume}";
my $source_volume= "${source}.${source_vol}";

my $sql = Nebulous::Server::SQL->new();

my $query = $dbh->prepare( $sql->get_volume_by_name );
$query->execute( $local_volume );
my ($local_vol_id, $local_vol_name, $local_vol_host, $local_vol_path) = $query->fetchrow_array;
$query->finish;

$query->execute( $source_volume );
my ($source_vol_id, $source_vol_name, $source_vol_host, $source_vol_path) = $query->fetchrow_array;
$query->finish;

print "LOG INIT $host $volume $source $source_vol $dir $local_vol_id $source_vol_id\n";

foreach my $subdir (@subdirectories) {

    my $destination_subdir = $subdir;
    $destination_subdir =~ s%/retire_rsync/data/${source}.${source_vol}/nebulous%/nebulous%;

    my @files = <${subdir}/*>;
    my $otime = $time;
    $time = time();
    my $dtime = $time - $otime;
    print "LOG BEGIN $subdir $time $dtime\n";
    for (my $i = 0; $i <= $#files; $i++) {
        my $f = $files[$i];
        my ($ins_id);
        $ins_id = $f;
        $ins_id =~ s/^$subdir\///;
        $ins_id =~ s/\..*//;

        # Write log of what we plan to do.
        my $destination_f = $f;
        $destination_f =~ s%/retire_rsync/data/${source}.${source_vol}/nebulous%/nebulous%;

        my $db_uri = $destination_f;
        $db_uri =~ s%^/export/%/data/%;
        $db_uri = 'file://' . $db_uri;

        print "$ins_id $f $destination_f $db_uri\n";

#       die;

        # Do move of file.
        if (-e $destination_f) {
            print "FILE ALREADY FOUND\n";
            next;
        }

        my $validate_ins_id_query = "SELECT * FROM instance WHERE vol_id = ${source_vol_id} AND ins_id = ${ins_id}";
        my @instances = $dbh->selectall_arrayref( $validate_ins_id_query );
        if ($#instances != 0) { # We expect one instance on the source
            print "NO DB ENTRY\n";
            next;
        }


#       print "PASSED DB CHECK: $#instances\n";
#       system("stat ${f}");
        system("mv ${f} ${destination_f}");
#       system("stat ${destination_f}");

        # Register database change:

        unless (-e $destination_f) {
            die;
        }

        $query = $dbh->prepare( $sql->update_instance_uri );
        $query->execute( $local_vol_id, $db_uri, $ins_id );
        $query->finish;
#       die;
    } # END loop over files
    rmdir($subdir);
} # END loop over subdirectories
rmdir($root);

