<?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 {

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

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

	public function GetDesktopMonitor($params) {
		if (!isset($params['file']))
			$params['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=shell_exec($ipCommand);
		
		if ($ipAddress=="")
			return "Waiting for PC to wake<script>GetHWM(5000)</script>";
		
		ob_start();
		$ch=curl_init("http://$ipAddress:$hwmPort/".$params['file']);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 500);
		curl_setopt($ch, CURLOPT_TIMEOUT, 500);
		$output=curl_exec($ch);
		$html=ob_get_clean();
		
		if ($output===true){
			if ($params['file']==""){ // remove tags we don't want from html page
				$html=str_replace(array("<html>","</html>","<body>","</body>","<head>","</head>"),"",$html);
				$html=preg_replace("/<title>(.*)<\/title>/im","",$html);
			}
			return $html;
		} else
			return "Waiting for hardware monitor to start<script>GetHWM(1000)</script>";
	}

}
