<?php
/**
 * GitHub Auto-Deploy Webhook
 * Verifies GitHub HMAC signature, then queues the repo for git pull.
 * A root cron job (/usr/local/bin/jarvis-deploy.sh) processes the queue every minute.
 *
 * WEBHOOK_SECRET is loaded from api/config.php (gitignored) — never hardcoded here.
 */

require_once __DIR__ . '/../api/config.php';
if (!defined('WEBHOOK_SECRET')) {
    http_response_code(500);
    echo json_encode(['error' => 'Webhook not configured']);
    exit;
}
define('DEPLOY_QUEUE', '/tmp/jarvis-deploy-queue.txt');
define('DEPLOY_LOG',   '/home/orbishosting.com/logs/deploy.log');

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

$payload = file_get_contents('php://input');
$sig     = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $payload, WEBHOOK_SECRET);

if (!hash_equals($expected, $sig)) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

$data   = json_decode($payload, true);
$repo   = $data['repository']['name'] ?? '';
$ref    = $data['ref'] ?? '';
$pusher = $data['pusher']['name'] ?? 'unknown';

// Only deploy on pushes to main
if ($ref !== 'refs/heads/main') {
    echo json_encode(['ok' => true, 'skipped' => "ref $ref is not main"]);
    exit;
}

$repoMap = [
    'orbishosting'        => '/home/orbishosting.com/public_html',
    'orbis-hosting-portal' => '/home/orbis.orbishosting.com/public_html',
];

if (!isset($repoMap[$repo])) {
    http_response_code(404);
    echo json_encode(['error' => "Unknown repo: $repo"]);
    exit;
}

$path = $repoMap[$repo];
$ts   = date('Y-m-d H:i:s');

file_put_contents(DEPLOY_QUEUE, $path . "\n", FILE_APPEND | LOCK_EX);
file_put_contents(DEPLOY_LOG, "[$ts] Queued deploy: $repo by $pusher -> $path\n", FILE_APPEND | LOCK_EX);

echo json_encode(['ok' => true, 'queued' => $repo, 'path' => $path]);
