#!/usr/bin/perl 
use lib("/www/opals/module");
use strict;
use DBI;
use Opals::SIF::SifSubscriber;
use Opals::SIF::ObjectDataParser::SchoolInfoParser;
use Opals::SIF::Specs;
use JSON;




my @zisList=();

load_ZIS();
foreach my $zis(@zisList){
    $zis->{'agent'}=Opals::SIF::SifSubscriber->new($zis->{'sifInfo'},$zis->{'zone'});
    $zis->{'agent'}->unRegister($zis->{'zone'});
}

exit 0;


#------------------------------------------------------------------------------

sub load_ZIS {
    my $OPALS_CONF_DIR = '/etc/opals/conf/';
        open SITECODE, "ls $OPALS_CONF_DIR | ";
        my @siteList;
        while (<SITECODE>) {
            chomp;
            my $code = $_;

            my $site;
            my $config = loadConfig("/etc/opals/conf/$code");
            if (!$config || $config->{'type'} eq 'union') {
                next;
            }
            push @siteList, $code;
        }
        close SITECODE;

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

        my ($opals_conf, $vhost_conf, $opals_root, $script);

        foreach my $s (@siteList) {
                getSIfConfig($s);
        }
    
}
#------------------------------------------------------------------------------
sub getSIfConfig{
    my ($site)=@_;
    my $dbh=getDbh($site);
    my($SIF_zis_url,$SIF_version,$SIF_sourceId,$SIF_schoolLocalId)=(undef,undef,undef,undef);
    my ($SIF_enable)=$dbh->selectrow_array("select val from opl_preference where var='SIF_enable'");
       ($SIF_zis_url)=$dbh->selectrow_array("select val from opl_preference where var='SIF_zis_url'");
    if(defined $SIF_enable && $SIF_enable eq '1'){
        ($SIF_version)=$dbh->selectrow_array("select val from opl_preference where var='SIF_version'");
        ($SIF_sourceId)=$dbh->selectrow_array("select val from opl_preference where var='SIF_sourceId'");
        ($SIF_schoolLocalId)=$dbh->selectrow_array("select val from opl_preference where var='SIF_schoolLocalId'");

        my $found=0;
        if(defined $SIF_zis_url && $SIF_zis_url ne '' ){
            my $s={siteCode=>$site};
            $s->{'schoolLocalId'}=$SIF_schoolLocalId if($SIF_schoolLocalId ne '');
            foreach my $z (@zisList){
                if($z->{'zone'}->{'url'} eq $SIF_zis_url && $z->{'sifInfo'}->{'sourceId'} eq $SIF_sourceId){
                    foreach my $e(@{$z->{'sites'}}){
                        if($site eq $e->{'siteCode'}){
                            $found=1;
                            last;
                        }
                    }
                    if(!$found){
                        push @{$z->{'sites'}},$s;
                        $found=1;
                        last;
                    }
                }
            }
            if(!$found){
            my $z={
                zone=>{ url=>$SIF_zis_url,
                    agentName=>"OPALS SIF Agent"},
                sifInfo=>{version=>$SIF_version,
                        sourceId=>$SIF_sourceId,
                        authLevel=>0,
                        encryptLevel=>0,
                        sourceName=>"OPALS SIF Agent",
                        },
                sites=>[$s]        
                };
            push @zisList,$z;

            }
        }
    }
    else{
        foreach my $z (@zisList){
            my $arr=[];
            foreach my $e(@{$z->{'sites'}}){
                 if($site ne $e->{'siteCode'}){
                       push @$arr,$e;
                 }
            }
            $z->{'sites'}=$arr;

        }
    }
}


#------------------------------------------------------------------------------
sub loadSifsrvCfg{
   my $sifSrvCfg={
       synFreq =>300,
       subscription=>["StudentPersonal","RoomInfo","StudentSchoolEnrollment","StaffPersonal","SchoolInfo"]
   };
   my $cfg=loadConfig("/etc/opals/SIF.conf");
   if(defined $cfg){
       if(defined $cfg->{'subscription'} && $cfg->{'subscription'} ne ''){
            my $subscription=[];
            foreach my $objName(split(",",$cfg->{'subscription'} )){
                $objName=~ s/^\s+|\s+$//g;
                push @$subscription,$objName;
            }
            $sifSrvCfg->{'subscription'}=$subscription if(scalar(@$subscription)>0)
       }
       if(defined $cfg->{'syncFrequency'} && $cfg->{'syncFrequency'} =~ m/(\d+)/  ){
            my $freq =$1;
            $freq =~ s/^[ 0]+//g;
            if($freq >0){
                $sifSrvCfg->{'synFreq'}=int($freq);

            }
       }
   }
   return $sifSrvCfg;
}
#------------------------------------------------------------------------------
sub loadConfig {
    my ($configFile) = @_;

    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 getDbh {
    my($siteCode) =@_;
    my $config=loadConfig("/etc/opals/conf/$siteCode");
    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);
    my $dbh = DBI->connect($dsn, $db_user, $db_password);

    my ($TZ) = $dbh->selectrow_array(<<_STH_);
select val
from   opl_preference
where  var='timezone'
_STH_

    if ($TZ) {
        $ENV{'TZ'} = $TZ;
        $dbh->do("set time_zone='$TZ'");
    }

    return $dbh;
#    $g_context->{'dbh'} = DBI->connect($dsn, $db_user, $db_password);
#
#    return $g_context->{'dbh'};
}

#------------------------------------------------------------------------------
