<?php
/**
 * Gitea Webhook Deploy Handler
 * Called by Gitea on push to main branch.
 *
 * Set DEPLOY_SECRET in Gitea webhook settings and
 * configure the same value in the DEPLOY_SECRET env var
 * (or hardcode it below for simple setups).
 */

$secret = getenv('DEPLOY_SECRET') ?: '';

if (empty($secret)) {
    http_response_code(500);
    die('DEPLOY_SECRET not configured.');
}

// Verify Gitea HMAC-SHA256 signature
$signature = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
$body = file_get_contents('php://input');
$expected = hash_hmac('sha256', $body, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    die('Invalid signature.');
}

// Only act on push events
$event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? '';
if ($event !== 'push') {
    http_response_code(200);
    die('Ignored: not a push event.');
}

// Only deploy on main branch
$payload = json_decode($body, true);
$ref = $payload['ref'] ?? '';
if ($ref !== 'refs/heads/main') {
    http_response_code(200);
    die('Ignored: not main branch.');
}

// Run git pull (HOME must be set explicitly since PHP's shell_exec doesn't inherit it)
putenv('HOME=/var/www');
$output = shell_exec('git -C /var/www/html pull 2>&1');

http_response_code(200);
header('Content-Type: text/plain');
echo "Deploy triggered:\n" . $output;
