#!/usr/bin/perl

use strict;
use DBI;

my $scriptname = `basename $0`;
chomp $scriptname;
if ($ENV{'LOGNAME'} ne 'root') {
    print STDERR "$scriptname: run by $ENV{'LOGNAME'}\n";
    exit 1;
}

my $backupRunning=`ps -ef | grep 'opals/bin/backup' | grep -v grep`;
if ($backupRunning) {
    print "Backup is running...\n";
    exit 2;
}

my $isRunning = `ps -ef | grep $scriptname | grep perl | grep -v grep | wc -l`;
chomp($isRunning);
if ($isRunning > 1) {
    print "$scriptname is running...\n";
    exit 3;
}

checkAllSite();
#while (checkAllSite()) {
#}

exit 0;


################################################################################
sub checkAllSite {
    my $OPALS_CONF_DIR = '/etc/opals/conf/';

    open SITECODE, "ls $OPALS_CONF_DIR | ";
    my @siteList;
    while (<SITECODE>) {
        chomp;
        my $code = $_;

#        next if ($code =~ m/^__sample/);
#        print "This is $code\n";

        my $site;
        $site->{'code'} = $code;
        $site->{'config'} = loadConfig($code);
        if (!$site->{'config'}) {
            next;
        }

#        $site->{'dateRequest'} = dateRequest($site->{'config'});
#        push @siteList, $site if ($site->{'dateRequest'});
        push @siteList, $site;
    }
    close SITECODE;

    return if (scalar(@siteList) == 0);

    my ($opals_conf, $vhost_conf, $opals_root, $script);
    my $running = 0;

    foreach my $s 
            (@siteList) {
#            (sort { $a->{'dateRequest'} <=> $b->{'dateRequest'} } @siteList) {
        # site config file
        $opals_conf = $OPALS_CONF_DIR . $s->{'code'};

        # vhost config file
        $vhost_conf = 
            `grep -R "$opals_conf\$" /etc/httpd/conf.d/opals | cut -d: -f1`;
        chomp $vhost_conf;

        # OPALS root
        $opals_root = '/' .
            `cat $vhost_conf | sed -re 's/#.+\$//' | grep OPALS_ROOT | cut -d/ -f2,3`;
        chomp $opals_root;

        # run script
        $script = $opals_root . '/script/cron/exec_requests';
        print time_now(), ": start $script $s->{'code'}...\n";
        if (-x $script) {
            $ENV{'PERL5LIB'} = $opals_root . '/module';
            $ENV{'OPALS_CONF'} = $opals_conf;
            system($script, $s->{'code'});

            $running = 1;
        }
    }

    return $running;
}


############################################################
sub loadConfig {
    my ($siteCode) = @_;

    my $configFile = "/etc/opals/conf/$siteCode";
    if (! -r $configFile) {
        return;
    }
    
    my $config;

    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        chomp;                  # remove new line
        s/#.*//;                # remove comments
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $config->{$1} = $2;
        }
    }
    close CONF;

    return $config;
}


############################################################
#sub dateRequest {
#    my ($config) = @_;
#
#    my ($db_driver, $db_name, $db_host, $db_port, $db_user, $db_password);
#    $db_driver   = $config->{'db_driver'} || 'mysql';
#    $db_name     = $config->{'db_name'};
#    $db_host     = $config->{'db_host'};
#    $db_port     = $config->{'db_port'}   || '3306';
#    $db_user     = $config->{'db_user'};
#    $db_password = $config->{'db_password'};
#    my $dsn = "dbi:$db_driver:$db_name:$db_host:$db_port";
#    my $dbh = DBI->connect($dsn, $db_user, $db_password) || return;
#
#    my $dateRequest;
#    
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  dateUpload
#from    opl_marcImport
#where   status = 'accepted' &&
#        countProcessed < countTotal
#order by dateUpload asc
#limit 1
#_STH_
#    }
#
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  dateRequest
#from    opl_marcExport
#where   status = 'waiting'
#order by dateRequest asc
#limit 1
#_STH_
#    }
#
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  dateRequest
#from    opl_itemTypeChange
#where   status in ('waiting', 'processing')
#order by dateRequest asc
#limit 1
#_STH_
#    }
#
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  reqDate
#from    opl_ge852request
#where   status in ('waiting', 'processing')
#order by reqDate asc
#limit 1
#_STH_
#    }
#
#    if (!$dateRequest) {
#        my ($autoUpdateUnion) = $dbh->selectrow_array(<<_SQL_);
#select  val
#from    opl_preference
#where   var='autoUpdateUnion'
#_SQL_
#
#        my ($unionSvcUrl) = $dbh->selectrow_array(<<_SQL_);
#select  val
#from    opl_preference
#where   var='unionSvcUrl'
#_SQL_
#
#        if ($autoUpdateUnion && $unionSvcUrl) {
#            ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  date
#from    opl_unionRequest
#where   status in ('pending', 'processing')
#order by date asc
#limit 1
#_STH_
#        }
#    }
#
#    # textbook import
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  dateUpload
#from    tb_csvImport
#where   status = 'accepted'
#order by dateUpload asc
#limit 1
#_STH_
#    }
#
#    if (!$dateRequest) {
#        ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  dateUpload
#from    tb_marcImport
#where   status = 'accepted'
#order by dateUpload asc
#limit 1
#_STH_
#    }
#    #/textbook import
#
#    # send circulation data to union site
#    if (!$dateRequest) {
#        my ($sendCircData) = $dbh->selectrow_array(<<_SQL_);
#select  val
#from    opl_preference
#where   var = 'unionCircUpdate'
#_SQL_
#        if ($sendCircData) {
#            ($dateRequest) = $dbh->selectrow_array(<<_STH_);
#select  val
#from    opl_preference
#where   var = 'unionCircUpdateDate'
#     && val + interval 30 minute < now()
#_STH_
#        }
#    }
#
#    #Delete outdated export
#    my $sth = $dbh->prepare(<<_STH_);
#select  to_days(dateExpiry) - to_days(now())
#from    opl_marcExport
#where   eid = ?
#_STH_
#    my $exDir = $config->{'exDir'};
#    ($exDir) || ($exDir = "/data/opals/export/$db_name");
#
#    my ($eid, $deltaExpiry);
#    open EID, "ls $exDir/ | ";
#    while (<EID>) {
#        $eid = $_;
#        if ($eid =~ m/([\d]+)\.mrc$/) {
#            $eid = $1;
#            $sth->execute($eid) || last;
#            ($deltaExpiry) = $sth->fetchrow_array;
#            if ($deltaExpiry < 0) {
#                print "Delete $exDir/$eid.mrc\n";
#                unlink "$exDir/$eid.mrc";
#            }
#        }
#    }
#    close EID;
#    $sth->finish;
#
#    $dbh->disconnect();
#
#    return $dateRequest;
#}


############################################################
sub time_now {
    my $tn = `date +'%Y-%m-%d %H:%M:%S'`;
    chomp $tn;

    return $tn;
}
