#!/usr/bin/php
<?php
error_reporting(E_ALL);
require '/usr/lib/sysadmin/includes.php';

$txnId = '';

if (isset($argv[1])) {
   $txnId = $argv[1];
}

$firstCommandOutput = [];
$firstCommandReturn = 1;
$cmd = "/usr/sbin/fwconsole ma upgradeall";

//Running upgrade all module command
exec($cmd, $firstCommandOutput, $firstCommandReturn);

if($firstCommandReturn == 0){

   // Running Chown Command
   
   $secondCommandOutput = [];
   $secondCommandReturn = 1;
   $cmd = "/usr/sbin/fwconsole chown 2>&1";
   exec($cmd, $secondCommandOutput, $secondCommandReturn);
   
   if ($secondCommandReturn == 0) {

      //Running Reload Command
      
      $thirdCommandOutput = [];
      $thirdCommandReturn = 1;
      $cmd = "/usr/sbin/fwconsole reload 2>&1";
      exec($cmd , $thirdCommandOutput, $thirdCommandReturn);

      if ($thirdCommandReturn == 0) {
         
         $message = json_encode($firstCommandOutput);
         $status = "Executed";

      } else {
         
         if (array_key_exists(2, $thirdCommandOutput)) {
            $message =  "Failed to execute command [ " . $cmd . " ] , command output = $thirdCommandOutput[2]";
         } else {
            $message =  "Failed to execute command [ " . $cmd . " ]";
         }
         $status = 'Failed';
      }
   } else {
      
      if (array_key_exists(2, $secondCommandOutput)) {
         $message =  "Failed to execute command [ " . $cmd . " ] , command output = $secondCommandOutput[2]";
      } else {
         $message =  "Failed to execute command [ " . $cmd . " ]";
      }
      $status = 'Failed';
   }
}else {

   if (array_key_exists(2, $firstCommandOutput)) {
      $message =  "Failed to execute command [ " . $cmd . " ] , command output = $firstCommandOutput[2]";
   } else {
      $message =  "Failed to execute command [ " . $cmd . " ]";
   }
   $status = 'Failed';
}


$db = \Sysadmin\FreePBX::Database();
$sql = ("UPDATE IGNORE api_asynchronous_transaction_history SET event_status = :event_status , failure_reason =:failure_reason, process_end_time =:end_time WHERE `txn_id` = :txn_id");
$sth = $db->prepare($sql);
$sth->execute([
	":event_status" => $status,
	":failure_reason" => $message,
	":end_time" => time(),
	":txn_id" => $txnId
]);