#!/opt/Guardian/Admin/php/bin/php
<?php
/* 2005.07.11 % -> KB ѹ */
/* 2005.08.29 KB -> MB ѹ */

require_once "util.php";

function usage() {
	print "Usage: " . basename($_SERVER["PHP_SELF"]) . " [options] \n";
	print "  -f : config file path. \n";
	print "  -n : check only (display remove target file). \n";
	exit(1);
}

/* main */

$conf = null;
$check = false;

if (count($argv) == 1) usage();

array_shift($argv);
while(($opt = array_shift($argv)) != null) {
	if ($opt{0} != '-')
		break;
	switch($opt{1}) {
	case 'f':
		$conf = array_shift($argv);
		break;
	case 'n':
		$check = true;
		break;
	default:
		usage();
		break;
	}
}
/* new */
$logger = new Logger($conf, $check);

/* Ƹ */
if (!$logger->isValid(&$err)) {
	print $err . "\n";
	exit(-1);
}

/*  */
if (!$logger->execute(&$err)) {
	print $err . "\n";
	exit(-1);
}
print "successful. \n";
exit(0);


/*
 * Class Logger
 */
class Logger {
	var $conf;		// ե
	var $check;		// åΤ
	var $dir;		// ¸ǥ쥯ȥ
	var	$days;		// ¸
	var $max_size;	// ¥ 
	var $DISK_FREE;

	/* 󥹥ȥ饯 */
	function Logger($conf, $check) {
		$this->conf = $conf;
		$this->check = $check;

		// localޥɤ˽ 2005.08.29
		// KB -> MB ˽ 2005.80.29
		$this->DISK_FREE =  GRDN_BASE . "local/bin/df -kP ";
		// $this->DISK_USAGE = GRDN_BASE . "local/bin/du -ks ";
		$this->DISK_USAGE = GRDN_BASE . "local/bin/du -ms ";

//		$os_type = trim(shell_exec('/bin/uname'));
//		if ('SunOS' == $os_type) {
//			$this->DISK_FREE = "/usr/bin/df -kl ";
//			$this->DISK_USAGE = "/usr/bin/du -ksd ";
//		} else if ('Linux' == $os_type) {
//			$this->DISK_FREE = "/bin/df -kl ";
//			$this->DISK_USAGE = "/usr/bin/du -ksx ";
//		} else if ('HP-UX' == $os_type) {
//			$this->DISK_FREE = GRDN_BASE . "local/bin/df -hl ";
//		}
	}

	/*  */
	function execute($err) {
		/* ͼ */

		// ¸
		$this->days = $this->getConfValue('Expire', 'WebLog', &$err);
		if ($this->days === false) return false;
		if ($this->days == null) $this->days = 180;
		print "Save Days:" . $this->days . "\n";

		// ¥
		$max = $this->getConfValue('Expire', 'MaxWebLogSize', &$err);
/*
		if ($max) $max = substr($max, 0 , strlen($max) - 1);
*/
		$this->max_size = $max;
		if ($this->max_size === false) return false;
		print "Max Size:" . $this->max_size . "MB \n";

		/* Webǥ쥯ȥ */
		$this->dir = $this->getConfValue('Directories', 'WebLogDirectory', &$err);
// 2005.08.23
//		if (!$this->dir) { 
		if ($this->dir == '') { 
			$this->dir = '/var/opt/Guardian/WG/';
		}
		if (!preg_match("/\/$/", $this->dir)) {
			$this->dir = $this->dir . "/";
		}

		print "LogDirectory: $this->dir \n";

		/* Ķǥ쥯ȥκ */
		if ($this->days && $this->days > 0) {
			if (!$this->removeExpire(&$err)) {
				return false;
			}
		}

		/*
		 * ¥СΥǥ쥯ȥ
		 * ¥ʲˤʤޤǷ֤
		 */
		if ($this->max_size && $this->max_size > 0) {
//			$df = $this->getDiskFree(&$err);
			$du = $this->getDiskUsage(&$err);
//			if (!$df) return false;
			if (!$du) return false;

			if ($this->check) {
//				if ($df > $this->max_size) {
				if ($du > $this->max_size) {
					print "over MaxSize(now: $du MB). \n";
				} else {
					print "not over MaxSize(now: $du MB). \n";
				}
			} else {
//				while ($df > $this->max_size) {
				while ($du > $this->max_size) {
					$rtn = $this->removeOldestDir(&$err);
					if ($rtn === false && $err) {
						return false;
					} elseif ($rtn === false) {
						return true;
					}
					unset($df);
					unset($du);
//					$df = $this->getDiskFree(&$err);
					$du = $this->getDiskUsage(&$err);
					if (!$du && $err) {
						return false;
					} elseif (!$du) {
						break;
					}
				}
			}
		}
		return true;
	}

	/* Ķǥ쥯ȥκ */
	function removeExpire($err) {
		if (!is_dir($this->dir)) {
			return true;
		}
		foreach(glob($this->dir . "*/*/*") as $dirname) {
			if (preg_match("/^.*(\d{4})\/(\d{2})\/(\d{2})$/", $dirname, $v)) {
				$ymd = $v[1] . $v[2] . $v[3];
			} else {
				continue;
			}
			// о
			if ($this->isRemoveDir($ymd)) {
				if (!$this->check) {
					if (!$this->removeDir($dirname, &$err)) {
						return false;
					}
					print "removed(old) " . $dirname . ".\n";
				} else {
					print "Remove Target : $dirname \n";
				}
			}
		}
		return true;
	}

	/*
	 * ǥ쥯ȥΰָŤեǥ쥯ȥޤ
	 * return : false - ǥ쥯ȥ꤬ʤե뤬ʤ
	 */
	function removeOldestDir($err) {
		$dirlist;
		if (!is_dir($this->dir)) {
			return false;
		}
		foreach(glob($this->dir . "*/*/*") as $dirname) {
			if (!preg_match("/^.*(\d{4})\/(\d{2})\/(\d{2})$/", $dirname, $v)) {
				continue;
			}
			$dirlist[] = $dirname;
		}
		if (count($dirlist) > 0) {
			sort($dirlist);
			$dir = array_shift($dirlist);
			$rtn = $this->removeDir($dir, &$err);	
			print "removed(max) " . $dir . ".\n";
			return $rtn;
		} else {
			print "Over dir size, But not oldest file. \n";
			return false;
		}
		return true;
	}

	/* եǥ쥯ȥ */
	function removeDir($dir, $err) {
		if (!rmdir_tree($dir, true)) {
			$err = "failed remove dir ($dir).";
			return false;
		}
		// ƥǥ쥯ȥ()⤬ˤʤäϿƥǥ쥯ȥ
		$parent = dirname($dir);
		if ($this->isEmptyDir($parent)) {
			rmdir_tree($parent, true);
		}
		// ƥǥ쥯ȥ(ǯ)⤬ˤʤäϿƥǥ쥯ȥ
		$gparent = dirname($parent);
		if ($this->isEmptyDir($gparent)) {
			rmdir_tree($gparent, true);
		}
		return true;
	}

	/* ǥ쥯ȥ꤬Ǥ뤫ɤȽ */
	function isEmptyDir($path) {
// 2005.08.23
//		if (!$path || !is_dir($path)) {
		if ($path == '' || !is_dir($path)) {
			return false;
		}
		$rtn = true;
		$df = opendir($path);
		if (!$df) {
			print "error open dir ($path). \n";
			return false;
		}
		while($file = readdir($df)) {
			if ($file != "." && $file != "..") {
				$rtn = false;
				break;
			}
		}
		closedir($df);
		return $rtn;
	}

	/* ϥå */
	function isValid($err) {
		// ե̵ͭ
		if (!file_exists($this->conf)) {
			$err = "file not exits ($this->conf) .";
			return false;
		}
		return true;
	}

	/* ͼ */
	function getConfValue($sec, $key, $err) {
		return ReadServerConfig($key, null, $this->conf, $sec);
	}

	/* ǥ̤μ(%) */
	function getDiskFree($err) {
		$cmd = $this->DISK_FREE . $this->dir;
		exec($cmd, $out, $rtn);
		if ($rtn != 0) {
			$err = "exec error ($cmd).";
			return false;
		}
		$v = preg_split("/\s+/", $out[1]);
		return substr(trim($v[4]), 0, strlen(trim($v[4])) - 1);
	}

	/* ǥ̤μ(MB) */
	function getDiskUsage($err) {
		$cmd = $this->DISK_USAGE . $this->dir;
		exec($cmd, $out, $rtn);
		if ($rtn != 0) {
			$err = "exec error ($cmd).";
			return false;
		}
		$v = preg_split("/\t+/", $out[0]);
		return trim($v[0]);
	}

	/* ¸Ķκоݥǥ쥯ȥ꤫ɤȽ */
	function isRemoveDir($ymd) {
		if (!$ymd || strlen($ymd) != 8) {
			return false;
		}
		$y = substr($ymd, 0, 4);
		$m = substr($ymd, 4, 2);
		$d = substr($ymd, 6, 2);

		$ymd_t = mktime(0, 0, 0, $m, $d, $y);
		$chk_t = $this->days * 24 * 60 * 60;
		// 2005.08.29
		// $now_t = time();
        $now_y = date("Y", time());
        $now_m = date("m", time());
        $now_d = date("d", time());
        $now_t = mktime(0, 0, 0, $now_m, $now_d, $now_y);

		return ($now_t - $ymd_t > $chk_t);
	}
}
?>
