#!/usr/bin/perl

BEGIN {
    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        print_help();
        exit 1;
    }

    sub print_help {
        print <<_STR_;
NAME:
    Set union circulation data, student ILL flags or location ID for specified 
    host.
SYNOPSIS:
    PERL5LIB=/www/opals/module OPALS_CONF=/etc/opals/conf/\$SITECODE \\
        $0 -h \$UNION_HOST [-c on|off] [-i on|off] [-l]
DESCRIPTION:
    -h  host name.
    -c  specify if union site has circulation data. Currently this option only 
        retrieves data.
    -i  enable or disable student ILL.
    -l  update location ID.
_STR_
    }
}

use Getopt::Std;

my %options = ();
getopts("h:c:i:l",\%options);
my $host = $options{h};

if (!$host ||
    !($options{c} || $options{i} || $options{l})) {
    print_help();
    exit 1;
}

use Opals::Context;
use Opals::WebServiceClient qw(
    wsc_getLibInfo
);

use strict;
my $dbh = Opals::Context->dbh();;
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...
print "Update $host";

my $sql = 'update opl_zDatabase set ';
my @param;

my $flag;

if ($options{c}) {
    $flag = ($options{c} eq 'on') ? 1 : 0;
    $sql .= "circData = $flag, ";
}

if ($options{i}) {
    $flag = ($options{i} eq 'on') ? 1 : 0;
    $sql .= "studentILL = $flag, ";
}

if ($options{l}) {
    my ($loc_code) = $dbh->selectrow_array(<<_SQL_);
select  lCode
from    opl_library
where   lid = 3
_SQL_
    print " for [$loc_code]: ";

    my $libInfo = wsc_getLibInfo(
            host        => $host, 
            loc_code    => $loc_code
        );

    my @lids = keys %{$libInfo};
    my $lid = $lids[0];

    print $libInfo->{$lid}->{'unionId'}, "\n";

    $sql .= 'locationId = ?, ';
    push @param, $libInfo->{$lid}->{'unionId'};
}

$sql =~ s/, $/ /;
$sql .= 'where host = ?';
push @param, $host;

$dbh->do($sql, undef, @param);

print " done.\n";
# Codes end.

exit 0;
