<?php
// Simple PHP Git deploy script - tailored for Iozzia Gem Swap
// Source project: https://github.com/markomarkovic/simple-php-git-deploy

// Load local config if present
$configFile = __DIR__ . '/deploy-config.php';
if (file_exists($configFile)) {
    require $configFile;
}

// Defaults (can be overridden in deploy-config.php)
defined('REPO') or define('REPO', 'https://github.com/Iozzia-Lab/iozzia-games-gemswap.git');
defined('BRANCH') or define('BRANCH', 'main');
defined('TARGET_DIR') or define('TARGET_DIR', '/home/iozziaco/public_html/games/gemswap/');
defined('TMP_DIR') or define('TMP_DIR', sys_get_temp_dir() . '/gemswap-deploy');
defined('SAT') or define('SAT', 'change-me'); // secret access token for webhook
defined('USE_COMPOSER') or define('USE_COMPOSER', false);
defined('BACKUP_DIR') or define('BACKUP_DIR', null);
defined('RSYNC_FLAGS') or define('RSYNC_FLAGS', '-az --delete');

// Basic access check using secret access token
$providedSat = isset($_GET['sat']) ? $_GET['sat'] : (isset($_POST['sat']) ? $_POST['sat'] : '');
if (!SAT || $providedSat !== SAT) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

function run($cmd, $cwd = null) {
    $descriptorSpec = [
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w']
    ];
    $process = proc_open($cmd, $descriptorSpec, $pipes, $cwd ?: null);
    if (!is_resource($process)) {
        throw new RuntimeException('Failed to start process: ' . $cmd);
    }
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $status = proc_close($process);
    if ($status !== 0) {
        throw new RuntimeException("Command failed ({$status}): {$cmd}\n{$stderr}");
    }
    return trim($stdout);
}

// Ensure tmp directories
if (!is_dir(TMP_DIR) && !mkdir(TMP_DIR, 0755, true)) {
    http_response_code(500);
    echo 'Failed to create TMP_DIR';
    exit;
}

$releaseDir = rtrim(TMP_DIR, '/').'/release';
$sharedDir  = rtrim(TMP_DIR, '/').'/shared';
if (!is_dir($releaseDir) && !mkdir($releaseDir, 0755, true)) {
    http_response_code(500);
    echo 'Failed to create releaseDir';
    exit;
}
if (!is_dir($sharedDir)) {
    mkdir($sharedDir, 0755, true);
}

try {
    // Optional backup
    if (BACKUP_DIR) {
        if (!is_dir(BACKUP_DIR)) { mkdir(BACKUP_DIR, 0755, true); }
        $timestamp = date('Ymd_His');
        $backupFile = rtrim(BACKUP_DIR, '/')."/gemswap_backup_{$timestamp}.tar.gz";
        if (is_dir(TARGET_DIR)) {
            run(sprintf('tar -czf %s -C %s .', escapeshellarg($backupFile), escapeshellarg(TARGET_DIR)));
        }
    }

    // Clone or fetch
    if (!is_dir($releaseDir.'/.git')) {
        run(sprintf('git clone --depth 1 --branch %s %s %s', escapeshellarg(BRANCH), escapeshellarg(REPO), escapeshellarg($releaseDir)));
    } else {
        run('git fetch --all --prune', $releaseDir);
        run(sprintf('git reset --hard origin/%s', escapeshellarg(BRANCH)), $releaseDir);
        run(sprintf('git checkout %s', escapeshellarg(BRANCH)), $releaseDir);
        run('git pull --rebase', $releaseDir);
    }

    // Optional composer
    if (USE_COMPOSER && file_exists($releaseDir.'/composer.json')) {
        run('composer install --no-interaction --prefer-dist --no-ansi --no-progress', $releaseDir);
    }

    // Rsync to target
    if (!is_dir(TARGET_DIR)) { mkdir(TARGET_DIR, 0755, true); }
    $rsyncCmd = sprintf('rsync %s --exclude ".git" --exclude "deploy-config.php" %s %s',
        RSYNC_FLAGS,
        escapeshellarg(rtrim($releaseDir, '/').'/'),
        escapeshellarg(rtrim(TARGET_DIR, '/').'/')
    );
    run($rsyncCmd);

    // Set minimal permissions (adjust as needed)
    @chmod(TARGET_DIR, 0755);

    header('Content-Type: text/plain');
    echo "Deployed branch '".BRANCH."' to '".TARGET_DIR."' successfully.";
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/plain');
    echo "Deployment failed:\n".$e->getMessage();
}
