<?php
declare(strict_types=1);

// Gitea push webhook — validates HMAC-SHA256 and runs deploy-tools.sh
// Runs as the dobetternorge user via SuexecUserGroup.

define('DEPLOY_SECRET', '59defe48282805e0706e556c39ecc852c3aa5d8f2598be378c68ac4a6a4b5813');
define('DEPLOY_SCRIPT', '/home/dobetternorge/bin/deploy-tools.sh');
define('LOG_FILE',      '/home/dobetternorge/logs/deploy-tools.log');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['ok' => false, 'error' => 'Method not allowed']));
}

$sig = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
$raw = file_get_contents('php://input');

$expected = hash_hmac('sha256', $raw, DEPLOY_SECRET);
if (!hash_equals($expected, $sig)) {
    http_response_code(403);
    exit(json_encode(['ok' => false, 'error' => 'Bad signature']));
}

$payload = json_decode($raw, true);
$ref     = $payload['ref'] ?? '';
if ($ref !== 'refs/heads/main') {
    echo json_encode(['ok' => true, 'skipped' => true, 'ref' => $ref]);
    exit;
}

// Fire-and-forget — respond immediately, deploy runs in background
// Use full paths to avoid PATH issues in PHP-FPM minimal environment.
$cmd = '/usr/bin/nohup /usr/bin/bash ' . escapeshellarg(DEPLOY_SCRIPT)
     . ' >> ' . escapeshellarg(LOG_FILE) . ' 2>&1 &';
shell_exec($cmd);

echo json_encode(['ok' => true, 'deploying' => true, 'ref' => $ref]);
