<?php
$method = $_SERVER['REQUEST_METHOD'] ?? '';
if ($method !== 'POST') {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

$payload = file_get_contents('php://input');
if ($payload === false || $payload === '') {
    http_response_code(400);
    echo 'Empty payload';
    exit;
}

$event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? '';
$secret = getenv('GITEA_WEBHOOK_SECRET');
$signature = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';

if ($secret !== false && $secret !== '') {
    if ($signature === '') {
        http_response_code(401);
        echo 'Missing signature';
        exit;
    }
    $hash = hash_hmac('sha256', $payload, $secret, false);
    if (!hash_equals($hash, $signature)) {
        http_response_code(401);
        echo 'Invalid signature';
        exit;
    }
}

$decoded = json_decode($payload, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

if ($event !== 'push') {
    http_response_code(202);
    echo 'Ignored';
    exit;
}

$ref = $decoded['ref'] ?? '';
if ($ref !== 'refs/heads/main') {
    http_response_code(202);
    echo 'Ignored';
    exit;
}

exec('/bin/sudo -u admin_hz2 /bin/bash /volume2/webssd/fabiennefoehn/deploy-staging.sh > /dev/null 2>&1 &');
echo 'Deploy triggered';
