<?php
// ═══════════════════════════════════════════════════════════════════════════════════════════════
// PURPOSE
//   Custom script CRUD. Reads, saves and deletes the user-authored scripts behind the
//   scheduler page's "+ Create Script" editor.
//
// OPERATIONAL MODEL
//   Custom scripts live in CUSTOM_SCRIPTS_DIR, outside the git repo entirely — alongside the
//   User Scripts plugin's own storage. That is what keeps them out of the pushed repository
//   and lets them survive a git pull that rewrites everything under SCRIPTS_DIR. Any .sh file
//   dropped into that folder by hand is picked up too; it does not have to be created here.
//
//   The Custom/ prefix is a namespace, not a directory under SCRIPTS_DIR. Ids are
//   Custom/<name>.sh everywhere in the scheduler, and vv_cron_rebuild() is the other half of
//   the convention — it maps that prefix onto CUSTOM_SCRIPTS_DIR when generating cron lines.
//
//   Saving also registers. A new script gets a disabled, unscheduled entry in schedule.json so
//   it appears in the job list immediately; the user then schedules it through scheduler.php.
//
// DESIGN PRINCIPLES
//   Names, not paths, on the write side.
//       POST takes a bare name and composes the id and the path from it. There is no way to
//       express a subdirectory, so the flat namespace is a property of the interface rather
//       than something validation has to enforce afterwards.
//
//   Delete removes the script and its schedule entry together.
//       Unlink, drop the schedule key, save, rebuild the cron. Leaving a schedule entry for a
//       script that no longer exists would put a cron line in place for a missing file.
//
//   Reading a script that does not exist returns empty content, not an error.
//       The editor opens the same way for a new script and an existing one.
//
// OPERATIONAL SAFEGUARDS
//   The read id is constrained to the Custom namespace.
//       ^Custom/[a-zA-Z0-9_\-]+\.sh$ plus a '..' check — no dots in the name, no nested path,
//       no other prefix. This endpoint cannot be used to read a repo script; that is
//       readscript.php, which has its own extension allowlist.
//
//   The write name excludes every path character.
//       ^[a-zA-Z0-9_\-]+$ — no slash, no dot, no traversal sequence can be expressed, so the
//       composed path is always a direct child of CUSTOM_SCRIPTS_DIR. The name pattern is
//       stricter than the read pattern because it is what constructs the filename.
//
//   The script write is atomic, and executable before it is visible.
//       tmp + chmod 0755 + rename. An enabled custom script can be launched by cron at any
//       moment; writing in place would let it fire against a truncated file, and chmod after
//       the write would let it fire against a non-executable one.
//
//   Delete confirms existence first, so a repeated delete reports a clear "Script not found"
//   rather than silently rebuilding the cron for nothing.
//
//   Unknown methods are refused explicitly at the end, so a PUT or DELETE cannot fall through
//   the two handled blocks into an empty 200.
//
//   Accepted by design: this endpoint writes an executable root-run script from a browser.
//       That is the entire feature, and it is why it is confined to a directory outside the
//       repo with a flat namespace and a strict name pattern. The save and delete paths are
//       POST, so Unraid's auto_prepend validates a CSRF token before any of this runs; the
//       WebGUI session is the outer boundary. See README-unraid.md.
//
// REQUEST
//   GET  ?id=Custom/<name>.sh                       read (empty content when absent)
//   POST name=<name>  content=<script text>         save or overwrite (action defaults to save)
//   POST name=<name>  action=delete                 delete script and schedule entry
//
// RESPONSE
//   {"ok":true,"content":"…"}                       read
//   {"ok":true,"id":"Custom/<name>.sh"}             save
//   {"ok":true}                                     delete
//   {"ok":false,"error":"Invalid id"|"Name must be letters, numbers, _ or - only"
//                      |"Script not found"|"Failed to write script"|"Method not allowed"}
//
// DEPENDS ON
//   include/scheduler.php   vv_schedule_load(), vv_schedule_save(), vv_cron_rebuild()
//   include/config.php      CUSTOM_SCRIPTS_DIR
// ═══════════════════════════════════════════════════════════════════════════════════════════════
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/scheduler.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = trim($_GET['id'] ?? '');
    if (!$id || !preg_match('/^Custom\/[a-zA-Z0-9_\-]+\.sh$/', $id) || str_contains($id, '..')) {
        echo json_encode(['ok' => false, 'error' => 'Invalid id']);
        exit;
    }
    $path = CUSTOM_SCRIPTS_DIR . '/' . substr($id, strlen('Custom/'));
    echo json_encode(['ok' => true, 'content' => file_exists($path) ? file_get_contents($path) : '']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action  = trim($_POST['action'] ?? 'save');
    $name    = trim($_POST['name'] ?? '');
    $content = $_POST['content'] ?? '';

    if (!$name || !preg_match('/^[a-zA-Z0-9_\-]+$/', $name)) {
        echo json_encode(['ok' => false, 'error' => 'Name must be letters, numbers, _ or - only']);
        exit;
    }

    $id   = 'Custom/' . $name . '.sh';
    $path = CUSTOM_SCRIPTS_DIR . '/' . $name . '.sh';

    if ($action === 'delete') {
        if (!file_exists($path)) {
            echo json_encode(['ok' => false, 'error' => 'Script not found']);
            exit;
        }
        unlink($path);
        $schedule = vv_schedule_load();
        unset($schedule[$id]);
        vv_schedule_save($schedule);
        vv_cron_rebuild($schedule);
        echo json_encode(['ok' => true]);
        exit;
    }

    $dir = CUSTOM_SCRIPTS_DIR;
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    // tmp + chmod + rename — an enabled script can be launched by cron at any moment, and a
    // half-written or not-yet-executable file would run as a truncated script.
    $tmp = $path . '.vv.tmp';
    if (file_put_contents($tmp, $content) === false) {
        @unlink($tmp);
        echo json_encode(['ok' => false, 'error' => 'Failed to write script']);
        exit;
    }
    chmod($tmp, 0755);
    if (!rename($tmp, $path)) {
        @unlink($tmp);
        echo json_encode(['ok' => false, 'error' => 'Failed to write script']);
        exit;
    }

    // Ensure schedule.json has an entry so the script appears in the job list
    $schedule = vv_schedule_load();
    if (!isset($schedule[$id])) {
        $schedule[$id] = ['id' => $id, 'enabled' => false, 'cron' => '', 'log_enabled' => false, 'updated' => date('c')];
        vv_schedule_save($schedule);
    }

    echo json_encode(['ok' => true, 'id' => $id]);
    exit;
}

echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
