#!/usr/bin/perl 
=item
command to update all the sites:

for i in `ls /etc/opals/conf/`; do cp -p /www/opals/script/util/genCodeAccessKey_EBOOK /tmp/urt; perl -pi -e "s/_MY_SITE_/$i/" /tmp/urt; sudo /tmp/urt; done

=cut
use lib '/www/opals/module';
#use Opals::Context("/etc/opals/conf/_MY_SITE_");

use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
);
use Time::localtime;
use Digest::SHA qw(
    sha1_hex
);

use Time::localtime;
use LWP::UserAgent;
use LWP::Protocol::http; # to suppress the warning "possible typo" in the next statement
push(@LWP::Protocol::http::EXTRA_SOCK_OPTS, MaxLineLength => 0);
use HTTP::Request::Common;


    my %options = ();
    getopts("u:",\%options);
    my $configFile="";
    my $ebs_host    ='ebook.hati.opalsinfo.net';



    my $httpConf = $options{u};

   $httpConf=~ s/^http:\/\///g;
   $httpConf=~ s/\/(.*)$//g;
   $httpConf = sprintf "/etc/httpd/conf.d/opals/%s.conf",$httpConf;
    if (!$httpConf || ! -f $httpConf) {
        print "Usage: $0 -u URL\n";
        exit 1;
    }
    $configFile=getConfPath($httpConf);

    if (!$configFile || ! -f $configFile) {
        print "Error reading Opals configuration file\n";
        exit 1;
    }
   updateHttpConfig($httpConf);


    my $config = loadConfig($configFile);
    my $dbh    = makeConnection($config);

    my $libCode = $config->{"db_user"} ;
    my $libName     = getPreference($dbh,'libName');


    my $content=[libCode=>$libCode,libName=>$libName];
    my $url="http://$ebs_host/bin/ws/addLib";
    my $rs =http_post($url,$content);


    if($rs->{'errorCode'} eq '0'){
        my $accessKey= $rs->{'accessKey'};
        my $pref2update=[
            {var=>'ebookModule', val=>'1',valShow=>'Enable'},
            {var=>'ebs_host',val=>$ebs_host,valShow=>$ebs_host},
            {var=>'ebs_libCode',val=>$libCode,valShow=>$libCode},
            {var=>'ebs_accessKey',val=>$accessKey,valShow=>$accessKey}
        ];
        my $sth=$dbh->prepare("update opl_preference set val=? ,valShow =? where var=?");
        foreach my $e(@$pref2update){
            $sth->execute($e->{'val'},$e->{'valShow'},$e->{'var'});
        }


        $dbh->do("replace into opl_permission set id=34, name='eBook Mgmt',grpId=1,code='ebook_mgmt'");
        $dbh->do("update opl_user set permissions=concat(permissions,',ebook_mgmt') where username='admin'");
        print "SUCCESS: ebook account has been created and linked to the Ebook server:.\n";

    }
    elsif($rs->{'errorCode'} eq '1'){
        print "ERROR: libCode $libCode has been assigned to other Library, or the library name is not the same as the one on eBook server.\n";
    }
    else{
        print "ERROR: access to this service denied by eBook server; verify to list of IPs allowed on eBook server\n";
    }

END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;


exit 0;

############################################################
sub makeConnection {
    my ($config) = @_;
    if (!$config) {
        return;
    }
    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";

    return DBI->connect($dsn, $db_user, $db_password);
}
############################################################


sub getConfPath {
    my ($configFile) = @_;
    my $path="";
    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        my $str=$_;
        if($str=~ m/SetEnv[\s]+OPALS_CONF[\s]+(\/etc\/opals\/conf\/(.*?))\n/g){
            $path=$1;
            last;
        }

    }
    close CONF;
    
    return $path;
}
############################################################
sub loadConfig {
    my ($configFile) = @_;
#    print "Enter the config filename of Opals: ";
#    $configFile = <STDIN>;
    my $config = {};

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

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

########################################################################

sub getPreference {
    my ($dbh,$var) = @_;;
    my ($val) = $dbh->selectrow_array(<<_STH_);
select val
from   opl_preference
where  var='$var'
_STH_

    return $val;
}

#////////////////////////////////////////////////////////////////////////////

sub http_post {
    my ($postURL, $postContent) = @_;

    my $ua = LWP::UserAgent->new();
    $ua->agent('OPALS  Web Service Client');
    $ua->timeout(120);
    my $result = {
        status  => 0,
        error   => '',
        content => '',
    };

    my $response = $ua->request(
        POST "$postURL",
        Content_Type => 'multipart/form-data', 
        Content => $postContent
    );

    if ($response->is_error() || !$response->is_success){
        $result->{'error'} = "connection error";
    }
    else {
        my $responseXml = $response->content;
        
        if ($responseXml =~ m/<errorCode>(.*)<\/errorCode>/gi){
            $result->{'errorCode'}= $1;
        }
        if ($responseXml =~ m/<accessKey>(.*)<\/accessKey>/gi){
            $result->{'accessKey'}= $1;
        }

    }
    return $result;
}

#////////////////////////////////////////////////////////////////////////////
sub updateHttpConfig{
    my ($httpConf)=@_;
    my $confTxt="";
    my $ebookRuleConfStr="";
    my $rules=[
        "RewriteRule   /ebook/reader/([^/]+) /bin/ebook/reader?bid=\$1 [PT]",
        "RewriteRule   /ebook/([^/]+)/([^/]+) /bin/ebook/file?bid=\$1&fid=\$2 [PT]"
    ];
    open CONF, $httpConf || die "Cannot open file $httpConf";
    while (<CONF>) {
        $confTxt .=$_;
    }
    close CONF;

    if($confTxt !~ m/RewriteEngine[\s]+on/g){
        $ebookRuleConfStr ="    RewriteEngine on\n";
    }
    $confTxt =~ s/RewriteRule[\s]+\/ebook\/(.*)\n//g;

        foreach my $rule(@$rules){
                $ebookRuleConfStr .="    $rule\n";
        }
        
        if($ebookRuleConfStr ne ""){
            $confTxt =~ s/(.*)[\s]*<\/VirtualHost>/$1\n$ebookRuleConfStr<\/VirtualHost>/g;
            open CONF, ">$httpConf";
            print CONF $confTxt;
            close CONF;

        }
    



}
#////////////////////////////////////////////////////////////////////////////
