<?php
// Yeh script seedhe browser se nahi chalegi. Isse sirf restore_backup.php hi chala sakta hai.

if (php_sapi_name() !== 'cli') {
    die("This script can only be run from the command line.");
}

// Arguments prapt karein
$db_file = $argv[1] ?? null;
$files_file = $argv[2] ?? null;

if (!$db_file || !$files_file) {
    log_error("Missing backup file paths.");
    exit(1);
}

// Configuration
$source_dir = '/home/cybsoul/kids.eventsnews.in';
$db_details = [
    'host' => 'localhost',
    'user' => 'cybsoul_loyality',
    'pass' => 'Digital@1270',
    'name' => 'cybsoul_taskapp',
];
$temp_restore_dir = '/home6/cybsoul/temp_restore';

function log_error($message) {
    file_put_contents(__DIR__ . '/restore_error.log', date('Y-m-d H:i:s') . " - " . $message . "\n", FILE_APPEND);
}

// --- 1. Files Restore ---
log_error("Starting files restore...");

// Purana temp folder delete karein agar maujood hai
if (is_dir($temp_restore_dir)) {
    system("rm -rf " . escapeshellarg($temp_restore_dir));
}
// Naya temp folder banayein
mkdir($temp_restore_dir, 0755, true);

// Backup ko temp folder me extract karein
$unzip_command = "unzip -o " . escapeshellarg($files_file) . " -d " . escapeshellarg($temp_restore_dir);
exec($unzip_command, $output, $return_unzip);
if ($return_unzip !== 0) {
    log_error("Failed to unzip files backup.");
    exit(1);
}

// rsync ka istemaal karke files ko live directory me copy karein
$rsync_command = "rsync -a --delete " . escapeshellarg($temp_restore_dir . '/home/cybsoul/kids.eventsnews.in/') . " " . escapeshellarg($source_dir . '/');
exec($rsync_command, $output, $return_rsync);
if ($return_rsync !== 0) {
    log_error("Failed to sync files to live directory.");
    exit(1);
}

// Temp folder saaf karein
system("rm -rf " . escapeshellarg($temp_restore_dir));
log_error("Files restore completed.");


// --- 2. Database Restore ---
log_error("Starting database restore...");

// mysql command se database ko restore karein
$db_restore_command = "gunzip < " . escapeshellarg($db_file) . " | mysql --host=" . escapeshellarg($db_details['host']) . " --user=" . escapeshellarg($db_details['user']) . " --password='" . $db_details['pass'] . "' " . escapeshellarg($db_details['name']);
exec($db_restore_command, $output, $return_db);
if ($return_db !== 0) {
    log_error("Failed to restore database. MySQL command returned: " . $return_db);
    exit(1);
}

log_error("Database restore completed.");
log_error("Restore process finished successfully.");

exit(0);
?>

