#!/usr/bin/php 
<?PHP
/* Copyright 2015-2026, Lime Technology
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<?

$docroot ??= ($_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp');
require_once "$docroot/webGui/include/Helpers.php";
require_once "$docroot/plugins/dynamix.vm.manager/include/fs_helpers.php";

$json_path = "/boot/config/plugins/dynamix.vm.manager/vms.json";

if (!file_exists($json_path)) {
    die("Configuration file not found: $json_path\n");
}

$vmsjson = file_get_contents($json_path);
if ($vmsjson === false) {
    die("Failed to read configuration file: $json_path\n");
}

$vms = json_decode($vmsjson, true);
if ($vms === null && json_last_error() !== JSON_ERROR_NONE) {
    die("Invalid JSON in configuration file: " . json_last_error_msg() . "\n");
}

file_put_contents("/tmp/libvirtrestore","");
foreach ($vms as $vm => $vmdetail) {
  $to_file = "/etc/libvirt/qemu/$vm.xml";
  $from_file = $vmdetail['path']."/$vm.xml";
  #echo " from:$from_file     to:$to_file";
  if (file_exists($from_file)) {
    $res = copy_if_different($from_file, $to_file, false);
    $msg = "$vm from:$from_file to:$to_file";
    if (!empty($res['error'])) {
        $msg .= " ERROR:" . $res['error'];
    } elseif (!empty($res['copied'])) {
        $msg .= " COPIED";
    } elseif (!empty($res['would_copy'])) {
        $msg .= " WOULD_COPY";
    } else {
        $msg .= " SKIPPED_IDENTICAL";
    }
    file_put_contents("/tmp/libvirtrestore", $msg . "\n", FILE_APPEND);
  } else {
    file_put_contents("/tmp/libvirtrestore","Nocpy $vm from:$from_file     to:$to_file\n",FILE_APPEND);
  }
}
?>
