#!/usr/bin/perl 
use strict;

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($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) {
        # run script
        $opals_conf = $OPALS_CONF_DIR . $s;
        # 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_userImport';
            $ENV{'PERL5LIB'} = $opals_root . '/module';
            $ENV{'OPALS_CONF'} = $opals_conf;
            system($script, $s);



    }
 exit 0;


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

    return $tn;
}
#------------------------------------------------------------------------------
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;
}

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