#!/opt/Guardian/Admin/php/bin/php
<?php
// Copyright(c) 2007 CANON SYSTEM SOLUTIONS INC. All rights reserved.
// 塼顼֤μ¹Գǧcron
//   - 󥹥ȡ顼¹Ԥ륵֥ץ
//   - ζ̤ʤ̤Ѳǽ
mb_internal_encoding("EUC-JP");
mb_http_output("EUC-JP");
clearstatcache();   //statå奯ꥢ

//ޥ
$cat_cmd = '/opt/Guardian/local/bin/cat';
$crn_cmd = '/usr/bin/crontab';

//ե
$crn_fil = '/var/tmp/crontab_gsuite.tmp';

//OS
if (trim(shell_exec('/bin/uname')) == 'SunOS')
     $isSunOS = true;
else $isSunOS = false;

$Dmode = false;     //ǥХå⡼
$Smode = true;      //ȥ⡼
$Rmode = true;      //ꥹȥ⡼($Smode = faleͭ)

array_shift($argv);
while (($opt = array_shift($argv)) != null) switch ($opt) {
    case '-d':
    case '--debug':
        $Dmode = true;
        break;
    case '-e':
    case '--end':
        $Smode = false;
        break;
    case '-n':
    case '--nores':
        $Rmode = false;
        break;
    default:
        fwrite(STDERR, "Error: unknown option (" . $opt . "?)\n");
    case '-h':
    case '--help':
        usage();
}

if (!$Smode) {  //⡼(end) crontab򸵤᤹
    if ($Dmode) var_dump($crn_fil);

    if (!is_readable($crn_fil) || filesize($crn_fil) <= 0) {
        fwrite(STDERR, "ERR: illegal backuped crontab setting.\n");
        exit(1);
    }
    if (!$Rmode) {
        @unlink($crn_fil);
        exit(0);
    }

    $cmd = sprintf("(%s %s | %s%s)", $cat_cmd, $crn_fil, $crn_cmd, $isSunOS? '': ' -') . ' 2>/dev/null';
    if ($Dmode) var_dump($cmd);
    else {
        $res = shell_exec($cmd);
        @unlink($crn_fil);
    }

    exit(0);
}

//⡼(start) 
//crontab򥳥ȥȡХåå
$cmd = $crn_cmd . ' -l 2>/dev/null';
exec($cmd, $out, $rtn);
if ($rtn != 0 || count($out) <= 0) {
    fwrite(STDERR, "ERR: cannot get crrent crontab setting.\n");
    exit(1);
}

if ($Dmode) var_dump($crn_fil);
else {
    if (($fp = fopen($crn_fil, 'w')) === false) {
        fwrite(STDERR, "ERR: cannot open backup file for crontab.\n");
        exit(1);
    }
}

$cmd = $crn_cmd;
if (!$isSunOS) $cmd .= ' -';
$cmd .= ' >/dev/null 2>&1';

if ($Dmode) var_dump($cmd);
else {
    if (($pp = popen($cmd, 'w')) === false) {
        fwrite(STDERR, "ERR: cannot open process for crontab.\n");
        exit(1);
    }
}

foreach ($out as $line) {
    if (!$isSunOS) {
        if (preg_match("/^# DO NOT EDIT/", $line)) continue;
        if (preg_match("/^# \(.* installed on/", $line)) continue;
        if (preg_match("/^# \(Cron version --/", $line)) continue;
    }
    if (preg_match("/\/opt\/Guardian\/Admin\/bin\//", $line)) {
        if (preg_match("/^\s*#\s*(.*)$/", $line, $ncl)) {
            $fline = $ncl[1];
            $pline = '#' . $ncl[1];
        } else {
            $fline = $line;
            $pline = '#' . $line;
        }
    } else {
        $fline = $line;
        $pline = $line;
    }
    if ($Dmode) var_dump($fline, $pline);
    else {
        fwrite($fp, $fline . "\n");
        fwrite($pp, $pline . "\n");
    }
}
if (!$Dmode) {
    pclose($pp);
    fclose($fp);
}
unset($cmd, $out, $rtn);

//塼顼֤μ¹Գǧ
$ServI = array( 'A' => array( 'CD1' => '/opt/Guardian/Admin/bin/guts_adminconf',    //С
                              'CD2' => '/opt/Guardian/Admin/bin/guts_servinfo',
                              'PFL' => 'guts_launcher_a.pid' ),
                'C' => array( 'CD1' => '/opt/Guardian/Admin/bin/guts_servconf',     //С
                              'CD2' => '/opt/Guardian/Admin/bin/guts_lic',
                              'PFL' => 'guts_launcher_c.pid' ) );

foreach (array_keys($ServI) as $s) {
    if (!is_executable($ServI[$s]['CD2'])) continue;

    //Сμv41ʹߤ̤ڤʬ
    $cmd = $ServI[$s]['CD2'] . ' -v 2>/dev/null';
    $ver = shell_exec($cmd);
    if (preg_match("/(\d+)\.(\d+)\.(\d+)/", $ver, $v)) {
        $ver = sprintf("%s%s%s", $v[1], $v[2], $v[3]);
        if ($ver < 4100) $ServI[$s]['NEW'] = false;
        else             $ServI[$s]['NEW'] = true;
    } else continue;

    //ǥ쥯ȥμ
    if ($ServI[$s]['NEW']) $ServI[$s]['TMP'] = '/opt/Guardian/Admin/tmp/';
    else {
        $cmd = sprintf("%s -l -sDirectories -kTmpDirectory 2>/dev/null", $ServI[$s]['CD1']);
        exec($cmd, $out, $rtn);
        if ($rtn != 0) $ServI[$s]['TMP'] = '/opt/Guardian/Admin/tmp/';
        else {
            $val = preg_replace("/^\s*\d*\s*:\s*/", "", $out[0]);
            $ServI[$s]['TMP'] = trim($val);
            if ($ServI[$s]['TMP'] != '/' && !preg_match("/\/$/", $ServI[$s]['TMP']))
                $ServI[$s]['TMP'] .= '/';
        }
        unset($cmd, $out, $rtn);
    }
    if ($Dmode) var_dump($ServI[$s]);

    //֤ξ֤ǧ
    if (($fp = @fopen($ServI[$s]['TMP'] . $ServI[$s]['PFL'], 'r')) === false) continue;
    if ($ServI[$s]['NEW']) {
        if (flock($fp, LOCK_SH|LOCK_NB)) {
            //¹ԤƤʤ֡
            fclose($fp);
            continue;
        }
        //¹ξ֡λ
        fclose($fp);
        fwrite(STDOUT, "Running\n");
        exit(0);
    } else {
        $pid = 0;
        while (!feof($fp)) {
            $bf = trim(fgets($fp));
            if (intval($bf) > 0) $pid = intval($bf);
        }
        fclose($fp);
        if ($pid > 0) {
            exec(sprintf("kill -0 %d", $pid) . ' 2>/dev/null', $out, $rtn);
            if ($rtn == 0) {
                //¹ξ֡λ
                fwrite(STDOUT, "Running\n");
                exit(0);
            }
            unset($out, $rtn);
        }
        //¹ԤƤʤ֡
    }
}

//塼顼֤¹ԤƤʤΥݽ
$ServI['A']['RMF'] = array( '.lock.DeliverLog', '.lock.ArchiveLog', '.lock.ManagerLog', '.lock.ScreeningLog',
                            '.lock.ViewerLog', '.lock.ArchiveData', '.lock.ProxyLog', '.lock.PostLog' );

foreach (array_keys($ServI) as $s) {
    if (!array_key_exists('TMP', $ServI[$s])) continue;

    if (file_exists($ServI[$s]['TMP'] . $ServI[$s]['PFL'])) {   //PIDեΥߺ
        if ($Dmode) fwrite(STDOUT, "Delete file --->[" . $ServI[$s]['TMP'] . $ServI[$s]['PFL'] . "]\n");
        else @unlink($ServI[$s]['TMP'] . $ServI[$s]['PFL']);
    }
    if (array_key_exists('RMF', $ServI[$s])) {
        foreach ($ServI[$s]['RMF'] as $f) {
            if (file_exists($ServI[$s]['TMP'] . $f)) {          //åեΥߺ
                if ($Dmode) fwrite(STDOUT, "Delete file --->[" . $ServI[$s]['TMP'] . $f . "]\n");
                else @unlink($ServI[$s]['TMP'] . $f);
            }
        }
    }

    if ($s != 'A' || !array_key_exists('NEW', $ServI[$s])) continue;

    //ǥ쥯ȥμ
    if ($ServI[$s]['NEW']) $ServI[$s]['RES'] = '/opt/Guardian/Admin/etc/admin/server/';
    else {
        $cmd = sprintf("%s -a -sDirectories -kResultDirectory 2>/dev/null", $ServI[$s]['CD1']);
        exec($cmd, $out, $rtn);
        if ($rtn != 0) $ServI[$s]['RES'] = '/opt/Guardian/Admin/etc/admin/server/';
        else {
            $val = preg_replace("/^\s*\d*\s*:\s*/", "", $out[0]);
            $ServI[$s]['RES'] = trim($val);
            if ($ServI[$s]['RES'] != '/' && !preg_match("/\/$/", $ServI[$s]['RES']))
                $ServI[$s]['RES'] .= '/';
        }
        unset($cmd, $out, $rtn);
    }
    if ($Dmode) var_dump($ServI[$s]);

    if (($dp = @opendir($ServI[$s]['RES'])) === false) continue;
    while (($cd = readdir($dp)) !== false) {
        if (!preg_match("/^\d+$/", $cd)) continue;

        if (($cdp = @opendir($ServI[$s]['RES'] . $cd)) === false) continue;
        while (($ccf = readdir($cdp)) !== false) {
            if (preg_match("/\.pid$/", $ccf) || preg_match("/^\.lock\./", $ccf)) {
                //ϿƤ븡С PIDեȥåեΥߺ
                if ($Dmode) fwrite(STDOUT, "Delete file --->[" . $ServI[$s]['RES'] . $cd . '/' . $ccf . "]\n");
                else @unlink($ServI[$s]['RES'] . $cd . '/' . $ccf);
            }
        }
        closedir($cdp);
    }
    closedir($dp);
}

exit(0);

//ˡ
function usage(){
    fwrite(STDERR, "Usage: " . basename($_SERVER['PHP_SELF']) . " [options]\n");
    fwrite(STDERR, " options...\n");
    fwrite(STDERR, "  -d [--debug]: debug mode. display internal parameters detail.\n");
    fwrite(STDERR, "  -e [--end]  : end mode. restore crontab setting.\n");
    fwrite(STDERR, "  -n [--nores]: not restore mode. using with end mode.\n");
    fwrite(STDERR, "  -h [--help] : display this.\n");
    exit(1);
}
