<?php
// ═══════════════════════════════════════════════════════════════════════════════════════════════
// PURPOSE
//   Arr download webhook. Receives Sonarr, Radarr and Lidarr Download events and fires
//   upgrade_webhook_handler.sh against the affected folder so the partner learns about the
//   new file immediately rather than at the next scheduled sync.
//
// OPERATIONAL MODEL
//   Accept, dispatch, return. The handler is backgrounded and the response goes out at once,
//   because an arr that is made to wait on a cross-host push will time the webhook out and
//   log it as a failure — and it retries on a schedule that would compound the problem.
//
//   200 therefore means accepted, not propagated. The handler's own log is the record of what
//   happened; this endpoint cannot report it and does not pretend to.
//
//   The reason for immediacy is search suppression: until the partner knows a file exists, it
//   will keep searching for it. The scheduled sync would close that gap eventually; the
//   webhook closes it in seconds.
//
// DESIGN PRINCIPLES
//   The arr type is inferred from the payload's shape, not from a parameter.
//       series.path means Sonarr, movie.folderPath means Radarr, artist.path means Lidarr.
//       Each app names its own field, so the structure identifies the sender without a query
//       string the user could get wrong when configuring three separate applications.
//
//   Test events are answered with instructions.
//       Sonarr's "Test" button gets a message telling the user to configure On Download,
//       because a bare success there is exactly what leads to a webhook that is connected and
//       wired to nothing.
//
//   Every non-Download event is acknowledged and skipped.
//       ok:true with the event name, never an error. An arr that receives an error status
//       retries and eventually disables the webhook, so events this endpoint does not care
//       about have to be accepted rather than rejected.
//
//   Fires on all Download events, not just upgrades.
//       New grabs and upgrades both need propagating; distinguishing them would suppress
//       exactly the first-time grabs the partner is most likely to duplicate.
//
//   The kill switch is read per request.
//       DOWNLOAD_WEBHOOK_ENABLED is checked from conf on every call, so turning it off takes
//       effect without touching the arr configuration — and the response says it was skipped
//       rather than silently doing nothing.
//
// OPERATIONAL SAFEGUARDS
//   POST only, with a real status code.
//       405 for the wrong method, 400 for unparseable or unrecognised bodies. Status codes
//       matter more here than elsewhere in this layer: the caller is a machine that changes
//       its retry behaviour based on them.
//
//   The path is validated and then escaped.
//       Must be absolute, no '..', no null bytes or newlines — then passed through
//       escapeshellarg() into the handler invocation. The arr type is likewise escaped even
//       though it is one of three literals this file chose itself.
//
//   Both the empty-path and unrecognised-structure cases are handled explicitly.
//       A payload with a recognised key holding an empty value is rejected separately from
//       one whose structure is unknown, because those are different misconfigurations.
//
//   A missing handler is reported as a server error, not swallowed.
//       500 with a named error, so a partial deploy is visible in the arr's own webhook log
//       rather than appearing to succeed forever.
//
//   Output is appended to a dedicated log with stdin detached, so a backgrounded handler
//   cannot hold the request's file descriptors open.
//
//   UNREACHABLE — this endpoint cannot currently be called by an arr at all.
//       Two platform layers stand in front of it, and an arr satisfies neither. nginx applies
//       `auth_request` to everything under /plugins/, so a request without a WebGUI session is
//       redirected to the login page. And Unraid's auto_prepend terminates every POST that
//       does not carry a valid CSRF token — which an arr has no way to obtain.
//
//       The live path is the standalone Node listener, Arrs_Stack/webhook_listener.js, running
//       on WEBHOOK_PORT outside nginx entirely and validating WEBHOOK_SECRET itself. That is
//       what the arrs are pointed at, and it is why it exists.
//
//       This file is therefore dead code kept for reference, not a second live entry point.
//       Nothing here authenticates, because nothing here can be reached. Do not "fix" it by
//       adding a secret check and re-pointing an arr at it — it would still be blocked by the
//       two layers above. If it is ever wanted as a real entry point it needs to be served
//       from outside /plugins/, at which point it needs WEBHOOK_SECRET validation first.
//       Removing it outright is the other reasonable option. See README-unraid.md.
//
// REQUEST
//   POST <arr webhook JSON body>
//        eventType=Test        → connection acknowledgement
//        eventType=Download    → dispatches the handler
//        any other eventType   → acknowledged and skipped
//
// RESPONSE
//   {"ok":true,"arr":"sonarr|radarr|lidarr","path":"…"}   dispatched
//   {"ok":true,"message":"Webhook connected — …"}         Test
//   {"ok":true,"skipped":"<event>|DOWNLOAD_WEBHOOK_ENABLED=false"}
//   {"ok":false,"error":…} with 405 / 400 / 500 as appropriate
//
// DEPENDS ON
//   include/config.php   vv_conf_vars(), SCRIPTS_DIR
//   Media/upgrade_webhook_handler.sh   the backgrounded handler
//   master.conf          DOWNLOAD_WEBHOOK_ENABLED
// ═══════════════════════════════════════════════════════════════════════════════════════════════
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]);
