<?php

class SysteminfoController
{
	public static function Run ($argv)
	{
		$infoCtrl = new SysteminfoController();
		echo implode("\r\n", $infoCtrl->Info()) . "\r\n";
	}

	private $patterns;

	public function __construct ()
	{
		$this->patterns = array(
			'Computername' => '/Hostname:\s+([^\n\r]*)/im',
			'Domaene' => '/Dom.ne:\s+([^\n\r]*)/im',
			'IP-Adresse' => '/(LAN-Verbindung|Ethernet\s?\d|Local Area)[^[]*\[01\]:\s([\d\.]+)/im',
			'System' => '/Betriebssystemname:\s+([^\n\r]*)/im',
			'Build' => '/Betriebssystemversion:\s+([^\n\r]*)/im',
			'Installation' => '/Installationsdatum:\s+([^\n\r]*)/im',
			'Prozessor' => '/Prozessor\(en\):[^\[]*\[01\]:\s([^\n\r]+)/im',
			'RAM gesamt' => '/ter physikalischer Speicher:\s+([^\n\r]*)/im',
			'RAM frei' => '/gbarer physikalischer Speicher:\s+([^\n\r]*)/im',
			'Laufzeit' => '/System\w+zeit:\s+([^\n\r]*)/im'
		);
	}

	public function Info ()
	{
		$systemLog = dirname(__FILE__) . "/../../../logs/system.info.log";
		if (file_exists($systemLog) && filemtime($systemLog) + 23 * 60 * 60 > strtotime("now")) {
			$output = file_get_contents($systemLog);
		} else {
			$output = array();
			exec("systeminfo", $output);
			$output = implode("\r\n", $output);
			file_put_contents($systemLog, $output);
		}

		$result = array();
		$match = array();
		foreach ($this->patterns as $name => $p) {
			if (preg_match($p, $output, $match)) {
				$value = array_pop($match);
				$value = str_replace("\xA9", '', $value);
				if ($name == "Laufzeit" && preg_match('/(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)/', $value, $match)) {
					$time = strtotime("now") - mktime($match[4], $match[5], $match[6], $match[2], $match[1], $match[3]);
					$days = floor($time / (24 * 60 * 60));
					$time -= $days * 24 * 60 * 60;
					$hours = floor($time / (60 * 60));
					$time -= $hours * 60 * 60;
					$minutes = $time / 60;
					$value .= sprintf(" (%d Tage, %d Stunden, %d Minuten)", $days, $hours, $minutes);
				}
				$result[] = str_pad($name.":", 15) . $value;
			}
		}


		$disk = substr(dirname(__FILE__), 0, 2);
		$result[] = str_pad("Festplatte " . $disk, 15) . $this->HumanSize(disk_free_space($disk)) . " frei";
		return $result;
	}

	private function HumanSize($bytes)
	{
		$type = array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
		$index = 0;
		while($bytes >= 1024)
		{
			$bytes /= 1024;
			$index++;
		}
		return("" . number_format($bytes, 2, ",", "") . " " . $type[$index]);
	}

}