<?php
/**
 * Generate .cpanel.yml untuk staging/production.
 * Contoh:
 * php scripts/generate_cpanel_yml.php staging USERNAME public_html/staging-perawat
 * php scripts/generate_cpanel_yml.php production USERNAME public_html/perawat
 */

$root = dirname(__DIR__);
$env = $argv[1] ?? null;
$username = $argv[2] ?? null;
$target = $argv[3] ?? null;

if (!$env || !$username || !$target || !in_array($env, ['staging', 'production'], true)) {
    fwrite(STDERR, "Usage: php scripts/generate_cpanel_yml.php <staging|production> <CPANEL_USERNAME> <target-path-inside-home>\n");
    fwrite(STDERR, "Example: php scripts/generate_cpanel_yml.php staging itcd5572 public_html/staging-perawat\n");
    exit(1);
}

$target = trim($target, '/');
$deployPath = "/home/{$username}/{$target}/";

$yaml = implode(PHP_EOL, [
    '---',
    'deployment:',
    '  tasks:',
    "    # Generated for {$env}",
    "    - export DEPLOYPATH={$deployPath}",
    '    - /bin/mkdir -p $DEPLOYPATH',
    '    - /bin/rsync -av --delete \\',
    "      --exclude='.git' \\",
    "      --exclude='.github' \\",
    "      --exclude='.env' \\",
    "      --exclude='.env.*' \\",
    "      --exclude='storage/backups/*' \\",
    "      --exclude='storage/logs/*' \\",
    "      --exclude='storage/cache/*' \\",
    "      --exclude='storage/exports/*' \\",
    "      --exclude='uploads/*' \\",
    "      --exclude='exports/*' \\",
    '      ./ $DEPLOYPATH',
    '    - /bin/mkdir -p ${DEPLOYPATH}storage/logs ${DEPLOYPATH}storage/cache ${DEPLOYPATH}storage/exports ${DEPLOYPATH}storage/backups',
    '    - /bin/mkdir -p ${DEPLOYPATH}uploads/jadwal ${DEPLOYPATH}uploads/dokumen ${DEPLOYPATH}uploads/lampiran ${DEPLOYPATH}uploads/temp',
    '    - /bin/cp -n uploads/.htaccess ${DEPLOYPATH}uploads/.htaccess || true',
    '    - /bin/cp -n storage/.htaccess ${DEPLOYPATH}storage/.htaccess || true',
]);

$filePath = $root . DIRECTORY_SEPARATOR . '.cpanel.yml';
file_put_contents($filePath, $yaml . PHP_EOL);
echo "Generated .cpanel.yml for {$env}: {$deployPath}" . PHP_EOL;
