<?php
/**
 * Gitea webhook → rebuild + redeploy
 *
 * Triggereado por push a branch main en mauri/hostingdelsur.net
 * Ejecuta: git pull, npm install, npm run build, rsync dist a 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';

$commands = [
    "cd {$projectDir} && git pull origin main 2>&1",
    "cd {$projectDir} && npm install --production=false 2>&1",
    "cd {$projectDir} && npm run build 2>&1",
    "rsync -a --delete --exclude='mwp' --exclude='.well-known' --exclude='.smtp-credentials.json' --exclude='api' --exclude='.htaccess' {$distDir}/ {$publicHtml}/ 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)]);
