<?php
header("Access-Control-Allow-Origin: *");
// for linux user, you might need  chmod 0777 smartctl_x86_64 &&  chmod 0777 smartctl_armv6
// you need smartctl 7.0.0 above to support JSON output

$ok = false;
preg_match('/smartmontools release ([0-9])\.([0-9])/', shell_exec(' sudo smartctl --version | grep "release"'), $filter);
if(isset($filter[1])){
	if($filter[1] > 6){
		$binary = "smartctl";
		$ok = true;
	}
}

if($ok == false){
	if(strcasecmp(substr(PHP_OS, 0, 3), 'WIN') == 0){
		$binary = "./bin/smartctl";
	}else{
		if(strpos(exec('uname -m'), 'arm') !== false){
			$binary = "./smartctl_armv6";
		}else{
			$binary = "./smartctl_x86_64";
		}
	}
}
if($_GET["opr"] == "scan"){
	echo shell_exec($binary.' --scan -j');
	//echo file_get_contents("scan.txt");
}else if($_GET["opr"] == "info"){
	//smartctl -H /dev/sdb -j
	//echo shell_exec('sudo ./smartctl_i386 -i '.$_GET["drive"].' -j -A');
	$DiskData = [];
    $DiskData["model_name"] = "Unknown";
    $DiskData["user_capacity"]["bytes"] = 0;
    $DiskData["temperature"]["current"] = 0;
    $DiskData["model_family"] = "Unknown";
    $DiskData["device"]["info_name"] = "Unknown";
    $DiskData["firmware_version"] = "0.0.0";
    $DiskData["serial_number"] = "Unknown";
	$DiskData["power_on_time"]["hours"] = 0;
    $DiskData["power_cycle_count"] = 0;
    $DiskData["sata_version"]["string"] = "Unknown";
    $DiskData["interface_speed"]["current"]["string"] = "Unknown";
	$DiskData["interface_speed"]["max"]["string"] = "Unknown";
    $DiskData["ata_version"]["string"] = "Unknown";
	$DiskData["rotation_rate"] = 0;
    $DiskData["device"]["protocol"] = "Unknown";
	$DiskData["ata_smart_attributes"]["table"] = [];
	
	$execResult = json_decode(shell_exec('sudo '.$binary.' -i '.$_GET["drive"].' -j -A'),true);
	//$execResult = json_decode(file_get_contents(explode("/",$_GET["drive"])[2].".txt"),true);
	if($execResult == null){
		die("");
	}
    $DiskData = array_merge($DiskData,$execResult);
    echo json_encode($DiskData);
}
?>