#!/usr/bin/php -q
<?php

error_reporting(E_ALL);
date_default_timezone_set('UTC');

	require '/usr/lib/sysadmin/includes.php';

   $filename = '';
   $txn_id  = "";

   if (isset($argv[1])) {
      // Underp the base64
      $b = str_replace('_', '/', $argv[1]);
      $settings = @json_decode(gzuncompress(@base64_decode($b)), true);
      if (is_array($settings)) {
         $filename = $settings[0];
         $txn_id = $settings[1];
      }
    }

	$message = $status = "";

	$isValidRestorePath = static function (string $path): bool {
		if ($path === '' || strpos($path, '..') !== false) {
			return false;
		}
		return (bool) preg_match('/^[a-zA-Z0-9\/_.@+=:-]+$/', $path);
	};

	if (!$isValidRestorePath($filename) || !is_file($filename)) {
		$status = 'Failed';
		$message = 'Backup file not found or invalid path';
	}
	else {
		try {
			// Argument array = no shell interpretation of $filename
			$process = \freepbx_get_process_obj([
				'/usr/sbin/fwconsole',
				'backup',
				'--restore',
				$filename,
				'--skiprestorehooks',
			]);
			if (!$process) {
				throw new Exception('Unable to create restore process');
			}
			$process->setTimeout(null);
			$process->mustRun();
			$status = 'Executed';
			$message = 'Restore Done';
		} catch (Exception $e) {
			$message = 'Restore Errored';
			$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" => $txn_id
	]);
?>