#!/opt/Guardian/Admin/php/bin/php
<?php
// Copyright (c) 2006 Canon System Solutions Inc. All rights reserved.
// GUARDIANSUITE ݡȥץ (GUARDIANSUITE V4.0ʾ)

require_once "rpc_server_funcs.php";
require_once "rpc_lib.php";

$servers = array(ADM, MAIL, WEB, PC);

// -----------------------------------------------------

// ɽ
function usage($msg = '') {
	if (!empty($msg)) {
		print "$msg \n";
	}
    print "Usage: " . basename($_SERVER["PHP_SELF"]) . " [options] \n";
    print "  --adm   : Admin Server. \n";
    print "  --mail  : Mail Server. \n";
    print "  --web   : Web Server. \n";
    print "  --pc    : Pc Server. \n";
	print "  --log YYYYMMDD YYYYMMDD: systemlog file span. \n";
    print "  --d [dir] : output direcotory. \n";
    print "  --server: Show This Server Info. \n";
    exit(1);
}
// -----------------------------------------------------

// main
$us = posix_getpwuid(posix_geteuid());
if ('root' != strtolower($us['name'])) {
	errex('You need to login as root.');
}

if (count($argv) == 1) {
	usage();
}
// options
array_shift($argv);
$opts = array();
for($i=0; $i<count($argv); $i++) {
	$opt = preg_replace("/-/", "", $argv[$i]);
	switch($opt) {
		case ADM:
		case MAIL:
		case WEB:
		case PC:
		case 'server':
			$opts[$opt] = true;
			break;
		case 'log':
			$ymd1 = $argv[($i+1)];
			if (preg_match("/\d{8}/", $ymd1)) {
				$i++;
				if (preg_match("/\d{8}/", $argv[($i+1)])) {
					$ymd2 = $argv[++$i];
				} else {
					$ymd2 = $ymd1;
				}
			} else {
				$ymd1 = date('Ymd');
				$ymd2 = $ymd1;
			}
			$opts[$opt] = array($ymd1, $ymd2);
			break;
		case 'd':
			$opts[$opt] = $argv[++$i];
			break;
		default:
			break;
	}
}

$types = get_servertypes();

// --server:
if ($opts['server']) {
	show_thisinfo();
	exit(0);
}

// check -----------------------------------------

if (!$opts[ADM] && !$opts[MAIL] && !$opts[WEB] && !$opts[PC]) {
	errex("you must specify server option.");
}
// -d ꤬ʤAdmin/tmp/YYYYMMDD-HHiiss.tar.gz
if (isset($opts['d'])) {
	$dir = $opts['d'];
	if (!is_dir($dir)) {
		errex("no exists directory.(" . $opts['d'] . ")");
	}
	if (!preg_match("/\/$/", $dir)) $dir .= '/';
	$opts['d'] = $dir;
} else {
	$opts['d'] = TMP_DIR;
}

// ϥե ---------------------------------
$opts['d'] .= date('Ymd-His') . '.tar';
if (file_exists($opts['d'])) {
	errex("file exists " . $opts['d']);
}

// С󡦥ե -------------------

// adm, mail, web, pc
$info_files = array();

// ȥǥ쥯ȥư
$TMPDIR = TMP_DIR . 'grdninfo.' . date('Ymd-His') . '/';

if (!mkdir_tree($TMPDIR)) {
	errex("make directory $TMPDIR");
}
$cwd = getcwd();
chdir($TMPDIR);
$startd = ($opts['log']) ? $opts['log'][0] : null;
$endd   = ($opts['log']) ? $opts['log'][1] : null;
$apachepath = '/' . preg_quote(ADMIN_BASE . 'logs', '/') . '/';
foreach($servers as $s) {
	if ($opts[$s]) {
		if (!$types[$s]) errex("$s not in this server.");

		// С
		$info = guts_get_server_info($s);
		$infof = $TMPDIR . $s . ".txt";
		$fp = fopen($infof, "w");
		if ($fp === false) errex("failed open file $infof");
		fputs($fp, $info);
		fclose($fp);
		$info_files[] = $infof;

		// ȥǥ쥯ȥ˥ե򽸤
		if ($opts['log']) {
			$log_list = guts_get_loglist($s, $startd, $endd);
			if (is_array($log_list) && count($log_list) > 0) {
                if ($s != ADM) {
					$logdir = $TMPDIR . $s . '/';
					if (!mkdir_tree($logdir)) {
						cleanup($TMPDIR);
						errex("make directory $logdir");
					}
				}
				$apachedir = $TMPDIR . 'httpd/';
				if (!is_dir($apachedir) &&  !mkdir_tree($apachedir)) {
					cleanup($TMPDIR);
					errex("make directory $apachedir");
				}
				foreach($log_list as $log_file) {
					$todir = preg_match($apachepath, $log_file) ? $apachedir : $logdir;
					if (!su_cp($log_file, $todir)) {
						print "failed: cp $log_file $todir";
					}
					unset($todir);
				}
			}
		}
		// СϸСо
		if ($s == ADM) {
			$list = getGDNServerList();
			foreach($list as $s) {
				// info,log򸡺С
				$args = array($s->id, $s->type, $startd, $endd);
				$out = guts_call_phpfunc_output($s, "guts_get_filterdata", null, $args);
				if (preg_match("/^error/", $out)) {
					cleanup($TMPDIR);
					errex($out);
				}
				// ե
				$f = $TMPDIR . basename($out);
				if (!guts_get_file($s, $out, $f)) {
					cleanup($TMPDIR);
					errex("get file[$out] by server id " . $s->id);
				}
				// ե
				if (!guts_exec_cmd($s, GRDN_BASE . "local/bin/rm $out", true)) {
					guts_log_warn("rm $out at [$s->id] server - guts_support_info");
				}

				// Ÿ
				$cmd = CMD_GTAR_C . " -xf $f 2>/dev/null";	
				exec($cmd, $out, $rtn);
				if ($rtn != 0) {
					cleanup($TMPDIR);
					errex($cmd);
				}
				su_rm($f);
				unset($out, $f);
			}
		}
		unset($info, $infof, $fp, $out, $rtn, $logdir);
	}
}

// TAR
$tar = $opts['d'];
$bn = basename($TMPDIR);
chdir(dirname(getcwd()));

$cmd = CMD_GTAR_C . " -cf $tar $bn 2>/dev/null";
exec($cmd, $out, $rtn);
if ($rtn != 0) {
	cleanup($TMPDIR);
	errex($cmd);
}
// ZIP
$cmd = GRDN_BASE . 'local/bin/gzip ' . $tar . ' 2>/dev/null';
exec($cmd, $out, $rtn);
if ($rtn != 0) {
	foreach($info_files as $f) su_rm($f);
	errex($cmd);
}
chdir($cwd);
// CleanUp
cleanup($TMPDIR);


// ե̾ɽ
pri($opts['d'] . '.gz');

// finish
exit(0);

// task -----------------------------------------------------

// show this server info
function show_thisinfo() {
	global $types;
	pri('# ThisServerInfo');
	if ($types[ADM]) {
		pri ('-- ADM Server');
		$list = getGDNServerList();
		foreach($list as $s) {
			pri(TAB . "$s->id($s->type) $s->hostname");
		}
	}
	if ($types[MAIL]) pri ('-- MAIL Server');
	if ($types[WEB])  pri ('-- WEB Server');
	if ($types[PC])   pri ('-- PC Server');
}
function cleanup($dir) {
	global $cwd;
	chdir($cwd);
	return su_exec("rm -rf $dir");
}
// -----------------------------------------------------

// 顼
function errex($s) {
	print "error: " . $s . "\n";
    exit(-1);
}
function pri($msg) {
	print $msg . "\n";
}
?>
