<?php
// Receives Sonarr/Radarr/Lidarr Download events. Fires upgrade_webhook_handler.sh
// in the background and returns 200 immediately — arr does not wait on the push.
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/config.php';

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

$payload = json_decode(file_get_contents('php://input'), true);
if (!$payload) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
    exit;
}

$event = $payload['eventType'] ?? '';

if ($event === 'Test') {
    echo json_encode(['ok' => true, 'message' => 'Webhook connected — configure On Download to use this URL']);
    exit;
}

$vars    = vv_conf_vars();
$enabled = strtolower($vars['DOWNLOAD_WEBHOOK_ENABLED'] ?? 'true') !== 'false';
if (!$enabled) {
    echo json_encode(['ok' => true, 'skipped' => 'DOWNLOAD_WEBHOOK_ENABLED=false']);
    exit;
}

// Fire on any Download event — new grabs and upgrades both need immediate propagation
// so remote nodes don't search for something we already have.
if ($event !== 'Download') {
    echo json_encode(['ok' => true, 'skipped' => $event]);
    exit;
}

// Detect arr type and item folder from payload structure
if (isset($payload['series']['path'])) {
    $arr_type = 'sonarr';
    $path     = $payload['series']['path'];
} elseif (isset($payload['movie']['folderPath'])) {
    $arr_type = 'radarr';
    $path     = $payload['movie']['folderPath'];
} elseif (isset($payload['artist']['path'])) {
    $arr_type = 'lidarr';
    $path     = $payload['artist']['path'];
} else {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Unrecognised payload structure']);
    exit;
}

if (!$path) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Empty path in payload']);
    exit;
}

// Basic path sanity — must be absolute, no traversal
if (!str_starts_with($path, '/') || str_contains($path, '..') || preg_match('/[\x00\n\r]/', $path)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Unsafe path']);
    exit;
}

$handler = SCRIPTS_DIR . '/Media/upgrade_webhook_handler.sh';
if (!file_exists($handler)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'upgrade_webhook_handler.sh not found']);
    exit;
}

exec('bash ' . escapeshellarg($handler)
    . ' ' . escapeshellarg($arr_type)
    . ' ' . escapeshellarg($path)
    . ' >> /var/log/varaverk/upgrade_webhook.log 2>&1 &');

echo json_encode(['ok' => true, 'arr' => $arr_type, 'path' => $path]);
