#!/usr/bin/env perl

use warnings;
use strict;

use DBI;
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock'; # Socket for mysql
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );

use Nebulous::Client;

use constant EXT => [ 'inConv.fits', 'inConv.mk.fits', 'inConv.wt.fits',
                      'refConv.fits', 'refConv.mk.fits', 'refConv.wt.fits' ]; # Extensions to delete

my $hostname = `hostname`;      # Name of host
chomp $hostname;


my ($db_host, $db_name, $db_user, $db_pw); # Database details
my @extensions;                            # Extensions to delete

GetOptions(
    'dbhost=s' => \$db_host, # Database host name
    'dbname=s' => \$db_name, # Database name
    'dbuser=s' => \$db_user, # Database user
    'dbpass=s' => \$db_pw, # Database p/w
    'ext=s' => \@extensions,    # Extensions to delete
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --ext\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw;

# Database connection
my $db = DBI->connect( "DBI:mysql:database=$db_name;host=$db_host;mysql_socket=" . DB_SOCKET(),
                       $db_user,
                       $db_pw,
                       { RaiseError => 1, AutoCommit => 1 }
                       ) or die "Unable to connect to database: $DBI::errstr";

# Nebulous client
my $neb = Nebulous::Client->new( proxy => $ENV{NEB_SERVER} ) or die "Unable to connect to Nebulous: $!\n";

my @files;                      # Files to clean up
{

    my $sql = <<SQL_DONE;
SELECT path_base
FROM diffRun
JOIN diffSkyfile USING(diff_id)
JOIN magicRun USING(diff_id)
WHERE diffRun.state IN ('full', 'drop')
    AND magicRun.state IN ('full', 'drop', 'censored')
    AND diffRun.bothways = 0
    AND diffSkyfile.hostname = '$hostname'
UNION
SELECT path_base
FROM diffRun
JOIN diffSkyfile USING(diff_id)
JOIN magicRun AS magicPositive
    ON magicPositive.diff_id = diffRun.diff_id
    AND magicPositive.inverse = 0
JOIN magicRun AS magicNegative
    ON magicNegative.diff_id = diffRun.diff_id
    AND magicNegative.inverse = 1
WHERE diffRun.state IN ('full', 'drop')
    AND magicPositive.state IN ('full', 'drop', 'censored')
    AND magicNegative.state IN ('full', 'drop', 'censored')
    AND diffRun.bothways = 1
    AND diffSkyfile.hostname = '$hostname'
SQL_DONE

    my $results = $db->selectall_arrayref( $sql ) or die "Unable to execute SQL: $DBI::errstr";

    $db->disconnect;

    foreach my $result ( @$results ) {
        my $path = $$result[0];
        next if $path !~ m|^neb://|;
        foreach my $ext ( @{EXT()} ) {
#        foreach my $ext ( @extensions ) {
            my $file = "$path.$ext";
            print "$file\n";
            eval { $neb->delete($file); };
#            $file = eval { $neb->find($file); };
#            print "--> $file\n";
        }
    }
}
