<?php
/**
 * Backup file aplikasi sebelum deploy besar.
 * Jalankan:
 *   php scripts/backup_files.php
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo 'CLI only';
    exit(1);
}

$root = realpath(__DIR__ . '/..');
$backupDir = $root . '/storage/backups';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$timestamp = date('Ymd_His');
$out = $backupDir . "/files_{$timestamp}.zip";

$exclude = [
    './storage/backups/*',
    './storage/logs/*',
    './storage/cache/*',
    './.git/*',
];

$excludeArgs = '';
foreach ($exclude as $pattern) {
    $excludeArgs .= ' -x ' . escapeshellarg($pattern);
}

$cmd = 'cd ' . escapeshellarg($root) . ' && zip -qr ' . escapeshellarg($out) . ' .' . $excludeArgs;
passthru($cmd, $code);

if ($code !== 0 || !file_exists($out)) {
    fwrite(STDERR, "Backup file gagal. Pastikan command zip tersedia di hosting.\n");
    exit(1);
}

echo "Backup file berhasil: {$out}\n";
