<? 
/*********************************************************************
 *
 *  Wattmon
 *    
 *  File : flash.cgi
 * 
 *  Description: Flash settings page
 *
 *********************************************************************
 * Company:         Cynergy Software
 *
 * Software License Agreement
 *
 * Copyright (c) 2013 Cynergy Software.  All rights reserved.
 *
 * Cynergy licenses to you the right to use, modify, copy, and 
 * distribute: 
 * (i)  the Software when used on a Wattmon device
 * (ii) the Software on any platform or device for personal use
 *
 * For commercial use please contact us via http://www.wattmon.com
 *
 * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT 
 * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT 
 * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A 
 * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL 
 * CYNERGY BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR 
 * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF 
 * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS 
 * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE 
 * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER 
 * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT 
 * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
 *
 * Author               Date        Comment
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * Akash Heimlich       20/08/13    v1.0
 *                      29/01/14    v1.1 new layout
 *						25/04/15	added role_timeout
 *						28/06/18	WattmonOS 3
 ********************************************************************/
include("/app/config.inc");
$angular_controller="FlashEditCtrl"; 
$title=lang('FLASH_SETTINGS','flash');
include("/app/header.inc");

define('FLASH_STATUS_IDLE', 0);
define('FLASH_STATUS_ERASING',  1);
define('FLASH_STATUS_RESTORING',  2);
define('FLASH_STATUS_BACKING_UP',  3);
define('FLASH_STATUS_ERROR',  4);

$status = flash_status();
$busy = $status['state'];

?>


<!-- BREADCRUMBS -->
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('FLASH_SETTINGS','flash')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('CONFIGURE_TITLE','flash')) ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
    <? print(lang('HELP','uphp')) ?>
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','flash')) ?></a>
  </li>
  <li class="nav-item">
  <a class="nav-link {{getClass()}}" ng-show='locked==1' ng-click="unlockFlash()" ><i class="icon-lock"></i> UNLOCK</a>
  <a class="nav-link {{getClass()}}" ng-show='locked==0' ng-click="lockFlash()" ><i class="icon-lock"></i> LOCK</a>
  </li>
  
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1 || settings_locked' ng-click="formatFlash()" ><i class="icon-check"></i> <? print(lang('FORMAT_FLASH','flash')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1 || settings_locked' ng-click="eraseFlash()" ><i class="icon-check"></i> <? print(lang('ERASE_FLASH','flash')) ?></a>
  </li>
  
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1 || settings_locked' ng-click="restoreFlash()" ><i class="icon-check"></i> <? print(lang('RESTORE_FLASH','flash')) ?></a>
  </li>
 <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1 || settings_locked' ng-click="backupFlash()" ><i class="icon-check"></i> <? print(lang('BACKUP_FLASH','flash')) ?></a>
  </li>  
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1 || settings_locked' ng-click="saveSettings()" ><i class="icon-check"></i> <? print(lang('APPLY','flash')) ?></a>
  </li>
</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
    <? 
    $cnt=intval(lang('HELP_CNT','flash'));
    for ($i=1;$i<=$cnt;$i++) {
        print(lang('HELP'.$i,'flash'));
    }
    ?>
  </div>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','flash')) ?></div>
<form name="form" class="css-form form-horizontal" novalidate>
<!-- VARIABLES -->
<? 
  $cur_drive=get_drive();
  $boot=ini_get("0:/config/boot.ini","config","boot",1);
?>
<form name="form" class="css-form form-horizontal" novalidate>
<div ng-init="sysmsg='<? if ($_GLOBALS['needreboot']) print("You will need to reboot the device for changes to take effect."); ?>';"></div>
<div ng-init="boot=<? print($boot); ?>;"></div>

<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('PAGE_TITLE','flash')) ?></h5>
        <p class="card-text">    
            <div class="form-group">
                <label for="boot"><? print(lang('BOOT_DRIVE','flash')) ?></label>
                <select ng-model="boot" name='boot' class="custom-select custom-select-sm">
                    <option value='0'><? print(lang('BOOT_SD','flash')) ?></option>
                    <option value='1'><? print(lang('BOOT_FLASH','flash')) ?></option>
                </select>
                <small id="langH" class="form-text text-muted"><? print(lang('BOOT_DRIVE_HELP','flash')) ?></small>
            </div>
		 </p>
	</div>
	
</div>
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('FLASH_INFO','flash')) ?></h5>
        <p class="card-text">    <pre>
Flash Status: <? print(sys_get("FLASH_STATUS")); ?>
Flash ID: <? printf("%X",sys_get("FLASH_ID")); ?>
Flash Size: <? printf("%d",sys_get("FLASH_SIZE")); ?>MB

Free: <? $size=intval(disk_total_space(1)/1024); 
print(number_format(disk_free_space(1)/1024,1)."MB of ".$size.'MB');	?>
</pre>
		 </p>
	</div>
	
</div>

</form>

     <script>
var app = angular.module('myApp', []);         

app.factory('dataService', function($http) {
  
  this.async = function(roles) {
    return $http.get('/app/flash_ajax.cgi?action=status')
    .then(function (response) {
        //alert(response.data);
      var data = response.data;
      return data;
    }, function(reason) {
        //alert('Failed: ' + reason);
        //$timeout(poll, 100);  // try again
    });
    
  };
  
  return this;
});

function FlashEditCtrl(dataService,$scope, $timeout,$http) {
   var self = this;

  $scope.refresh=0;
  $scope.roles=0;
  $scope.last_status=0;
   $scope.infomsg="";
   $scope.settings_locked=settings_locked;
   if (settings_locked) 
        $scope.errormsg="Unable to save settings since the Flash is locked.  Please unlock first.";
   
   $scope.loading=0;
   $scope.asyncData = dataService.async();
    $scope.locked=<? print(sys_get("FLASH_STATUS")==4?"1":"0") ?>;
   function poll(){
          $scope.loading=1;
          $scope.asyncData = dataService.async();
        }
      
   $scope.poll=poll;  
  
   $scope.restoreFlash=function () {
<?   
    
        if ($cur_drive==1) {
        ?>
        alert("Unable to restore flash as your booted from flash.  Please boot from SD first.");
        return;
        <? } 
        if (!file_exists("0:/flash.iso")) {
        ?>
        alert("No flash file found in the root of the SD card.  Ensure flash.dat exists!");
        return;
        <?          
        }
        ?>
        //$scope.loading=1;
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       //
       $http.get('/app/flash_ajax.cgi?action=restore',{timeout: 120000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Restore started":"Error restoring.";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   $scope.formatFlash=function () {
<?   
    
        if ($cur_drive==1) {
        ?>
        alert("Unable to format flash as your booted from flash.  Please boot from SD first.");
        $scope.errormsg="Unable to format flash as your booted from flash.  Please boot from SD first.";
        return;
        <? } 
        ?>
        if (!confirm("You are about to erase all files on your flash.  Are you sure you want to do this?")) {
            $scope.infomsg="Aborted by user";
            return;
        }
      //  $scope.loading=1;
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       //
       $http.get('/app/flash_ajax.cgi?action=format',{timeout: 120000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Format Started":"Error formatting.";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   
    $scope.eraseFlash=function () {
<?   
    
        if ($cur_drive==1) {
        ?>
        alert("Unable to erase flash as your booted from flash.  Please boot from SD first.");
        $scope.errormsg="Unable to format flash as your booted from flash.  Please boot from SD first.";
        return;
        <? } 
        ?>
        if (!confirm("You are about to erase all files on your flash.  Are you sure you want to do this?")) {
            $scope.infomsg="Aborted by user";
            return;
        }
      //  $scope.loading=1;
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       
       //alert();
       //
       $http.get('/app/flash_ajax.cgi?action=erase',{timeout: 120000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Erase Started":"Error formatting.";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.locked=0;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   
   $scope.unlockFlash=function () {
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       //
       //$scope.loading=1;
       $http.get('/app/flash_ajax.cgi?action=unlock',{timeout: 12000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Flash unlocked":"Error unlocking";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.locked=0;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   $scope.lockFlash=function () {
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       //
       //$scope.loading=1;
       $http.get('/app/flash_ajax.cgi?action=lock',{timeout: 12000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Flash locked":"Error unlocking";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.locked=1;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   
   $scope.backupFlash=function () {
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       //
       //$scope.loading=1;
       $http.get('/app/flash_ajax.cgi?action=backup',{timeout: 120000})
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.result==1)?"Backup Started":"Error backing up";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          $scope.poll();
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   $scope.saveSettings=function () {
       $scope.successmsg="";
       $scope.errormsg="";
       $scope.infomsg="";
       //alert();
       $scope.loading=1;
       $http.post('/app/configsave.cgi?config=boot.ini&section=config&drive=0',"boot="+$scope.boot)
        .then(function (response) {
          var data = response.data;      
          $scope.successmsg=(data.status==1)?"Saved Settings":"";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
            //alert('Failed: ' + reason);
           
        });
   }
   
   $scope.$watch('asyncData', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        
        $scope.status = asyncData.result.state;
        $scope.percent = asyncData.result.percent;
        if ($scope.status) {
            if ($scope.status==1) {
                $scope.successmsg="Erasing flash chip - "+$scope.percent+"% complete";
            }
            if ($scope.status==2) {
                $scope.successmsg="Restoring backup ISO image to flash chip - "+$scope.percent+"% complete";
            }
            if ($scope.status==3) {
                $scope.successmsg="Backing up flash chip to ISO image - "+$scope.percent+"% complete";
            }
            if ($scope.status==4) {
                $scope.errormsg="Error during the last operation. Your flash may be corrupt";
            }
            $timeout(poll, 5000);
        } else {
            $scope.loading=0;
            if ($scope.last_status==1) {
                $scope.successmsg="Erasing flash chip completed successfully.";
            }
            if ($scope.last_status==2) {
                $scope.successmsg="Restoring backup ISO image to flash chip completed successfully.";
            }
            if ($scope.last_status==3) {
                $scope.successmsg="Backing up flash chip to ISO image completed successfully.";
            }
            if ($scope.last_status==4) {
                $scope.errormsg="Error during the last operation failed";
            
            }
        }
        $scope.last_status=$scope.status;
    }
  });
<? if ($busy) { ?>    
  poll();
<? } ?>  

}</script>
<? include("/app/footer.inc"); ?>




