<?php

ApplicationSettings::RegisterDefaultSetting("status", "disks", "/");

class Status extends Controller {

	public function Index() {
		$vars=array();

		$vars['disks']=array();
		$disks=explode(",", ApplicationSettings::GetSetting("status", "disks"));
		foreach ($disks as $disk) {
			$vars['disks'][]=new DiskInfo($disk);
		}

		return new View("Status/index.view", $vars);
	}

	public function GetSystemInfo() {
		$info=new stdClass();
		
		if (function_exists("sys_getloadavg"))
			$info->load=sys_getloadavg();
		else
			$info->load=array(rand(0, 4), rand(0, 4), rand(0, 4));
		
		$data=explode("\n", trim(file_get_contents("/proc/meminfo")));
		$memInfo=array();
		foreach ($data as $line) {
			list($key, $val)=explode(":", $line);
			$memInfo[$key]=explode(" ", trim($val))[0];
		}

		$info->memFree=$memInfo['MemFree'];
		$info->memTotal=$memInfo['MemTotal'];
		$info->memUsage=(($memInfo['MemTotal']-$memInfo['MemFree'])/$memInfo['MemTotal'])*100;
		
		$cpuTemp=(int)file_get_contents("/sys/class/thermal/thermal_zone0/temp");
		$info->cpuTemp=$cpuTemp/1000;
		
		return json_encode($info);
	}

	public function GetProcesses() {
		$lines=array();
		exec("ps aux", $lines);
		if (count($lines)==0) {
			$output=file_get_contents("/ps.txt");
			$output=htmlspecialchars($output);
			$lines=explode("\n", $output);
		}
		$header=preg_split('/\s+/', $lines[0]);
		for ($i=0; $i<count($lines); $i++)
			$lines[$i]=preg_split('/\s+/', $lines[$i], count($header));
		return json_encode($lines);
	}

	public function GetUptime() {
		$uptime=exec("uptime");
		if ($uptime=="")
			$uptime="17:16:18 up 22 days,  9:39,  1 user,  load average: 2.10, 2.18, 2.33";
		$matches=array();
		preg_match("/(\d+) days,\s*(\d*):(\d*)/", $uptime, $matches);
		$obj=new stdClass();
		$obj->days=$matches[1];
		$obj->hours=$matches[2];
		$obj->minutes=$matches[3];
		
		return json_encode($obj);
	}
}
