<?php

ApplicationSettings::RegisterDefaultSetting("desktop", "mac_address", "");
ApplicationSettings::RegisterDefaultSetting("desktop", "wake_command", "wakeonlan");
ApplicationSettings::RegisterDefaultSetting("desktop", "ip_command", "/usr/sbin/arp -n | grep <mac> | awk '{print $1}'");
ApplicationSettings::RegisterDefaultSetting("desktop", "hardware_monitor_port", "8085");

class Desktop extends Controller {

	public function Index() {
		return new View("Desktop/index.view");
	}

	public function Wake() {
		$command=ApplicationSettings::GetSetting("desktop", "wake_command");
		$mac=ApplicationSettings::GetSetting("desktop", "mac_address");
		return $output=shell_exec(sprintf("%s %s", $command, $mac));
	}

	public function GetDesktopMonitor($file) {
		if (!isset($file))
			$file="";
		
		$ipCommand=ApplicationSettings::GetSetting("desktop", "ip_command");
		$mac=ApplicationSettings::GetSetting("desktop", "mac_address");
		$hwmPort=ApplicationSettings::GetSetting("desktop", "hardware_monitor_port");
		$ipCommand=str_replace("<mac>", $mac, $ipCommand);
		$ipAddress=trim(shell_exec($ipCommand));
		
		if ($ipAddress=="")
			return "Waiting for PC to wake<script>GetHWM(5000)</script>";
		
		ob_start();
		$ch=curl_init("http://$ipAddress:$hwmPort/".$file);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 500);
		curl_setopt($ch, CURLOPT_TIMEOUT, 500);
		$output=curl_exec($ch);
		$html=ob_get_clean();
		
		if ($output===true){
			switch ($file) {
				case "": // remove tags we don't want from html page
					preg_match("@<head>(.*?)</head>@ims", $html,$matches);
					$head=preg_replace("@\b(href|src)\b=(\"|')(.*?)(\"|')@", "$1=$2/desktop/GetDesktopMonitor?file=$3$4", $matches[1]);
					$html=preg_replace("@<head>.*?</head>@ims", $head, $html);
					$html=str_replace(array("<html>","</html>","<body>","</body>","<head>","</head>"),"",$html);
					$html=preg_replace("@<title>(.*?)</title>@im","",$html);
					break;
				case "js/ohm_web.js":
					$html=str_replace("data.json","/desktop/GetDesktopMonitor?file=data.json",$html);
					break;
				case "data.json":
					$html=preg_replace('@"ImageURL": "(.*?)"@', '"ImageURL": "/desktop/GetDesktopMonitor?file=$1"', $html);
					break;
				case "css/jquery.treeTable.css":
				case "css/custom-theme/jquery-ui-1.8.16.custom.css":
				case "css/ohm_web.css":
					$html=preg_replace('@url\(("?.*?"?)\)@','url("/desktop/GetDesktopMonitor?file=$1")',$html);
					break;
			}
			return $html;
		} else
			return "Waiting for hardware monitor to start<script>GetHWM(1000)</script>";
	}
}
