<?php
//vim: ts=2 sw=2

include_once "sdcard/cpt/app/base_controller.php";

class UpgradeFirmwareController extends BaseController {
  protected function signinRequired() {
    return true;
  }

  protected function adminRequired() {
    return true;
  }
  
  protected function genResponse() {
    $file = $_FILES['firmwareFile'];
    $tempPath = $file['tmp_name'];
    $name = $file['name'];
    
    //check if firmware file is too small
    $fileSize = filesize($tempPath);
    if ($fileSize < 1*1024*1024) {
        echo "The uploaded file size is invalid.";
        return;
    }
    $fwPath = firmwareUpgradePath();
    if (!is_null($fwPath)) {
        //check if enough space left 
        $freeSpace = disk_free_space($fwPath);
        // since the php temp folder for uploaded file and firmware target 
        // file(/tmp/firmware) are in memory, the check here is different 
        // compared to browser side
        //
        // GOTCHA: there will be 2 copies of firmware file stored in memory,
        // and one copy will be released when the current request worker is
        // done. so if we require 2 firmware free space available before
        // flashing, we only need to check 1*fileSize, since another fileSize
        // mem will be released at end of this request. the logic only make 
        // sense in FW platform, FS don't use mem to store firmware file
        if ($freeSpace < 1*$fileSize) {
            echo "No enough space left.";
            return;
        }

        $dstPath = build_file_path($fwPath, basename($name));
        if ($tempPath != $dstPath)
          move_uploaded_file($tempPath, $dstPath);

        sync();
        echo "SUCCESS: File '$name' is uploaded sucessfully.";
    }
    else {
        echo "This platform is not supported.";
    }
  }
  
  protected function doAjaxPost() {
    $this->genResponse();
    die();
  }

  protected function doGet() {
    //clean up old files 
    $upgradePath = firmwareUpgradePath();
    $fileList = array("fw140.tar.gz", "BaseCommL", "FirmwareUpgradeL", "fw08mcu.bin", "fw14mcu.bin", "fwledL", "TestCommL", "fwcore.bin", "BaseCommO", "FirmwareUpgradeO", "fwledO", "TestCommO", "fwrebootL", "fwrebootO", "fw140.md5");
    foreach($fileList as $file) {
      $path = build_file_path($upgradePath, $file);
      if (file_exists($path))
        unlink($path)
    }

    `rm -rf /tmp/firmware`
    `mkdir /tmp/firmware`
  }

  protected function doPost() {
    echo '<textarea>';
    $this->genResponse();
    echo '</textarea>';
    die();
  }
}

$controller = new UpgradeFirmwareController();
$controller->run();

function readString($file, $network, $str)
{
	$reading = fopen($file, 'r');
	$fnet = 0;
	
	while (!feof($reading))
	{
		$line = fgets($reading);
		if(stristr($line, $network))
		{
			$fnet = 1;
		}
		elseif(($fnet == 1) && (strstr($line, $str)))
		{
			$result = str_replace($str, "", $line);
			$tmp_result = $result = trim($result);	//Remove whitespace from front and back
			$result = str_replace("'", "", $result);
			break;
		}
	}
	fclose($reading);
	return $result;
}

$fwconfig = "/mnt/fw.config";
$retainSettings = readString($fwconfig, "EthernetPort", "RetainSettings:");
if ($retainSettings == "1")
{
	$retainSettings = "checked";
}
else
{
	$retainSettings = "";
}

$svmversion = readString("/mnt/fw.config", "NetworkResetCount", "SvmVersion:");
$releasedate = readString("/mnt/fw.config", "Model", "ReleaseDate:");
$mcuversion = readString("/mnt/fw.config", "SvmVersion", "McuVersion:");
?>

<!doctype html>
<html lang="en">
<head>
    <eta charset="utf-8">
    <eta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>EasyIO FW : Firmware Upgrade</title>

    <link rel="stylesheet" href="css/pure-min.css">
    <!--[if lte IE 8]>
        <link rel="stylesheet" href="css/grids-responsive-old-ie-min.css">
    <![endif]-->
    <!--[if gt IE 8]><!-->
        <link rel="stylesheet" href="css/grids-responsive-min.css">
    <!--<![endif]-->

    <link rel="stylesheet" href="css/cssprogress.min.css">
    <link rel="stylesheet" href="css/utility.css">
</head>

<body>
  <div id="layout">
    <div class="pure-g">
      <div class="pure-u-2-24"></div>
      <div id="firmware_upgrade_panel" class="pure-u-20-24">
        <div style="margin-bottom: 80px;">
          <h1 style="font-family:arial, helvetica, sans-serif; font-size:300%; text-align:center; width:100%;"><a href="/utility.php" style="text-decoration:none">
					<span style="color: blue">Easy</span><span style="color: red">IO</span><span style="color: black"> FW : Firmware Upgrade</span></a></h1>
        </div>

				<div id="detailsDiv" style="width:100%; margin-bottom: 50px; color:#337ab7;">
					<table align="center" style="width:100%; margin:0;"><tr>
					<td style="width:33.33%; text-align:center;"> Firmware Version : <?php echo $svmversion ?> </td>
					<td style="width:33.33%; text-align:center;"> Build Date : <?php echo $releasedate ?> </td>
					<td style="width:33.33%; text-align:center;"> MCU Firmware Version : <?php echo $mcuversion ?> </td>
					</tr></table>
				</div>
				
        <form id="firmware_upgrade_form" class="pure-form" action="firmware.php" method="post" enctype="multipart/form-data">
          <fieldset>
            <div class="alert hide"></div>

            <label for="inputFirmwareFile">Firmware File:</label>
            <input type="file" id="inputFirmwareFile" name="firmwareFile">
            <div id="firmware-upgrade-progress" class="cssProgress hide">
              <div class="progress2">
                <div class="cssProgress-bar cssProgress-success cssProgress-stripes" data-percent='0' >
                  <span class="cssProgress-label">0%</span>
                </div>
              </div>
            </div>
            <button type="submit" class="pure-button pure-button-primary upgrade-button" disabled>Upgrade</button>
          </fieldset>
        </form>

      </div>
      <div class="pure-u-2-24"></div>
			
			<div class="pure-u-2-24"></div>
			<div id="firmware_retain_settings" class="pure-u-20-24">
				<form id="retain_settings">
				<input type="checkbox" id="retainsettings" <?php echo $retainSettings ?> onclick="retainSettings();"></input>
				<label for="retainSettings"> Retain Network Settings </label>
				</form>
			</div>
			<div class="pure-u-2-24"></div>
    </div>

  </div>

  <script language="javascript" type="text/javascript">
    window.firmwareFileName = '<?php echo firmwareFileName() ?>';
    window.freeDiskSpace = Number.parseInt('<?php echo disk_free_space(firmwareUpgradePath()) ?>');
  </script>

  <script type="text/javascript" src="js/jquery-1.10.0.min.js"></script>
  <script type="text/javascript" src="js/underscore-min.js"></script>
  <script type="text/javascript" src="js/underscore.string.min.js"></script>
  <script type="text/javascript" src="js/spin.min.js"></script>
  <script type="text/javascript" src="js/jquery.form.min.js"></script>

  <script type="text/javascript" src="js/utility.js"></script>

	<script type="text/javascript">
		function retainSettings()
		{
			var temp = document.getElementById("retainsettings").checked;
			
			var xmlhttp = new XMLHttpRequest();
			xmlhttp.open("POST", "helper.php", true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.send("mode=retainsettings&retainsettings=" + temp);
		}
	</script>
</body>
</html>