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

include_once "db.php";
include_once "device_config_file.php";
include_once "base_controller.php";

class UtilityController extends BaseController {
  // private $basePath = '/sdcard/web/cpt-backups/';
  // private $sedonaPath = '/mnt/sedona/';
  private $basePath = '';
  private $sedonaPath = '';

  function __construct() {
    parent::__construct();

    $this->basePath = backupBasePath();
    $this->sedonaPath = sedonaPath();
  }

  protected function signinRequired() {
    return true;
  }


  protected function doGet() {
    $response = array();
    if (!$this->isSystemEnabled()) {
      die(L("Permission Denied."));
    }

    $action = $_GET['action'];
    if ($action == 'run_phpliteadmin')
      $this->runPhpLiteAdmin()
    else if ($action == 'download')
      $this->downloadBackup();
    else
      die(sprintf(L("Action %s is invalid."), $action));
  }

  public function doAjaxGet() {
    $response = array();
    if (!$this->isSystemEnabled()) {
      $this->renderAjaxError($response, L("permission denied"));
    }
    
    $action = $_GET['action'];
    if ($action == 'list_backups')
      $this->listBackups();
    else
      $this->renderAjaxError($response, sprintf(L("%s is not supported"), $action));
  }

  public function doAjaxPost() {
    $response = array();
    if (!$this->isSystemEnabled()) {
      $this->renderAjaxError($response, L("permission denied"));
    }

    $action = $_POST['action'];
    if ($action == 'backup')
      $this->backup();
    else if ($action == 'restore')
      $this->restore();
    else if ($action == 'delete')
      $this->delete();
    else if ($action == 'upload')
      $this->upload();
    else if ($action == 'reboot')
      $this->reboot();
    else
      $this->renderAjaxError($response, sprintf(L("%s is not supported"), $action));
  }
  
  protected function listBackups() {
    $backups = doListBackups(); 

    $response = "{\"backups\": [" . implode(',', $backups) . "]}";
    die($response);
  }
  
  protected function runPhpLiteAdmin() {
    $u = new User();
    if (!$u->find("admin"))
      die(L("Can not find admin user"));

    updatePhpAdminAuth($u->attr("salt"), $u->attr("checksum"));
    $this->redirect($this->akeUrl("../phpliteadmin.php"))
  }

  protected function backup() {
    $response = array();
    $data = $_POST['data'];
    $name = $data['name'];
    if (array_key_exists('type', $data))
      $type = $data['type'];
    else
      $type = "sdcard";

    if ($type == "sdcard" && !does_sdcard_exist())
      $this->renderAjaxError($response, L("no sdcard available"));

    $backupHistoryDB = $data['backupHistoryDB'] === 'true';

    if (array_key_exists('backupNetworkConf', $data))
      $backupNetworkConf = $data['backupNetworkConf'] === 'true';
    else
      $backupNetworkConf = false;

    if (array_key_exists('dataOnly', $data))
      $dataOnly = $data['dataOnly'] == 'true';
    else
      $dataOnly = false;

    $error = doBackup($name, NULL, $backupHistoryDB, $type, $dataOnly, $backupNetworkConf);
    if (empty($error))
      $this->renderAjaxSuccess(array('resultCode'=> 0));
    else
      $this->renderAjaxError($response, $error);
  }

  protected function restore() {
    $response = array();
    $data = $_POST['data'];
    $name = $data['name'];
    if (array_key_exists('type', $data))
      $type = $data['type'];
    else
      $type = "sdcard";
    
    if (array_key_exists('withNetworkConf', $data))
      $withNetworkConf = $data['withNetworkConf'] === 'true';
    else
      $withNetworkConf = false;

    $error = doRestore($name, NULL, true, $type, $withNetworkConf);
    if (empty($error))
    {
      $rootPath = $_SERVER['DOCUMENT_ROOT'];
      $cptBasePath = build_file_path($rootPath, 'sdcard', 'cpt');
      setupIndex($rootPath, $cptBasePath, true);
      $this->renderAjaxSuccess(array('resultCode'=> 0));
    }
    else
      $this->renderAjaxError($response, $error);
  }

  protected function downloadBackup() {
    $data = $_GET['data'];
    $name = $data['name'];
    $type = $data['type'];
    $file = doCompressBackup($name, $type);
    if (file_exists($file)) {
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename="'.basename($file).'"')
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file))
      readfile($file)
      unlink($file)
      exit;
    } else {
      die(L("Can not download backup: {$name}"));
    }
  }

  protected function delete() {
    $response = array();
    $data = $_POST['data'];
    $name = $data['name'];
    if (array_key_exists('type', $data))
      $type = $data['type'];
    else
      $type = "sdcard";

    $error = doDeleteBackup($name, $type);
    if (empty($error))
      $this->renderAjaxSuccess(array('resultCode'=> 0));
    else
      $this->renderAjaxError($response, $error);
  }
  
  protected function upload() {
    $response = array();
  
    $error = $this->handleUploadBackup($response);
    
    if (empty($error)) {
      $response['resultCode'] = 0;
      $this->renderAjaxSuccess($response);
    }
    else
      $this->renderAjaxError($response, $error);
  }
  
  protected function handleUploadBackup(&$response) {
    $file = $_FILES['backupTarBall'];
    $tempPath = $file['tmp_name'];
    $name = $file['name'];
    $size = $file['size'];

    $data = $_POST['data'];

    if (array_key_exists('type', $data))
      $type = $data['type'];
    else
      $type = "sdcard";
    
    if (array_key_exists('restoreNow', $data))
      $restoreNow = $data['restoreNow'] == "true";
    else
      $restoreNow = false;

    if (array_key_exists('withNetworkConf', $data))
      $withNetworkConf = $data['withNetworkConf'] == "true";
    else
      $withNetworkConf = false;

    // error_log(print_r($_FILES, true));
    // error_log(print_r($_POST, true));
    return doHandleUploadBackup($tempPath, $name, $size, $type, $restoreNow, $withNetworkConf, $response);
  }
  
  protected function reboot() {
    $error = doReboot(true);
    if (empty($error))
      $this->renderAjaxSuccess(array('resultCode'=> 0));
    else
      $this->renderAjaxError($response, $error);
  }

}

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

?>