<?php
/**
 * Gitea webhook → rebuild + redeploy
 *
 * Triggereado por push a branch main en mauri/hostingdelsur.net
 * Ejecuta: git pull, npm install, npm run build, mirror dist → public_html
 *
 * Logs: /home/hostingd/deploy.log
 */

declare(strict_types=1);

$secret = getenv('DEPLOY_SECRET') ?: 'hds-deploy-2026';
$signature = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
$payload = file_get_contents('php://input');

$expected = hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Invalid signature']);
    exit;
}

$body = json_decode($payload, true);
$ref = $body['ref'] ?? '';
$repoName = $body['repository']['name'] ?? '';

if ($ref !== 'refs/heads/main' || $repoName !== 'hostingdelsur.net') {
    http_response_code(200);
    echo json_encode(['ok' => true, 'message' => 'Ignored (not main or wrong repo)']);
    exit;
}

$logFile = '/home/hostingd/deploy.log';
$timestamp = date('Y-m-d H:i:s');
$logLine = "[{$timestamp}] Deploy started for {$repoName} @ {$ref}\n";

$projectDir = '/home/hostingd/hostingdelsur.net';
$distDir = $projectDir . '/dist';
$publicHtml = '/home/hostingd/public_html';
$projectSrc = '/root/opencode/development/hostingdelsur.net';
$srcForms = $projectSrc . '/src/forms';

// Directorios/archivos que NO pertenecen al build de Astro y deben
// sobrevivir el wipe (mismo criterio que scripts/deploy.sh --exclude).
// Se mueven a un staging dir antes del rm -rf y se restauran después.
$preserve = ['mwp', 'mee', 'blog', 'design-system', '.well-known', '.smtp-credentials.json'];
$stagingDir = '/home/hostingd/.deploy-preserve-tmp';

$preserveOut = "rm -rf {$stagingDir} && mkdir -p {$stagingDir}";
foreach ($preserve as $item) {
    $preserveOut .= " && [ -e {$publicHtml}/{$item} ] && mv {$publicHtml}/{$item} {$stagingDir}/{$item} || true";
}

$restoreOut = "";
foreach ($preserve as $item) {
    $restoreOut .= "[ -e {$stagingDir}/{$item} ] && mv {$stagingDir}/{$item} {$publicHtml}/{$item} || true; ";
}
$restoreOut .= "rm -rf {$stagingDir}";

$commands = [
    "cd {$projectDir} && git pull origin main 2>&1",
    "cd {$projectDir} && npm install --production=false 2>&1",
    "cd {$projectDir} && npm run build 2>&1",
    "cp {$srcForms}/contact.php {$distDir}/api/contact.php 2>&1",
    "cp {$srcForms}/deploy-webhook.php {$distDir}/api/deploy-webhook.php 2>&1",
    "cp {$srcForms}/api-htaccess {$distDir}/api/.htaccess 2>&1",
    "{$preserveOut} 2>&1",
    "rm -rf {$publicHtml}/* {$publicHtml}/.[!.]* 2>&1; mkdir -p {$publicHtml}",
    "cp -r {$distDir}/* {$distDir}/.[!.]* {$publicHtml}/ 2>&1",
    "{$restoreOut} 2>&1",
];

foreach ($commands as $cmd) {
    $output = shell_exec($cmd . ' 2>&1');
    $logLine .= "$ {$cmd}\n{$output}\n";
}

$logLine .= "[{$timestamp}] Deploy completed\n\n";
file_put_contents($logFile, $logLine, FILE_APPEND);

http_response_code(200);
echo json_encode(['ok' => true, 'message' => 'Deploy triggered', 'log' => basename($logFile)]);
