#! /usr/bin/env perl
use warnings;

use DateTime;
use Sys::Hostname;
use PS::IPP::Config;
use DBI;

# Set up the database
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';
$dbname = 'gpc1';
$dbserver = 'ippdb01';
$dbuser = 'ippuser';
$dbpass = 'ippuser';
$db = DBI->connect("DBI:mysql:database=${dbname};host=${dbserver};" .
                   "mysql_socket=" . DB_SOCKET(),
                   ${dbuser},${dbpass}, 
		   { RaiseError => 1, AutoCommit => 1}
    ) or die "Unable to connect to database $DBI::errstr\n";


%stages = ("RAW" => 'rawExp',
	   "CHIP" => 'chipRun',
	   'CAMERA' => 'camRun',
	   'WARP' => 'warpRun',
	   'DIFF' => 'diffRun',
	   'STACK' => 'stackRun',
	   'DIST' => 'distRun',
	   'DESTREAK' => 'magicDSRun',
	   'MAGIC' => 'magicRun',
	   'DETREND' => 'detRun');

$base_query = 'select state,count(state) AS N from TABLETABLE GROUP BY state';


%im_stages = ("RAW" => 'rawImfile',
	      "CHIP" => 'chipProcessedImfile',
	      "WARP" => 'warpSkyfile',
	      "DIFF" => 'diffSkyfile'
    );


$im_query = 'select data_state,count(data_state) AS N from TABLETABLE GROUP BY data_state';

foreach $k (keys %im_stages) {
    $stages{$k} = $im_stages{$k};
}

my $ipprc = PS::IPP::Config->new("GPC1");
my $nebcon = $ipprc->nebulous();

my @lt = gmtime;
$dt = DateTime->now;
$dt->subtract( days => $lt[6]);
my $datestring = $dt->ymd;
my $outfile = "neb:///ipp_diskspace/${datestring}/run_im_counts.dat";
my $out_fh;
if ($ipprc->file_exists($outfile)) {
    my $U_file = $ipprc->file_resolve($outfile);
    open($out_fh,">$U_file");
}
else {
    $out_fh = $ipprc->file_create_open($outfile);
}

foreach $s (keys %stages) {
    my $query = $base_query;
    if (exists($im_stages{$s})) {
	$query = $im_query;
    }
    $query =~ s/TABLETABLE/$stages{$s}/;
    print STDERR "$s $query\n";
    my $dr = $db->selectall_arrayref( $query );
    foreach $rr (@{ $dr }) {
	my ($state,$count) = @{ $rr };
	print $out_fh "$s $state $count\n";
    }
}
print $out_fh "EXTERNAL any 1\n";
close($out_fh);

