<?php
/**
 * kickstart.php — bare-metal restore for FreeScout backups
 * Part of the Backup module by let's automate GmbH (https://letsautomate.ch)
 * Licensed under the AGPL-3.0, same as the module it belongs to.
 *
 * A single self-contained file that rebuilds a whole FreeScout instance from
 * one .fsback archive onto an empty directory. Nothing needs to be installed
 * first — not FreeScout, not the modules, not Composer.
 *
 * ---------------------------------------------------------------------------
 * HOW TO USE
 * ---------------------------------------------------------------------------
 *   1. Upload this file into the (empty) web root of the target host.
 *   2. Put the .fsback archive next to it -- or let step 2 fetch it from a
 *      URL (such as the «Link for kickstart» from the Backups page) or
 *      straight from S3 storage (Swiss Backup, Amazon S3 and others).
 *   3. Open kickstart.php in a browser and follow the wizard.
 *   4. Delete this file when the wizard tells you to. It offers to do it.
 *
 * ---------------------------------------------------------------------------
 * WHAT AN .fsback ACTUALLY CONTAINS — AND WHAT IT DOES NOT
 * ---------------------------------------------------------------------------
 * The archive (a tar.gz under a distinct extension) holds exactly four things:
 *
 *   manifest.json   app version, module versions, creation timestamp
 *   database.sql    full mysqldump (--single-transaction --routines --triggers)
 *   storage_app/    storage/app — uploads, avatars, logos
 *   modules/        the whole Modules/ tree
 *
 * It never holds FreeScout itself. Whether it holds the APP_KEY depends on
 * which of the two archive variants it is:
 *
 *   .fsback      no archive password. A plain tar.gz, openable with any tar,
 *                and WITHOUT the APP_KEY — an unencrypted file must not carry
 *                the key that decrypts the credentials inside it.
 *   .fsback.enc  an archive password was set. The same tar.gz, encrypted with
 *                AES-256-GCM, and because it now protects its own contents it
 *                also carries the APP_KEY in its manifest. A restore from one
 *                of these needs nothing but the password.
 *
 * So this script does two things the archive cannot:
 *
 *   FreeScout core. Fetched from GitHub at the version manifest.json names.
 *   That works because freescout-help-desk/freescout commits its vendor/
 *   directory, so the source zipball is a runnable instance — no Composer on
 *   the target host. A locally supplied zip works too, for hosts with no
 *   outbound network.
 *
 *   APP_KEY, for an unencrypted archive. This is the one that bites. Laravel
 *   encrypts several columns with it, and with a fresh key those rows survive
 *   the restore as undecryptable noise: mailboxes.in_password and
 *   out_password, the OAuth a_token/r_token pairs, the Bexio module's tokens,
 *   and the Calendar module's connection credentials. Vault is unaffected — it
 *   encrypts in the browser against the user's own passphrase, so APP_KEY
 *   never touches it. The wizard therefore asks for the old key and only
 *   generates a new one if you say so, with that consequence spelled out. For
 *   an encrypted archive none of this arises: the key comes out of the
 *   manifest, and the wizard says so instead of asking.
 *
 * ---------------------------------------------------------------------------
 * WHY IT IS BUILT THE WAY IT IS
 * ---------------------------------------------------------------------------
 * Resumable in small steps, because the work outlasts a PHP request. Every
 * phase runs against a wall-clock budget (BUDGET_SECONDS), saves where it got
 * to in kickstart-state.php, and is called again by the browser until it
 * reports done. That is what makes this survive a 30-second
 * max_execution_time on shared hosting.
 *
 * The phases resume differently, because their formats differ:
 *
 *   An encrypted archive is decrypted first, as its own phase, into an
 *   ordinary tar.gz. Its blocks are independent and fixed-size, so this is the
 *   one phase that resumes exactly, at a byte offset.
 *
 *   The core zip is a ZIP — random-access per entry, so it resumes at an
 *   entry index.
 *
 *   database.sql is a plain file — resumes at a byte offset.
 *
 *   The .fsback is a single gzip stream, and PHP cannot checkpoint zlib's
 *   inflate state. So it cannot resume mid-stream. Instead a resumed run
 *   re-reads the stream from the beginning and skips the entries it already
 *   wrote. Decompression is cheap next to disk writes, so each run still
 *   makes real forward progress. If the system `tar` is usable it is used
 *   instead, in one call, and this whole problem disappears.
 *
 * Files are extracted straight to their final location rather than to a work
 * directory first, so a restore needs roughly the size of the instance rather
 * than twice that. Two things are staged in the scratch directory:
 * database.sql, because it has to be read repeatedly, and — for an encrypted
 * archive — the decrypted copy.
 *
 * That scratch directory is the sharpest edge in this script, because while it
 * exists it holds a plaintext database dump and possibly a decrypted archive,
 * inside a web root. Its name therefore carries a random suffix, and
 * step_finalise() deletes it as soon as the restore is complete rather than
 * leaving it for the optional cleanup button.
 *
 * ---------------------------------------------------------------------------
 * SECURITY
 * ---------------------------------------------------------------------------
 * This script can overwrite a directory and drop a database. It must never be
 * reachable by anyone but the person doing the restore, so it will not do
 * anything at all until a token is presented.
 *
 * On first load it writes a random token to kickstart-token.php beside itself
 * and asks you to read it back. That is a deliberate proof of filesystem
 * access: whoever is restoring just uploaded this file, so they have it, and a
 * passer-by does not. The token then rides in a cookie and is compared with
 * hash_equals on every request.
 *
 * Token and state are PHP files that end the request before their content
 * (see GUARD_LINE). Up to 1.0.0 they were kickstart-token.txt and
 * kickstart-state.json, and the web server handed both out to anyone who
 * asked: the state holds the archive password, the APP_KEY from the archive,
 * the database credentials and the name of the scratch directory with the
 * decrypted dump.
 *
 * Archive paths are sanitised before anything is written — no absolute paths,
 * no traversal, no symlinks, no device nodes.
 *
 * When the restore finishes the script refuses to run again until its state
 * file is removed, and offers to delete itself along with the token and state.
 * Take that offer.
 */

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/** Wall-clock seconds one step may use before yielding to the next request.
 * Comfortably under a 30-second max_execution_time, with room for the
 * response itself. */
const BUDGET_SECONDS = 8;

/** Bytes per read while extracting or downloading. 1 MB is a good balance
 * between syscall overhead and memory. */
const CHUNK_BYTES = 1048576;

/** Where the core comes from. codeload serves the tag archive directly
 * without an API call or a token. */
const CORE_REPO = 'freescout-help-desk/freescout';
const CORE_ZIP_URL = 'https://codeload.github.com/freescout-help-desk/freescout/zip/refs/tags/';

const TOKEN_FILE = 'kickstart-token.php';
const STATE_FILE = 'kickstart-state.php';

/** First line of the token and state files. Both sit in the web root, because
 * that is the one directory this script is sure it may write to, and a web
 * server serves whatever lies there. A .json or .txt goes out as it is; a
 * .php file is executed instead, and this line ends that execution before a
 * byte of the content follows. It holds on every host that can run
 * kickstart.php at all, Apache, nginx and LiteSpeed alike, without depending
 * on .htaccess (nginx ignores it) or on file modes (with PHP and the web
 * server running as the same user, 0600 protects nothing). */
const GUARD_LINE = "<?php http_response_code(404); exit; ?>\n";

/** Names used up to 1.0.0. Removed on sight, since a leftover from an earlier
 * run is exactly the readable file this version exists to prevent. */
const LEGACY_FILES = ['kickstart-token.txt', 'kickstart-state.json'];

/** Prefix of the scratch directory. The actual name gets a random suffix per
 * run — see work_dir(). While a restore is in flight this directory holds the
 * plaintext database dump and, for an encrypted archive, a fully DECRYPTED
 * copy of it, both inside the web root. A guessable name would put those one
 * URL away from anybody. */
const WORK_DIR_PREFIX = 'kickstart-work';

const VERSION = '1.1.0';

// ---------------------------------------------------------------------------
// Bootstrap
// ---------------------------------------------------------------------------

@set_time_limit(0);
@ini_set('memory_limit', '256M');
ignore_user_abort(true);
error_reporting(E_ALL);
@ini_set('display_errors', '0');

if (version_compare(PHP_VERSION, '7.2.0', '<')) {
    die('kickstart.php benötigt PHP 7.2 oder neuer. Gefunden: '.PHP_VERSION);
}

// Defined beforehand only by the test runs, which point it at a scratch
// directory so state and work files never land in the module folder.
if (!defined('KS_ROOT')) {
    define('KS_ROOT', __DIR__);
}
define('KS_SELF', basename(__FILE__));

foreach (LEGACY_FILES as $legacy) {
    @unlink(KS_ROOT.'/'.$legacy);
}
unset($legacy);

// ---------------------------------------------------------------------------
// State — one JSON file, so every step knows where the last one stopped
// ---------------------------------------------------------------------------

function state_path()
{
    return KS_ROOT.'/'.STATE_FILE;
}

/** Reads a file written by guarded_write(), without its guard line. */
function guarded_read($path)
{
    if (!is_file($path)) {
        return null;
    }
    $raw = (string) @file_get_contents($path);
    if (strpos($raw, GUARD_LINE) === 0) {
        $raw = substr($raw, strlen(GUARD_LINE));
    }

    return $raw;
}

/** Writes $content behind GUARD_LINE, atomically, and readable only by the
 * owner as a second fence where file modes do count. The temporary file ends
 * in .php as well: a request that lands between write and rename must not
 * find a plain-text copy either. */
function guarded_write($path, $content)
{
    $tmp = $path.'.tmp.php';
    if (@file_put_contents($tmp, GUARD_LINE.$content) === false) {
        return false;
    }
    @chmod($tmp, 0600);

    return @rename($tmp, $path);
}

function state_load()
{
    $raw = guarded_read(state_path());
    if ($raw === null) {
        return [];
    }
    $data = json_decode($raw, true);

    return is_array($data) ? $data : [];
}

function state_save(array $state)
{
    // Written atomically: a half-written state file after a killed request
    // would strand the restore with no way to tell how far it got.
    guarded_write(state_path(), json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function state_set($key, $value)
{
    $state = state_load();
    $state[$key] = $value;
    state_save($state);

    return $state;
}

function state_get($key, $default = null)
{
    $state = state_load();

    return array_key_exists($key, $state) ? $state[$key] : $default;
}

/** The scratch directory for this run, created on first use with a random
 * suffix that is remembered in the state file.
 *
 * Everything in here is deleted by step_finalise() as soon as the restore is
 * complete, rather than left for the cleanup button: the button is optional
 * and easy to skip, and what is in here is a plaintext dump of the whole
 * database plus a decrypted archive. The random name only narrows the window;
 * the deletion closes it. */
function work_dir()
{
    $suffix = state_get('work_suffix');
    if (!$suffix) {
        $suffix = bin2hex(random_bytes(8));
        state_set('work_suffix', $suffix);
    }

    return KS_ROOT.'/'.WORK_DIR_PREFIX.'-'.$suffix;
}

// ---------------------------------------------------------------------------
// Token gate
// ---------------------------------------------------------------------------

function token_read()
{
    $raw = guarded_read(KS_ROOT.'/'.TOKEN_FILE);

    return $raw === null ? null : trim($raw);
}

/** Creates the token on first load. Returns null when it cannot be written —
 * an unwritable directory is itself a blocker the wizard needs to report,
 * rather than silently running without a gate. */
function token_ensure()
{
    $existing = token_read();
    if ($existing !== null && $existing !== '') {
        return $existing;
    }

    $token = bin2hex(random_bytes(16));
    if (!guarded_write(KS_ROOT.'/'.TOKEN_FILE, $token."\n")) {
        return null;
    }

    return $token;
}

function token_supplied()
{
    if (isset($_POST['ks_token'])) {
        return trim((string) $_POST['ks_token']);
    }
    if (isset($_COOKIE['ks_token'])) {
        return trim((string) $_COOKIE['ks_token']);
    }

    return '';
}

function token_valid()
{
    $expected = token_read();
    $given = token_supplied();

    return $expected !== null && $expected !== '' && $given !== ''
        && hash_equals($expected, $given);
}

// ---------------------------------------------------------------------------
// Small helpers
// ---------------------------------------------------------------------------

function human_bytes($bytes)
{
    $bytes = (float) $bytes;
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }

    return ($i === 0 ? (int) $bytes : round($bytes, 1)).' '.$units[$i];
}

function ensure_dir($path)
{
    if (is_dir($path)) {
        return true;
    }

    return @mkdir($path, 0755, true) || is_dir($path);
}

function rmtree($path)
{
    if (is_link($path) || is_file($path)) {
        return @unlink($path);
    }
    if (!is_dir($path)) {
        return true;
    }
    foreach (scandir($path) as $entry) {
        if ($entry === '.' || $entry === '..') {
            continue;
        }
        rmtree($path.'/'.$entry);
    }

    return @rmdir($path);
}

/** Whether shell commands are actually usable. exec() being defined is not
 * enough — it is very often in disable_functions on shared hosting. */
function shell_available()
{
    if (!function_exists('exec')) {
        return false;
    }
    $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
    if (in_array('exec', $disabled, true)) {
        return false;
    }
    $out = [];
    $code = 1;
    @exec('echo kickstart 2>&1', $out, $code);

    return $code === 0 && in_array('kickstart', array_map('trim', $out), true);
}

function have_binary($name)
{
    if (!shell_available()) {
        return false;
    }
    $out = [];
    $code = 1;
    @exec('command -v '.escapeshellarg($name).' 2>/dev/null', $out, $code);

    return $code === 0 && !empty($out[0]);
}

function budget_expired($startedAt)
{
    return (microtime(true) - $startedAt) >= BUDGET_SECONDS;
}

/** Rejects anything in an archive that must not be written: absolute paths,
 * traversal, and Windows drive letters. Returns the cleaned relative path, or
 * null to skip the entry. */
function safe_relative_path($path)
{
    $path = str_replace('\\', '/', (string) $path);
    $path = preg_replace('#^\./#', '', $path);
    $path = ltrim($path, '/');

    if ($path === '' || preg_match('#^[a-zA-Z]:#', $path)) {
        return null;
    }

    $parts = [];
    foreach (explode('/', $path) as $part) {
        if ($part === '' || $part === '.') {
            continue;
        }
        if ($part === '..') {
            return null;   // never resolve upward — just refuse the entry
        }
        $parts[] = $part;
    }

    return $parts ? implode('/', $parts) : null;
}

/** Maps an archive entry onto its destination inside the instance. Returns
 * null for anything outside the four known top-level names, so a tampered
 * archive cannot drop files wherever it likes. */
function map_archive_entry($relative)
{
    $relative = safe_relative_path($relative);
    if ($relative === null) {
        return null;
    }

    if ($relative === 'manifest.json' || $relative === 'database.sql') {
        return ['kind' => 'work', 'path' => work_dir().'/'.$relative];
    }
    if (strpos($relative, 'storage_app/') === 0) {
        return ['kind' => 'storage', 'path' => KS_ROOT.'/storage/app/'.substr($relative, strlen('storage_app/'))];
    }
    if (strpos($relative, 'modules/') === 0) {
        return ['kind' => 'modules', 'path' => KS_ROOT.'/Modules/'.substr($relative, strlen('modules/'))];
    }

    return null;
}

// ---------------------------------------------------------------------------
// Encrypted archives
// ---------------------------------------------------------------------------

/** Reader for the .fsback.enc format written by Support/ArchiveCipher.
 *
 * A deliberate copy rather than a shared file: this script has to work with
 * nothing else present, so it cannot require the module it came from. The
 * format is documented in full in ArchiveCipher's docblock; the constants
 * below have to stay in step with it, which is why they name the same values
 * rather than inventing new ones.
 *
 * Decryption happens as its own phase, into an ordinary .tar.gz in the work
 * directory, and everything downstream is then unchanged. Decrypting on the
 * fly under the gzip reader would avoid the temporary copy, but it would mean
 * a custom stream wrapper wrapped in compress.zlib://, and the system-tar path
 * could not use it at all — tar cannot read an encrypted file either way. One
 * extra archive-sized file on disk buys a much simpler and testable path.
 *
 * It resumes cleanly, unlike the gzip stream: blocks are independent and
 * fixed-size, so the next request seeks straight to where the last one
 * stopped. */
const ENC_MAGIC = "FSBACKENC\x01";
const ENC_HEADER_LENGTH = 48;
const ENC_CIPHER = 'aes-256-gcm';
const ENC_IV_LENGTH = 12;
const ENC_TAG_LENGTH = 16;

function enc_available()
{
    return extension_loaded('openssl') && in_array(ENC_CIPHER, openssl_get_cipher_methods(), true);
}

function enc_is_encrypted($path)
{
    $handle = @fopen($path, 'rb');
    if (!$handle) {
        return false;
    }
    $magic = fread($handle, strlen(ENC_MAGIC));
    fclose($handle);

    return $magic === ENC_MAGIC;
}

/** Parses the fixed header. Every field is bounds-checked before use, so a
 * hostile file cannot turn into an allocation or a loop bound. */
function enc_parse_header($header)
{
    if (strlen($header) < ENC_HEADER_LENGTH || strncmp($header, ENC_MAGIC, strlen(ENC_MAGIC)) !== 0) {
        throw new RuntimeException('Keine verschlüsselte FreeScout-Sicherung (Kennung passt nicht).');
    }
    if (ord($header[10]) !== 1) {
        throw new RuntimeException('Unbekanntes Verschlüsselungsverfahren im Archiv.');
    }
    if (ord($header[11]) !== 1) {
        throw new RuntimeException('Unbekanntes Schlüsselableitungsverfahren im Archiv.');
    }

    $iterations = unpack('N', substr($header, 12, 4))[1];
    $saltLength = ord($header[16]);
    $salt = substr($header, 17, $saltLength);
    $blockSize = unpack('N', substr($header, 33, 4))[1];
    $plainSize = unpack('J', substr($header, 37, 8))[1];

    if ($iterations < 1000 || $iterations > 10000000) {
        throw new RuntimeException('Unplausible Iterationszahl im Archivkopf.');
    }
    if ($saltLength !== 16 || strlen($salt) !== 16) {
        throw new RuntimeException('Falsche Salt-Länge im Archivkopf.');
    }
    if ($blockSize < 4096 || $blockSize > 67108864) {
        throw new RuntimeException('Unplausible Blockgrösse im Archivkopf.');
    }

    return [
        'iterations' => $iterations,
        'salt' => $salt,
        'block_size' => $blockSize,
        'plain_size' => $plainSize,
        'raw' => substr($header, 0, ENC_HEADER_LENGTH),
    ];
}

function enc_derive_key($password, $salt, $iterations)
{
    return hash_pbkdf2('sha256', $password, $salt, $iterations, 32, true);
}

/** Checks a password against the first block. Every block is authenticated
 * under a key derived from the password, so one block is proof enough — and it
 * makes a wrong password cost a moment instead of a whole pass. */
function enc_password_matches($path, $password)
{
    $handle = @fopen($path, 'rb');
    if (!$handle) {
        return false;
    }

    try {
        $meta = enc_parse_header(fread($handle, ENC_HEADER_LENGTH));
        $key = enc_derive_key($password, $meta['salt'], $meta['iterations']);

        $lengthBytes = fread($handle, 4);
        if (strlen((string) $lengthBytes) < 4) {
            return false;
        }
        $length = unpack('N', $lengthBytes)[1];
        if ($length < 1 || $length > $meta['block_size'] + 1024) {
            return false;
        }
        $iv = fread($handle, ENC_IV_LENGTH);
        $tag = fread($handle, ENC_TAG_LENGTH);
        $ciphertext = enc_read_exactly($handle, $length);
        if ($ciphertext === null) {
            return false;
        }

        return openssl_decrypt($ciphertext, ENC_CIPHER, $key, OPENSSL_RAW_DATA, $iv, $tag,
            $meta['raw'].pack('J', 0)) !== false;
    } catch (Throwable $e) {
        return false;
    } finally {
        fclose($handle);
    }
}

function enc_read_exactly($handle, $length)
{
    $buffer = '';
    while (strlen($buffer) < $length) {
        $chunk = fread($handle, $length - strlen($buffer));
        if ($chunk === false || $chunk === '') {
            return null;
        }
        $buffer .= $chunk;
    }

    return $buffer;
}

function decrypted_archive_path()
{
    return work_dir().'/archive.tar.gz';
}

// ---------------------------------------------------------------------------
// Pure-PHP tar reader
// ---------------------------------------------------------------------------

/** Opens a .fsback as an ordinary readable stream.
 *
 * The compress.zlib:// wrapper rather than the gz* function family: those
 * operate on a zlib resource that plain stream functions are not defined on,
 * while the wrapper yields a real stream that fread/feof/fseek all work with.
 * Everything below is written against plain stream functions, so this is the
 * only place that has to know the archive is compressed at all. */
function tar_open($path)
{
    return @fopen('compress.zlib://'.$path, 'rb');
}

/** Reads one 512-byte tar header. Returns null at the end-of-archive marker.
 *
 * Handles what GNU/busybox tar actually emits for this archive: regular files,
 * directories, GNU long names ('L'), and pax extended headers ('x'), whose
 * path record overrides the truncated name in the following header. Anything
 * else (symlinks, devices, fifos) is skipped rather than recreated — a restore
 * has no business creating device nodes, and a symlink is the classic way to
 * write outside the target directory. */
function tar_read_header($handle)
{
    $block = fread($handle, 512);
    if ($block === false || strlen($block) < 512) {
        return null;
    }
    // Two consecutive zero blocks end the archive; one is enough to stop.
    if (trim($block, "\0") === '') {
        return null;
    }

    $name = rtrim(substr($block, 0, 100), "\0");
    $sizeOctal = trim(substr($block, 124, 12), "\0 ");
    $type = substr($block, 156, 1);
    $prefix = rtrim(substr($block, 345, 155), "\0");

    $size = $sizeOctal === '' ? 0 : intval($sizeOctal, 8);
    if ($prefix !== '') {
        $name = $prefix.'/'.$name;
    }

    return ['name' => $name, 'size' => $size, 'type' => $type];
}

function tar_skip_body($handle, $size)
{
    $padded = $size + ((512 - ($size % 512)) % 512);
    if ($padded <= 0) {
        return;
    }
    // fseek on a gzip stream is a forward re-read, which is what we want and
    // all zlib can do; it is still far cheaper than writing the bytes out.
    $remaining = $padded;
    while ($remaining > 0) {
        $read = fread($handle, (int) min(CHUNK_BYTES, $remaining));
        if ($read === false || $read === '') {
            return;
        }
        $remaining -= strlen($read);
    }
}

// ---------------------------------------------------------------------------
// SQL statement splitter
// ---------------------------------------------------------------------------

/** Pulls complete statements out of a mysqldump, resumably.
 *
 * Reads from $offset, returns the statements it could complete plus the offset
 * to continue from, so the caller can stop whenever its time budget runs out
 * and pick up exactly where it left off.
 *
 * The parser has to cope with what mysqldump --routines --triggers actually
 * produces:
 *   - string literals containing semicolons, with '' and \' escapes
 *   - backtick identifiers
 *   - -- and # line comments, and block comments
 *   - /*!50003 ... *(/) version-gated blocks, which must be EXECUTED (MySQL
 *     reads them as SQL), unlike a plain comment which must be dropped
 *   - DELIMITER ;; around trigger and routine bodies, where the whole body
 *     contains ordinary semicolons that must not split anything
 */
function sql_next_statements($handle, $offset, $delimiter, $budgetStart)
{
    fseek($handle, $offset);

    $statements = [];
    // Per statement: the byte offset right after it and the delimiter in
    // force there, so a failed statement can be resumed at, not before it.
    $marks = [];
    $buffer = '';
    $consumed = $offset;
    // Scanner state carried from line to line, so every byte is looked at
    // once. Re-scanning the whole buffer after each line made one INSERT
    // with a few thousand embedded line breaks cost minutes (21.11.2026).
    $scan = sql_scan_start();

    while (!feof($handle)) {
        $line = fgets($handle);
        if ($line === false) {
            break;
        }
        $consumed += strlen($line);

        $trimmed = trim($line);

        // A DELIMITER directive is a client instruction, not SQL. It only
        // ever appears on a line of its own.
        if (preg_match('/^DELIMITER\s+(\S+)/i', $trimmed, $m)) {
            $delimiter = $m[1];
            continue;
        }

        // Whole-line comments. Note the deliberate exception: /*! ... is a
        // version-gated block that MySQL executes, so it is not a comment.
        if ($trimmed === '' || strpos($trimmed, '--') === 0 || strpos($trimmed, '#') === 0) {
            if ($buffer === '') {
                continue;
            }
        }

        $buffer .= $line;

        // Only look for the delimiter once the buffer is not inside a quote.
        if (sql_scan_line($scan, $line, $delimiter)) {
            $statement = substr($buffer, 0, strrpos($buffer, $delimiter));
            $statement = trim($statement);
            if ($statement !== '') {
                $statements[] = $statement;
                $marks[] = [$consumed, $delimiter];
            }
            $buffer = '';
            $scan = sql_scan_start();

            if (budget_expired($budgetStart) && $statements) {
                return [$statements, $consumed, $delimiter, false, $marks];
            }
        }
    }

    // Anything left in the buffer at EOF is a trailing statement without a
    // delimiter; mysqldump does not emit one, but a hand-edited file might.
    $tail = trim($buffer);
    if ($tail !== '') {
        $statements[] = $tail;
        $marks[] = [$consumed, $delimiter];
    }

    return [$statements, $consumed, $delimiter, true, $marks];
}

/** A fresh scanner state for sql_scan_line(): no open quote, no open block
 * comment. Line comments need no state, they end with their line. */
function sql_scan_start()
{
    return ['quote' => null, 'block' => false];
}

/** Scans one more line of a statement and reports whether the statement now
 * ends: $delimiter outside any quoted literal or comment, followed by
 * nothing but whitespace. Walks the line tracking state, because a regex
 * cannot: a semicolon inside 'a;b' must not end the statement. $state
 * carries an open quote or block comment over to the next line. */
function sql_scan_line(array &$state, $line, $delimiter)
{
    $len = strlen($line);
    $dlen = strlen($delimiter);

    $quote = $state['quote'];
    $inLineComment = false;
    $inBlockComment = $state['block'];
    $complete = false;

    for ($i = 0; $i < $len; $i++) {
        $c = $line[$i];
        $next = $i + 1 < $len ? $line[$i + 1] : '';

        if ($inLineComment) {
            if ($c === "\n") {
                $inLineComment = false;
            }
            continue;
        }
        if ($inBlockComment) {
            if ($c === '*' && $next === '/') {
                $inBlockComment = false;
                $i++;
            }
            continue;
        }
        if ($quote !== null) {
            if ($c === '\\' && $quote !== '`') {
                $i++;                       // escaped character
            } elseif ($c === $quote) {
                if ($next === $quote) {
                    $i++;                   // doubled quote is a literal one
                } else {
                    $quote = null;
                }
            }
            continue;
        }

        if ($c === "'" || $c === '"' || $c === '`') {
            $quote = $c;
            continue;
        }
        if ($c === '-' && $next === '-') {
            $inLineComment = true;
            $i++;
            continue;
        }
        if ($c === '#') {
            $inLineComment = true;
            continue;
        }
        // /*! is executable, not a comment — leave it in the statement.
        if ($c === '/' && $next === '*' && substr($line, $i + 2, 1) !== '!') {
            $inBlockComment = true;
            $i++;
            continue;
        }
        if ($c === $delimiter[0] && substr($line, $i, $dlen) === $delimiter) {
            // The delimiter counts only if nothing but whitespace follows.
            if (trim(substr($line, $i + $dlen)) === '') {
                $complete = true;
                break;
            }
            $i += $dlen - 1;
        }
    }

    $state['quote'] = $quote;
    $state['block'] = $inBlockComment;

    return $complete;
}

/** Strips the DEFINER clause from routine, trigger and view statements.
 *
 * mysqldump writes DEFINER=`someuser`@`somehost`, and CREATE fails outright
 * if that user does not exist on the target — which on a bare-metal restore
 * onto a new host is the normal case, not the exception. Dropping the clause
 * makes the object belong to whoever is importing. */
function sql_strip_definer($statement)
{
    if (stripos($statement, 'DEFINER') === false) {
        return $statement;
    }

    return preg_replace(
        '/DEFINER\s*=\s*(`(?:[^`]|``)*`|\'(?:[^\']|\'\')*\'|\S+)\s*@\s*(`(?:[^`]|``)*`|\'(?:[^\']|\'\')*\'|\S+)/i',
        '',
        $statement
    );
}

// ---------------------------------------------------------------------------
// Steps
// ---------------------------------------------------------------------------

/** Every step returns the same shape, so the browser loop stays trivial:
 *   done      true when this phase is finished
 *   progress  0..100, or null when it cannot be known
 *   message   one line for the log
 *   detail    optional second line
 */
function step_result($done, $progress, $message, $detail = null)
{
    return ['done' => (bool) $done, 'progress' => $progress, 'message' => $message, 'detail' => $detail];
}

// --- Preflight ------------------------------------------------------------

function checks_run()
{
    $checks = [];
    $add = function ($label, $ok, $detail, $fatal = false) use (&$checks) {
        $checks[] = ['label' => $label, 'ok' => $ok, 'detail' => $detail, 'fatal' => $fatal && !$ok];
    };

    $add('PHP-Version', version_compare(PHP_VERSION, '7.2.0', '>='), PHP_VERSION, true);

    foreach (['pdo_mysql' => true, 'zlib' => true, 'json' => true, 'mbstring' => false, 'zip' => false] as $ext => $required) {
        $loaded = extension_loaded($ext);
        $add(
            'Erweiterung '.$ext,
            $loaded || !$required,
            $loaded ? 'vorhanden' : ($required ? 'fehlt — zwingend' : 'fehlt — Ersatz vorhanden'),
            $required
        );
    }

    $writable = is_writable(KS_ROOT);
    $add('Verzeichnis beschreibbar', $writable, KS_ROOT, true);

    $free = @disk_free_space(KS_ROOT);
    $add('Freier Speicher', $free === false || $free > 500 * 1024 * 1024,
        $free === false ? 'unbekannt' : human_bytes($free));

    $shell = shell_available();
    $tar = $shell && have_binary('tar');
    $add('Systembefehl tar', $tar, $tar ? 'wird genutzt — deutlich schneller' : 'nicht verfügbar — PHP-Entpacker wird genutzt');

    $add('Shell-Zugriff', $shell, $shell ? 'vorhanden' : 'nicht vorhanden — kein Problem');

    $limit = (int) ini_get('max_execution_time');
    $add('max_execution_time', true, $limit === 0 ? 'unbegrenzt' : $limit.' s — Arbeit wird in Häppchen von '.BUDGET_SECONDS.' s erledigt');

    $add('Ausgehendes Netz', function_exists('curl_init') || ini_get('allow_url_fopen'),
        function_exists('curl_init') ? 'cURL vorhanden' : (ini_get('allow_url_fopen') ? 'allow_url_fopen aktiv'
            : 'nicht verfügbar — weder Core-Download noch Holen aus S3 oder von einer Adresse; das Archiv per SFTP hochladen'));

    return $checks;
}

// --- Archive discovery ----------------------------------------------------

function archives_available()
{
    $found = [];
    // Both variants: an unencrypted .fsback and an encrypted .fsback.enc.
    // The brace pattern keeps this to two globs instead of four.
    // Also look one level down, since people often upload into a subfolder.
    $paths = array_merge(glob(KS_ROOT.'/*.fsback{,.enc}', GLOB_BRACE) ?: [], glob(KS_ROOT.'/*/*.fsback{,.enc}', GLOB_BRACE) ?: []);
    foreach ($paths as $path) {
        $found[] = [
            'name' => ltrim(substr($path, strlen(KS_ROOT)), '/'),
            'size' => filesize($path),
            'size_human' => human_bytes(filesize($path)),
            'mtime' => date('d.m.Y H:i', filemtime($path)),
            'mtime_ts' => filemtime($path),
            'taken' => archive_taken_at($path),
            'encrypted' => enc_is_encrypted($path),
        ];
    }

    return $found;
}

/** When the backup was made, read from the name the module gives every
 * archive (freescout-backup-YYYY-MM-DD-HHMMSS…), in the source's local time.
 * The file time is no help: after a download it is the download, and the
 * server clock may well run in UTC. */
function archive_taken_at($path)
{
    if (preg_match('/freescout-backup-(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})\d{2}\.fsback/', basename($path), $m)) {
        return $m[3].'.'.$m[2].'.'.$m[1].' '.$m[4].':'.$m[5];
    }

    return null;
}

function archive_path()
{
    $name = state_get('archive');
    if (!$name) {
        return null;
    }
    $safe = safe_relative_path($name);
    if ($safe === null) {
        return null;
    }
    $path = KS_ROOT.'/'.$safe;

    return is_file($path) ? $path : null;
}

/** Reads manifest.json out of the archive without unpacking anything else.
 *
 * Scans until it finds the entry, which is not near the front: tar writes
 * members in directory order, and a real archive from this module starts with
 * the whole of modules/ — manifest.json turns up thousands of entries later.
 * An earlier version bailed out after 50 entries on the assumption that it
 * came first, and found nothing in any genuine archive.
 *
 * Scanning the whole stream is cheap because only headers are read and bodies
 * are skipped: no file is written and nothing is buffered. */
function archive_manifest($archivePath)
{
    $handle = tar_open($archivePath);
    if (!$handle) {
        return ['error' => 'Archiv konnte nicht geöffnet werden — ist es wirklich ein .fsback (tar.gz)?'];
    }

    $manifest = null;
    $entries = 0;
    try {
        while (($header = tar_read_header($handle)) !== null) {
            $entries++;
            $relative = safe_relative_path($header['name']);

            if ($relative === 'manifest.json' && $header['size'] > 0 && $header['size'] < 1048576) {
                $raw = '';
                $remaining = $header['size'];
                while ($remaining > 0) {
                    $read = fread($handle, (int) min(CHUNK_BYTES, $remaining));
                    if ($read === false || $read === '') {
                        break;
                    }
                    $raw .= $read;
                    $remaining -= strlen($read);
                }
                $manifest = json_decode($raw, true);
                break;
            }

            tar_skip_body($handle, $header['size']);
        }
    } finally {
        fclose($handle);
    }

    if (!is_array($manifest)) {
        return ['error' => 'Im Archiv wurde keine lesbare manifest.json gefunden ('.$entries
            .' Einträge durchsucht). Das sieht nicht nach einem Backup dieses Moduls aus.'];
    }

    return ['manifest' => $manifest];
}

// --- Archive download: from a URL or from S3 storage -----------------------
//
// For the case the archive is not on this host yet: a link (for example the
// «Link for kickstart» from the Backups page) or S3 storage such as Swiss
// Backup or Amazon S3. Downloaded in Range pieces within the step budget, so
// it survives a short max_execution_time, and resumable from the size of the
// .part file. The S3 secret key is used to list and to sign a download link,
// and is never written anywhere; the state keeps only the signed link.
//
// The signature is a copy of the module's S3Signer, because this file cannot
// load module code. Tests/kickstart_test.php holds both to the same AWS
// reference values so they cannot drift apart.

/** Bytes per Range request. */
const DOWNLOAD_CHUNK_BYTES = 8388608;

/** Names this module writes. Nothing else is downloaded. */
const ARCHIVE_NAME_PATTERN = '/^freescout-backup-\d{4}-\d{2}-\d{2}-\d{6}\.fsback(\.enc)?$/';

function ks_s3_endpoint($cfg)
{
    $endpoint = trim((string) ($cfg['endpoint'] ?? ''));
    $region = trim((string) ($cfg['region'] ?? '')) ?: 'us-east-1';
    if ($endpoint === '') {
        return 'https://s3.'.$region.'.amazonaws.com';
    }
    if (!preg_match('#^[a-z][a-z0-9+.-]*://#i', $endpoint)) {
        $endpoint = 'https://'.$endpoint;
    }
    $p = parse_url($endpoint);
    if ($p === false || empty($p['host'])) {
        return rtrim($endpoint, '/');
    }

    return strtolower($p['scheme']).'://'.strtolower($p['host']).(isset($p['port']) ? ':'.$p['port'] : '');
}

function ks_s3_encode_path($path)
{
    return implode('/', array_map('rawurlencode', explode('/', $path)));
}

/** URL of $key (unencoded) in the bucket, path style or virtual-hosted. */
function ks_s3_url($cfg, $key, array $query = [])
{
    $p = parse_url(ks_s3_endpoint($cfg));
    $port = isset($p['port']) ? ':'.$p['port'] : '';
    $bucket = trim((string) $cfg['bucket']);
    $url = !empty($cfg['path_style'])
        ? $p['scheme'].'://'.$p['host'].$port.'/'.$bucket.'/'.ks_s3_encode_path($key)
        : $p['scheme'].'://'.$bucket.'.'.$p['host'].$port.'/'.ks_s3_encode_path($key);
    if ($query) {
        $pairs = [];
        foreach ($query as $k => $v) {
            $pairs[] = $v === '' ? rawurlencode($k) : rawurlencode($k).'='.rawurlencode($v);
        }
        $url .= '?'.implode('&', $pairs);
    }

    return $url;
}

function ks_s3_canonical_query(array $query)
{
    $encoded = [];
    foreach ($query as $k => $v) {
        $encoded[rawurlencode((string) $k)] = rawurlencode((string) $v);
    }
    ksort($encoded, SORT_STRING);
    $pairs = [];
    foreach ($encoded as $k => $v) {
        $pairs[] = $k.'='.$v;
    }

    return implode('&', $pairs);
}

/** Splits an URL into host (with a non-default port), encoded path and query. */
function ks_s3_split($url)
{
    $p = parse_url($url);
    $scheme = strtolower($p['scheme'] ?? 'https');
    $host = strtolower($p['host']);
    if (isset($p['port']) && !(($scheme === 'https' && $p['port'] == 443) || ($scheme === 'http' && $p['port'] == 80))) {
        $host .= ':'.$p['port'];
    }
    $query = [];
    if (isset($p['query']) && $p['query'] !== '') {
        foreach (explode('&', $p['query']) as $pair) {
            if ($pair === '') {
                continue;
            }
            $kv = explode('=', $pair, 2);
            $query[rawurldecode($kv[0])] = isset($kv[1]) ? rawurldecode($kv[1]) : '';
        }
    }

    return [$scheme, $host, ks_s3_encode_path(rawurldecode($p['path'] ?? '/')), $query];
}

function ks_s3_signature($cfg, $now, $amzDate, $scope, $canonicalRequest)
{
    $region = trim((string) ($cfg['region'] ?? '')) ?: 'us-east-1';
    $toSign = "AWS4-HMAC-SHA256\n".$amzDate."\n".$scope."\n".hash('sha256', $canonicalRequest);
    $key = hash_hmac('sha256', gmdate('Ymd', $now), 'AWS4'.$cfg['secret_key'], true);
    $key = hash_hmac('sha256', $region, $key, true);
    $key = hash_hmac('sha256', 's3', $key, true);
    $key = hash_hmac('sha256', 'aws4_request', $key, true);

    return hash_hmac('sha256', $toSign, $key);
}

/** Signed request headers (SigV4) for a request without a body. */
function ks_s3_sign_headers($cfg, $method, $url, $now = null)
{
    $now = $now === null ? time() : $now;
    $amzDate = gmdate('Ymd\THis\Z', $now);
    $region = trim((string) ($cfg['region'] ?? '')) ?: 'us-east-1';
    list(, $host, $path, $query) = ks_s3_split($url);
    $hash = hash('sha256', '');
    $canonical = $method."\n".$path."\n".ks_s3_canonical_query($query)."\n"
        .'host:'.$host."\nx-amz-content-sha256:".$hash."\nx-amz-date:".$amzDate."\n\n"
        ."host;x-amz-content-sha256;x-amz-date\n".$hash;
    $scope = gmdate('Ymd', $now).'/'.$region.'/s3/aws4_request';

    return [
        'x-amz-content-sha256: '.$hash,
        'x-amz-date: '.$amzDate,
        'Authorization: AWS4-HMAC-SHA256 Credential='.$cfg['access_key'].'/'.$scope
            .',SignedHeaders=host;x-amz-content-sha256;x-amz-date,Signature='
            .ks_s3_signature($cfg, $now, $amzDate, $scope, $canonical),
    ];
}

/** Presigned GET link for $key, valid for $seconds (at most 604800). */
function ks_s3_presign($cfg, $key, $seconds, $now = null)
{
    $now = $now === null ? time() : $now;
    $amzDate = gmdate('Ymd\THis\Z', $now);
    $region = trim((string) ($cfg['region'] ?? '')) ?: 'us-east-1';
    $scope = gmdate('Ymd', $now).'/'.$region.'/s3/aws4_request';
    list($scheme, $host, $path, $query) = ks_s3_split(ks_s3_url($cfg, $key));
    $query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
    $query['X-Amz-Credential'] = $cfg['access_key'].'/'.$scope;
    $query['X-Amz-Date'] = $amzDate;
    $query['X-Amz-Expires'] = (string) min((int) $seconds, 604800);
    $query['X-Amz-SignedHeaders'] = 'host';
    $canonicalQuery = ks_s3_canonical_query($query);
    $canonical = "GET\n".$path."\n".$canonicalQuery."\nhost:".$host."\n\nhost\nUNSIGNED-PAYLOAD";

    return $scheme.'://'.$host.$path.'?'.$canonicalQuery
        .'&X-Amz-Signature='.ks_s3_signature($cfg, $now, $amzDate, $scope, $canonical);
}

/** Text of the first <$tag> in $xml, entity-decoded. */
function ks_xml_value($xml, $tag)
{
    return preg_match('#<'.$tag.'>(.*?)</'.$tag.'>#s', $xml, $m) ? html_entity_decode($m[1], ENT_QUOTES | ENT_XML1, 'UTF-8') : '';
}

/** Archives under $prefix, newest first: [['key', 'size', 'modified'], …],
 * or ['error' => …] with a sentence that never contains the secret key. */
function ks_s3_list($cfg, $prefix)
{
    if (!function_exists('curl_init')) {
        return ['error' => 'cURL fehlt auf diesem Host.'];
    }
    $found = [];
    $token = null;
    do {
        $query = ['list-type' => '2', 'prefix' => (string) $prefix];
        if ($token !== null) {
            $query['continuation-token'] = $token;
        }
        $url = ks_s3_url($cfg, '', $query);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ks_s3_sign_headers($cfg, 'GET', $url),
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
        ]);
        $body = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($body === false) {
            return ['error' => 'Keine Verbindung zum Speicher: '.curl_error($ch)];
        }
        if ($status >= 300) {
            $code = ks_xml_value($body, 'Code') ?: 'HTTP'.$status;
            $hints = [
                'SignatureDoesNotMatch' => 'Der geheime Schlüssel passt nicht zum Zugriffsschlüssel.',
                'InvalidAccessKeyId' => 'Der Zugriffsschlüssel ist dem Speicher unbekannt.',
                'AuthorizationHeaderMalformed' => 'Die Region passt nicht zum Bucket.',
                'NoSuchBucket' => 'Den Bucket gibt es nicht.',
                'AccessDenied' => 'Der Schlüssel darf diesen Bucket nicht auflisten.',
                'RequestTimeTooSkewed' => 'Die Uhr dieses Servers geht falsch.',
            ];

            return ['error' => trim(($hints[$code] ?? '').' S3: '.$code.' (HTTP '.$status.') '.ks_xml_value($body, 'Message'))];
        }
        preg_match_all('#<Contents>(.*?)</Contents>#s', $body, $entries);
        foreach ($entries[1] as $entry) {
            $key = ks_xml_value($entry, 'Key');
            if (preg_match(ARCHIVE_NAME_PATTERN, basename($key))) {
                $found[] = ['key' => $key, 'size' => (int) ks_xml_value($entry, 'Size'), 'modified' => ks_xml_value($entry, 'LastModified')];
            }
        }
        $token = ks_xml_value($body, 'IsTruncated') === 'true' ? ks_xml_value($body, 'NextContinuationToken') : null;
    } while ($token !== null && $token !== '');

    usort($found, function ($a, $b) {
        return strcmp(basename($b['key']), basename($a['key']));
    });

    return $found;
}

/** Whether a response to a Range request starting at $offset may be appended. */
function download_response_ok($status, $contentRange, $offset)
{
    if ($status === 206) {
        if (!preg_match('#bytes (\d+)-(\d+)/(\d+|\*)#', (string) $contentRange, $m)) {
            return ['ok' => false, 'total' => null, 'error' => 'Die Antwort trägt keinen gültigen Content-Range.'];
        }
        if ((int) $m[1] !== (int) $offset) {
            return ['ok' => false, 'total' => null, 'error' => 'Der Server lieferte ab Byte '.$m[1].' statt '.$offset.'.'];
        }

        return ['ok' => true, 'total' => $m[3] === '*' ? null : (int) $m[3], 'error' => null];
    }
    if ($status === 200) {
        if ((int) $offset === 0) {
            return ['ok' => true, 'total' => null, 'error' => null];
        }

        return ['ok' => false, 'total' => null, 'error' => 'Der Server unterstützt keine Teilabrufe (HTTP Range). Bitte das Archiv von Hand neben kickstart.php hochladen.'];
    }

    return ['ok' => false, 'total' => null, 'error' => 'HTTP '.$status.' beim Herunterladen.'];
}

/**
 * Appends Range pieces of $url to $partPath, starting at $offset, until the
 * file is complete or the step budget is used up. Always fetches at least
 * one piece and checks the budget afterwards. A server that ignores Range is
 * accepted only if the whole file fits into one piece.
 *
 * @return array ['offset' => int, 'total' => ?int, 'done' => bool, 'error' => ?string]
 */
function download_chunked($url, $partPath, $offset, $budgetStart, $chunk = DOWNLOAD_CHUNK_BYTES)
{
    $result = ['offset' => (int) $offset, 'total' => null, 'done' => false, 'error' => null];
    if (!preg_match('#^https?://#i', (string) $url)) {
        $result['error'] = 'Nur Adressen mit http:// oder https:// werden geholt.';

        return $result;
    }
    if (!function_exists('curl_init')) {
        $result['error'] = 'cURL fehlt auf diesem Host.';

        return $result;
    }
    if ($result['offset'] === 0 && is_file($partPath)) {
        @unlink($partPath);
    }

    do {
        $from = $result['offset'];
        $out = @fopen($partPath, 'ab');
        if (!$out) {
            $result['error'] = 'Die Datei '.basename($partPath).' lässt sich nicht schreiben.';

            return $result;
        }
        $status = 0;
        $range = null;
        $written = 0;
        $tooBig = false;
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => ['Range: bytes='.$from.'-'.($from + $chunk - 1)],
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_TIMEOUT => 600,
            CURLOPT_USERAGENT => 'FreeScout-kickstart/'.VERSION,
            CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
            CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$status, &$range) {
                if (preg_match('#^HTTP/\S+\s+(\d{3})#', $line, $m)) {
                    $status = (int) $m[1];
                    $range = null;
                } elseif (stripos($line, 'Content-Range:') === 0) {
                    $range = trim(substr($line, 14));
                }

                return strlen($line);
            },
            // Nothing is appended until the status line says it belongs here:
            // an error page or a full 200 body in the middle of the file would
            // otherwise land in the archive.
            CURLOPT_WRITEFUNCTION => function ($ch, $data) use (&$status, &$range, &$written, &$tooBig, $out, $from, $chunk) {
                $check = download_response_ok($status, $range, $from);
                if (!$check['ok']) {
                    return strlen($data); // discarded; the body is an error page
                }
                if ($status === 200 && $written + strlen($data) > $chunk) {
                    $tooBig = true;

                    return 0;
                }
                $written += strlen($data);

                return fwrite($out, $data);
            },
        ]);
        $ok = curl_exec($ch);
        fclose($out);
        $error = curl_error($ch);
        $check = download_response_ok($status, $range, $from);

        if ($tooBig) {
            $result['error'] = 'Der Server unterstützt keine Teilabrufe (HTTP Range), und das Archiv ist grösser als ein Stück. Bitte von Hand neben kickstart.php hochladen.';
            @unlink($partPath);

            return $result;
        }
        if ($ok === false) {
            $result['error'] = 'Herunterladen fehlgeschlagen: '.$error;

            return $result;
        }
        if (!$check['ok']) {
            $result['error'] = $check['error'];

            return $result;
        }
        if ($written === 0) {
            $result['error'] = 'Der Server lieferte keine Daten.';

            return $result;
        }

        $result['offset'] = $from + $written;
        $result['total'] = $check['total'] !== null ? $check['total'] : ($status === 200 ? $written : null);
        if ($result['total'] !== null && $result['offset'] > $result['total']) {
            $result['error'] = 'Die heruntergeladene Datei ist grösser als das Archiv. Bitte die .part-Datei löschen und neu beginnen.';

            return $result;
        }
        if ($status === 200 || ($result['total'] !== null && $result['offset'] >= $result['total'])) {
            $result['done'] = true;
        }
    } while (!$result['done'] && !budget_expired($budgetStart));

    return $result;
}

// --- Core download --------------------------------------------------------

function core_zip_path()
{
    return work_dir().'/freescout-core.zip';
}

/** Streams the core zip to disk in one pass.
 *
 * Not chunked across requests, and not resumable, because codeload does not
 * honour Range: a request with a Range header comes back HTTP 200 with the
 * entire body, so an offset-based resume would silently append the whole file
 * again on every call. Verified against
 * codeload.github.com/freescout-help-desk/freescout — 200, no Content-Range,
 * chunked transfer, and a range far past the end still returns everything.
 *
 * That is fine here: the tag archive is around 11 MB, so a single pass is a
 * couple of seconds. It lands in a .part file and is renamed only on success,
 * so an interrupted download is never mistaken for a complete one — the next
 * attempt simply starts over. */
function core_download_stream($url, $target)
{
    $part = $target.'.part';
    @unlink($part);

    $out = @fopen($part, 'wb');
    if (!$out) {
        return ['error' => 'Zieldatei für den Core-Download ist nicht beschreibbar.'];
    }

    $written = 0;

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_TIMEOUT => 900,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_USERAGENT => 'FreeScout-kickstart/'.VERSION,
            CURLOPT_FAILONERROR => true,
            CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use ($out, &$written) {
                $n = fwrite($out, $chunk);
                $written += (int) $n;

                return $n === false ? 0 : $n;
            },
        ]);
        $ok = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        fclose($out);

        if ($ok === false || $status >= 400) {
            @unlink($part);

            return ['error' => $error ?: ('HTTP '.$status.' beim Download.')];
        }
    } elseif (ini_get('allow_url_fopen')) {
        $context = stream_context_create(['http' => [
            'header' => 'User-Agent: FreeScout-kickstart/'.VERSION,
            'timeout' => 900,
            'follow_location' => 1,
        ]]);
        $in = @fopen($url, 'rb', false, $context);
        if (!$in) {
            fclose($out);
            @unlink($part);

            return ['error' => 'Verbindung zu GitHub fehlgeschlagen.'];
        }
        while (!feof($in)) {
            $chunk = fread($in, CHUNK_BYTES);
            if ($chunk === false || $chunk === '') {
                break;
            }
            $written += (int) fwrite($out, $chunk);
        }
        fclose($in);
        fclose($out);
    } else {
        fclose($out);
        @unlink($part);

        return ['error' => 'Weder cURL noch allow_url_fopen verfügbar — bitte den Core als ZIP hochladen und «Core ist schon vorhanden» wählen.'];
    }

    // A tag archive is never this small; anything under a megabyte is an
    // error page that arrived with a 200.
    if ($written < 1048576) {
        @unlink($part);

        return ['error' => 'Der Download ist nur '.human_bytes($written).' gross — das ist kein FreeScout-Archiv. Stimmt die Versionsnummer?'];
    }

    @unlink($target);
    if (!@rename($part, $target)) {
        return ['error' => 'Heruntergeladene Datei konnte nicht umbenannt werden.'];
    }

    return ['bytes' => $written];
}

function step_core_download($budgetStart)
{
    if (!state_get('core_wanted')) {
        return step_result(true, 100, 'Kein Core-Download angefordert.');
    }

    $version = trim((string) state_get('core_version'));
    if ($version === '') {
        return step_result(false, null, 'FEHLER: Keine FreeScout-Version bekannt. Bitte im Schritt «FreeScout-Core» eine Version eintragen.');
    }

    $target = core_zip_path();
    ensure_dir(dirname($target));

    // Already there from an earlier attempt — do not fetch it twice.
    if (is_file($target) && filesize($target) > 1048576) {
        return step_result(true, 100, 'Core-ZIP liegt bereits vor', human_bytes(filesize($target)));
    }

    $url = CORE_ZIP_URL.rawurlencode($version);
    $result = core_download_stream($url, $target);

    if (isset($result['error'])) {
        return step_result(false, null, 'FEHLER beim Core-Download: '.$result['error']);
    }

    state_set('core_zip_bytes', $result['bytes']);

    return step_result(true, 100, 'FreeScout-Core geladen', human_bytes($result['bytes']));
}

/** One-shot extraction through the system unzip, for hosts without the zip
 * extension. -qq quiet, -o overwrite, then the wrapper directory is moved up
 * a level — unzip has no --strip-components. */
function core_extract_with_unzip($zipPath)
{
    $staging = work_dir().'/core';
    rmtree($staging);
    ensure_dir($staging);

    $cmd = implode(' ', array_map('escapeshellarg', ['unzip', '-qq', '-o', $zipPath, '-d', $staging])).' 2>&1';
    $out = [];
    $code = 1;
    @exec($cmd, $out, $code);
    if ($code !== 0) {
        return step_result(false, null, 'FEHLER: unzip ist fehlgeschlagen.', implode(' ', $out));
    }

    $inner = glob($staging.'/*', GLOB_ONLYDIR);
    $source = (count($inner) === 1) ? $inner[0] : $staging;

    foreach (array_diff(scandir($source), ['.', '..']) as $entry) {
        $from = $source.'/'.$entry;
        $to = KS_ROOT.'/'.$entry;
        if (is_dir($to)) {
            // Merge rather than replace: Modules/ from the archive must
            // survive, and it is written after this step anyway.
            $cmd = implode(' ', array_map('escapeshellarg', ['cp', '-a', $from.'/.', $to.'/'])).' 2>&1';
            @exec($cmd, $out, $code);
        } else {
            @rename($from, $to);
        }
    }

    rmtree($staging);
    @unlink($zipPath);
    htaccess_guard();

    return step_result(true, 100, 'FreeScout-Core entpackt (Systembefehl unzip)');
}

/** The first line of the exception htaccess_guard() writes, and what
 * htaccess_release() looks for. */
const HTACCESS_MARK = '# kickstart: eigene Aufrufe nicht nach public/ umleiten (entfernt sich beim Aufräumen)';

/** The core's .htaccess rewrites every request into public/ -- the requests
 * to this script as well. From the moment it is unpacked, kickstart.php is
 * unreachable on Apache and LiteSpeed, and the restore stalls half-way
 * (found 21.11.2026 on the first real restore; php -S ignores .htaccess, so
 * no test run saw it). An exception for this one file goes in right after
 * «RewriteEngine on». Called after every extraction chunk: the next request
 * is the first one the rewrite would catch. */
function htaccess_guard()
{
    $path = KS_ROOT.'/.htaccess';
    $text = @file_get_contents($path);
    if ($text === false || strpos($text, HTACCESS_MARK) !== false) {
        return;
    }
    if (!preg_match('/^([ \t]*)RewriteEngine[ \t]+on\b[^\r\n]*/mi', $text, $m, PREG_OFFSET_CAPTURE)) {
        return;
    }
    $indent = $m[1][0];
    $end = $m[0][1] + strlen($m[0][0]);
    $insert = "\n".$indent.HTACCESS_MARK."\n".$indent.'RewriteRule ^'.preg_quote(KS_SELF, '/').'$ - [L]';
    @file_put_contents($path, substr($text, 0, $end).$insert.substr($text, $end));
}

/** Takes the exception out again, leaving the core's .htaccess as shipped. */
function htaccess_release()
{
    $path = KS_ROOT.'/.htaccess';
    $text = @file_get_contents($path);
    if ($text === false || strpos($text, HTACCESS_MARK) === false) {
        return;
    }
    $text = preg_replace('/\n[ \t]*'.preg_quote(HTACCESS_MARK, '/').'\n[ \t]*RewriteRule [^\r\n]*/', '', $text, 1);
    @file_put_contents($path, $text);
}

/** Unpacks the core zip. The GitHub tag archive wraps everything in one
 * top-level directory (freescout-help-desk-freescout-<sha>/), which is
 * stripped so the instance lands directly in the web root.
 *
 * Existing files are not overwritten if they came from the .fsback — the core
 * is placed first for exactly that reason, so the archive's Modules/ and
 * storage/app win afterwards. */
function step_core_extract($budgetStart)
{
    $zipPath = core_zip_path();
    if (!is_file($zipPath)) {
        return step_result(true, 100, 'Kein Core-ZIP vorhanden — übersprungen.');
    }
    if (!class_exists('ZipArchive')) {
        // No zip extension: the system unzip is the only way out, and it does
        // the whole thing in one call so there is nothing to resume.
        if (have_binary('unzip')) {
            return core_extract_with_unzip($zipPath);
        }

        return step_result(false, null,
            'FEHLER: Weder die PHP-Erweiterung zip noch der Befehl unzip ist verfügbar. '
            .'Bitte den Core von Hand entpacken und «Core ist schon vorhanden» wählen.');
    }

    $zip = new ZipArchive();
    if ($zip->open($zipPath) !== true) {
        return step_result(false, null, 'FEHLER: Core-ZIP konnte nicht geöffnet werden.');
    }

    $total = $zip->numFiles;
    $index = (int) state_get('core_extract_index', 0);
    $prefix = state_get('core_prefix');

    if ($prefix === null) {
        // Derive the wrapper directory from the first entry rather than
        // guessing the sha.
        $first = $zip->getNameIndex(0);
        $prefix = (strpos($first, '/') !== false) ? substr($first, 0, strpos($first, '/') + 1) : '';
        state_set('core_prefix', $prefix);
    }

    while ($index < $total && !budget_expired($budgetStart)) {
        $name = $zip->getNameIndex($index);
        $index++;

        if ($name === false) {
            continue;
        }
        if ($prefix !== '' && strpos($name, $prefix) === 0) {
            $name = substr($name, strlen($prefix));
        }
        $relative = safe_relative_path($name);
        if ($relative === null) {
            continue;
        }

        $target = KS_ROOT.'/'.$relative;

        if (substr($name, -1) === '/') {
            ensure_dir($target);
            continue;
        }

        ensure_dir(dirname($target));
        // getStream() wants the entry's own name, not the prefix-stripped
        // destination path computed above.
        $stream = $zip->getStream($zip->getNameIndex($index - 1));
        if (!$stream) {
            continue;
        }
        $out = @fopen($target, 'wb');
        if ($out) {
            while (!feof($stream)) {
                $buf = fread($stream, CHUNK_BYTES);
                if ($buf === false) {
                    break;
                }
                fwrite($out, $buf);
            }
            fclose($out);
        }
        fclose($stream);
    }

    $zip->close();
    state_set('core_extract_index', $index);
    htaccess_guard();

    $progress = $total > 0 ? (int) round($index / $total * 100) : 100;
    if ($index >= $total) {
        @unlink($zipPath);

        return step_result(true, 100, 'FreeScout-Core entpackt', $total.' Einträge');
    }

    return step_result(false, $progress, 'Core wird entpackt …', $index.' von '.$total.' Einträgen');
}

// --- Decryption -----------------------------------------------------------

/** Decrypts the archive into the work directory, resuming at a byte offset.
 *
 * Also the point where the manifest becomes readable, which is why the
 * archive's own metadata is only picked up after this phase: for an encrypted
 * archive there is no way to reach manifest.json without decrypting up to it,
 * and it sits thousands of entries in because tar writes in directory order. */
function step_decrypt($budgetStart)
{
    $archivePath = archive_path();
    if ($archivePath === null) {
        return step_result(false, null, 'FEHLER: Das gewählte Archiv ist nicht mehr auffindbar.');
    }
    if (!enc_is_encrypted($archivePath)) {
        return step_result(true, 100, 'Archiv ist unverschlüsselt — nichts zu entschlüsseln.');
    }
    if (!enc_available()) {
        return step_result(false, null, 'FEHLER: Die PHP-Erweiterung openssl mit aes-256-gcm fehlt, das Archiv kann nicht entschlüsselt werden.');
    }

    $password = (string) state_get('archive_password', '');
    if ($password === '') {
        return step_result(false, null, 'FEHLER: Für dieses Archiv ist kein Passwort hinterlegt.');
    }

    ensure_dir(work_dir());
    $target = decrypted_archive_path();

    $in = @fopen($archivePath, 'rb');
    if (!$in) {
        return step_result(false, null, 'FEHLER: Archiv ist nicht lesbar.');
    }

    try {
        $meta = enc_parse_header(fread($in, ENC_HEADER_LENGTH));
        $key = enc_derive_key($password, $meta['salt'], $meta['iterations']);

        $offset = (int) state_get('decrypt_offset', ENC_HEADER_LENGTH);
        $index = (int) state_get('decrypt_index', 0);
        $written = (int) state_get('decrypt_written', 0);

        // Append on resume, truncate on a fresh start — otherwise a restarted
        // run would double the file.
        $out = @fopen($target, $offset > ENC_HEADER_LENGTH ? 'ab' : 'wb');
        if (!$out) {
            return step_result(false, null, 'FEHLER: '.basename($target).' ist nicht beschreibbar.');
        }

        try {
            fseek($in, $offset);

            while (true) {
                $lengthBytes = fread($in, 4);
                if ($lengthBytes === '' || $lengthBytes === false || strlen($lengthBytes) < 4) {
                    // End of the block sequence.
                    if ($written !== $meta['plain_size']) {
                        return step_result(false, null, 'FEHLER: Entschlüsselt wurden '.human_bytes($written)
                            .', der Archivkopf nennt '.human_bytes($meta['plain_size']).' — das Archiv ist unvollständig.');
                    }
                    state_set('decrypt_done', true);

                    return step_result(true, 100, 'Archiv entschlüsselt', human_bytes($written).', '.$index.' Blöcke');
                }

                $length = unpack('N', $lengthBytes)[1];
                if ($length < 1 || $length > $meta['block_size'] + 1024) {
                    return step_result(false, null, 'FEHLER: Block '.$index.' nennt eine unplausible Länge.');
                }

                $iv = fread($in, ENC_IV_LENGTH);
                $tag = fread($in, ENC_TAG_LENGTH);
                $ciphertext = enc_read_exactly($in, $length);
                if (strlen((string) $iv) !== ENC_IV_LENGTH || strlen((string) $tag) !== ENC_TAG_LENGTH || $ciphertext === null) {
                    return step_result(false, null, 'FEHLER: Das Archiv endet mitten in Block '.$index.' — es ist abgeschnitten.');
                }

                $plain = openssl_decrypt($ciphertext, ENC_CIPHER, $key, OPENSSL_RAW_DATA, $iv, $tag,
                    $meta['raw'].pack('J', $index));
                if ($plain === false) {
                    return step_result(false, null, $index === 0
                        ? 'FEHLER: Falsches Passwort, oder das Archiv ist beschädigt.'
                        : 'FEHLER: Block '.$index.' ist nicht authentisch — das Archiv ist beschädigt oder manipuliert.');
                }

                fwrite($out, $plain);
                $written += strlen($plain);
                $index++;
                $offset = ftell($in);

                if (budget_expired($budgetStart)) {
                    state_set('decrypt_offset', $offset);
                    state_set('decrypt_index', $index);
                    state_set('decrypt_written', $written);

                    $progress = $meta['plain_size'] > 0
                        ? (int) round($written / $meta['plain_size'] * 100)
                        : null;

                    return step_result(false, $progress, 'Archiv wird entschlüsselt …',
                        human_bytes($written).' von '.human_bytes($meta['plain_size']));
                }
            }
        } finally {
            fclose($out);
        }
    } catch (Throwable $e) {
        return step_result(false, null, 'FEHLER beim Entschlüsseln: '.$e->getMessage());
    } finally {
        fclose($in);
    }
}

/** Reads the manifest out of the (now plain) archive and records what the rest
 * of the run needs from it: the FreeScout version to fetch, and the APP_KEY if
 * the archive carries one. Only an encrypted archive does — an unencrypted one
 * must not, so there is nothing to pick up there. */
function step_read_manifest($budgetStart)
{
    $path = working_archive_path();
    if ($path === null) {
        return step_result(false, null, 'FEHLER: Kein Archiv zum Lesen gefunden.');
    }

    $result = archive_manifest($path);
    if (isset($result['error'])) {
        return step_result(false, null, 'FEHLER: '.$result['error']);
    }

    $manifest = $result['manifest'];
    state_set('manifest', $manifest);

    $details = [];
    if (!empty($manifest['app_key'])) {
        // Only overrides a key the operator did not supply themselves.
        if ((string) state_get('app_key', '') === '') {
            state_set('app_key', $manifest['app_key']);
            state_set('app_key_from_archive', true);
            $details[] = 'APP_KEY aus dem Archiv übernommen';
        }
    }
    if (!empty($manifest['app_version']) && (string) state_get('core_version', '') === '' && state_get('core_wanted')) {
        state_set('core_version', $manifest['app_version']);
        $details[] = 'Core-Version '.$manifest['app_version'].' aus dem Archiv';
    }

    return step_result(true, 100, 'Manifest gelesen',
        $details ? implode(', ', $details) : 'FreeScout '.($manifest['app_version'] ?? '?'));
}

/** The archive everything after decryption works on: the decrypted copy if
 * there is one, otherwise the selected file itself. */
function working_archive_path()
{
    $decrypted = decrypted_archive_path();
    if (is_file($decrypted) && state_get('decrypt_done')) {
        return $decrypted;
    }

    return archive_path();
}

// --- Archive extraction ---------------------------------------------------

function step_archive_extract($budgetStart)
{
    $archivePath = working_archive_path();
    if ($archivePath === null) {
        return step_result(false, null, 'FEHLER: Das gewählte Archiv ist nicht mehr auffindbar.');
    }

    ensure_dir(work_dir());

    // Fast path: one tar call, no chunking, no resume problem.
    if (state_get('use_system_tar') && have_binary('tar')) {
        return archive_extract_with_tar($archivePath);
    }

    return archive_extract_with_php($archivePath, $budgetStart);
}

function archive_extract_with_tar($archivePath)
{
    $work = work_dir();

    // Two calls rather than one: manifest.json and database.sql go to the
    // work directory, the two payload trees straight to their final homes,
    // so nothing is written twice.
    $commands = [
        ['tar', 'xzf', $archivePath, '-C', $work, './manifest.json', './database.sql'],
    ];
    foreach ($commands as $argv) {
        $cmd = implode(' ', array_map('escapeshellarg', $argv)).' 2>&1';
        $out = [];
        $code = 1;
        @exec($cmd, $out, $code);
        if ($code !== 0) {
            return step_result(false, null, 'FEHLER: tar konnte database.sql/manifest.json nicht entpacken.', implode(' ', $out));
        }
    }

    foreach ([['storage_app', KS_ROOT.'/storage/app'], ['modules', KS_ROOT.'/Modules']] as $pair) {
        list($member, $dest) = $pair;
        ensure_dir($dest);
        $cmd = implode(' ', array_map('escapeshellarg', [
            // 2, not 1: entries look like './storage_app/foo', so the
            // leading '.' and the member name both have to go. Verified
            // against a real archive from this module on busybox tar 1.37.
            'tar', 'xzf', $archivePath, '-C', $dest, '--strip-components=2', './'.$member,
        ])).' 2>&1';
        $out = [];
        $code = 1;
        @exec($cmd, $out, $code);
        // A missing member is not an error — an archive may legitimately have
        // no modules at all.
        if ($code !== 0 && !preg_match('/Not found in archive|not found/i', implode(' ', $out))) {
            return step_result(false, null, 'FEHLER: tar konnte '.$member.' nicht entpacken.', implode(' ', $out));
        }
    }

    state_set('archive_entries_done', -1);

    return step_result(true, 100, 'Archiv entpackt (Systembefehl tar)');
}

/** Pure-PHP extraction, resumable by entry index.
 *
 * A gzip stream cannot be checkpointed, so a resumed run re-reads from the
 * start and skips the first N entries it already wrote. The skip is cheap
 * (decompress, discard) next to writing, so every run still moves forward. */
/** How often progress is flushed to the state file during PHP extraction.
 * Writing after every entry meant a JSON encode, write and rename per file —
 * thousands of them for one archive, and by far the most expensive thing in
 * the loop. Losing up to this many entries of progress on a hard kill costs a
 * re-skip of at most this many, which is nothing. */
const ARCHIVE_STATE_EVERY = 250;

function archive_extract_with_php($archivePath, $budgetStart)
{
    $handle = tar_open($archivePath);
    if (!$handle) {
        return step_result(false, null, 'FEHLER: Archiv konnte nicht geöffnet werden.');
    }

    $alreadyDone = (int) state_get('archive_entries_done', 0);
    $index = 0;
    $written = 0;
    $skipped = 0;
    $longName = null;

    try {
        while (($header = tar_read_header($handle)) !== null) {
            $name = $header['name'];
            $size = $header['size'];
            $type = $header['type'];

            // GNU long name: the real path is this entry's body, applying to
            // the header that follows.
            if ($type === 'L') {
                $raw = '';
                $remaining = $size;
                while ($remaining > 0) {
                    $read = fread($handle, (int) min(CHUNK_BYTES, $remaining));
                    if ($read === false || $read === '') {
                        break;
                    }
                    $raw .= $read;
                    $remaining -= strlen($read);
                }
                $pad = (512 - ($size % 512)) % 512;
                if ($pad > 0) {
                    fread($handle, $pad);
                }
                $longName = rtrim($raw, "\0");
                continue;
            }
            if ($longName !== null) {
                $name = $longName;
                $longName = null;
            }
            // pax headers and anything exotic: skip the body, keep going.
            if ($type === 'x' || $type === 'g') {
                tar_skip_body($handle, $size);
                continue;
            }

            $index++;

            if ($index <= $alreadyDone) {
                tar_skip_body($handle, $size);
                $skipped++;
                continue;
            }

            // Directories and regular files only. Symlinks ('1','2') are
            // deliberately not recreated — the archive should not contain
            // any, and a link is the standard way to escape the target tree.
            if ($type === '5') {
                $mapped = map_archive_entry(rtrim($name, '/').'/x');
                if ($mapped) {
                    ensure_dir(dirname($mapped['path']));
                }
                continue;
            }
            if ($type !== '0' && $type !== "\0" && $type !== '') {
                tar_skip_body($handle, $size);
                continue;
            }

            $mapped = map_archive_entry($name);
            if ($mapped === null) {
                tar_skip_body($handle, $size);
                continue;
            }

            ensure_dir(dirname($mapped['path']));
            $out = @fopen($mapped['path'], 'wb');
            if (!$out) {
                fclose($handle);

                return step_result(false, null, 'FEHLER: '.$mapped['path'].' ist nicht beschreibbar.');
            }

            $remaining = $size;
            while ($remaining > 0) {
                $read = fread($handle, (int) min(CHUNK_BYTES, $remaining));
                if ($read === false || $read === '') {
                    break;
                }
                fwrite($out, $read);
                $remaining -= strlen($read);
            }
            fclose($out);

            $pad = (512 - ($size % 512)) % 512;
            if ($pad > 0) {
                fread($handle, $pad);
            }

            $written++;

            if ($written % ARCHIVE_STATE_EVERY === 0) {
                state_set('archive_entries_done', $index);
            }

            if (budget_expired($budgetStart)) {
                fclose($handle);
                // Always flush before yielding, whatever the counter says —
                // this is the checkpoint the next request resumes from.
                state_set('archive_entries_done', $index);

                return step_result(false, null, 'Archiv wird entpackt …',
                    $index.' Einträge erledigt'.($skipped ? ' ('.$skipped.' übersprungen)' : ''));
            }
        }
    } finally {
        if (is_resource($handle)) {
            fclose($handle);
        }
    }

    state_set('archive_entries_done', -1);

    return step_result(true, 100, 'Archiv entpackt', $index.' Einträge');
}

// --- Database -------------------------------------------------------------

function db_connect(array $creds, $withDatabase = true)
{
    $dsn = 'mysql:host='.$creds['host'].';port='.(int) $creds['port'];
    if ($withDatabase) {
        $dsn .= ';dbname='.$creds['database'];
    }
    $dsn .= ';charset=utf8mb4';

    return new PDO($dsn, $creds['username'], $creds['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => true,
    ]);
}

function db_credentials()
{
    $creds = state_get('db');

    return is_array($creds) ? $creds : null;
}

function step_db_import($budgetStart)
{
    $sqlPath = work_dir().'/database.sql';
    if (!is_file($sqlPath)) {
        return step_result(false, null, 'FEHLER: database.sql wurde im Archiv nicht gefunden.');
    }

    $creds = db_credentials();
    if (!$creds) {
        return step_result(false, null, 'FEHLER: Keine Datenbank-Zugangsdaten hinterlegt.');
    }

    try {
        $pdo = db_connect($creds);
    } catch (Throwable $e) {
        return step_result(false, null, 'FEHLER: Verbindung zur Datenbank fehlgeschlagen.', $e->getMessage());
    }

    $offset = (int) state_get('db_offset', 0);
    $delimiter = (string) state_get('db_delimiter', ';');
    $total = filesize($sqlPath);

    // One-time preparation on the first pass.
    if ($offset === 0) {
        try {
            $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
            $pdo->exec('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
            if (state_get('db_drop_tables')) {
                db_drop_all_tables($pdo, $creds['database']);
            }
        } catch (Throwable $e) {
            return step_result(false, null, 'FEHLER bei der Vorbereitung der Datenbank.', $e->getMessage());
        }
    } else {
        // These are session settings, so they have to be set again on every
        // request — the connection from the previous chunk is long gone.
        try {
            $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
            $pdo->exec('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
        } catch (Throwable $e) {
            // Not fatal; the import will simply be stricter.
        }
    }

    // The dump's own session statements (SET NAMES, TIME_ZONE='+00:00',
    // @OLD_* and @saved_cs_client) only lived in the connection that ran
    // them. Replayed here, every request sees the session a single mysql
    // client would have had: without TIME_ZONE every timestamp after the
    // first chunk shifts on a server outside UTC, and SET x=@OLD_x fails
    // with NULL. Errors are ignored: a restore like SET x=@saved can run
    // before the statement that sets @saved, and the next one puts it right.
    $session = (array) state_get('db_session', []);
    foreach ($session as $set) {
        try {
            $pdo->exec($set);
        } catch (Throwable $e) {
        }
    }

    $handle = fopen($sqlPath, 'rb');
    if (!$handle) {
        return step_result(false, null, 'FEHLER: database.sql ist nicht lesbar.');
    }

    $executed = (int) state_get('db_statements', 0);
    try {
        list($statements, $newOffset, $newDelimiter, $eof, $marks) =
            sql_next_statements($handle, $offset, $delimiter, $budgetStart);

        foreach ($statements as $i => $statement) {
            $statement = sql_strip_definer($statement);
            if (trim($statement) !== '') {
                try {
                    $pdo->exec($statement);
                    $executed++;
                } catch (Throwable $e) {
                    // Resume AT the failed statement next time: the ones
                    // before it are in the database already, and running
                    // them again ends in «already exists» or duplicate rows.
                    fclose($handle);
                    state_set('db_offset', $offset);
                    state_set('db_delimiter', $delimiter);
                    state_set('db_statements', $executed);
                    state_set('db_session', array_values($session));

                    // Report the statement that failed rather than a bare
                    // message — a restore stops here and the operator needs
                    // to see which one it was.
                    return step_result(false, null, 'FEHLER beim Import (Anweisung '.($executed + 1).')',
                        $e->getMessage().' — '.mb_substr(preg_replace('/\s+/', ' ', $statement), 0, 200));
                }
                if (sql_is_session_statement($statement)) {
                    // Latest position wins, so the replay keeps the order.
                    $session = array_values(array_diff($session, [$statement]));
                    $session[] = $statement;
                }
            }
            list($offset, $delimiter) = $marks[$i];
        }
    } finally {
        if (is_resource($handle)) {
            fclose($handle);
        }
    }

    state_set('db_offset', $newOffset);
    state_set('db_delimiter', $newDelimiter);
    state_set('db_statements', $executed);
    state_set('db_session', array_values($session));

    $progress = $total > 0 ? (int) round(min($newOffset, $total) / $total * 100) : 100;

    if ($eof) {
        try {
            $pdo->exec('SET FOREIGN_KEY_CHECKS=1');
        } catch (Throwable $e) {
            // Session ends with the request anyway.
        }

        return step_result(true, 100, 'Datenbank importiert', $executed.' Anweisungen');
    }

    return step_result(false, $progress, 'Datenbank wird importiert …',
        human_bytes($newOffset).' von '.human_bytes($total).', '.$executed.' Anweisungen');
}

/** True for a statement that only sets session or user variables, as
 * mysqldump writes them: SET NAMES …, SET TIME_ZONE=…, SET @x=@@y, usually
 * inside a version-gated comment (!40101, MariaDB: M!100616). */
function sql_is_session_statement($statement)
{
    return (bool) preg_match('~^(?:/\*M?!\d*\s*)?SET\s~i', ltrim($statement));
}

function db_drop_all_tables(PDO $pdo, $database)
{
    $tables = $pdo->query('SHOW FULL TABLES')->fetchAll(PDO::FETCH_NUM);
    if (!$tables) {
        return;
    }
    $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
    foreach ($tables as $row) {
        $name = $row[0];
        $isView = isset($row[1]) && stripos($row[1], 'VIEW') !== false;
        $pdo->exec(($isView ? 'DROP VIEW IF EXISTS ' : 'DROP TABLE IF EXISTS ').'`'.str_replace('`', '``', $name).'`');
    }
    $pdo->exec('SET FOREIGN_KEY_CHECKS=1');
}

// --- Finalise -------------------------------------------------------------

/** Writes .env, clears the caches a restored instance must not inherit, and
 * creates the directories Laravel expects to exist. */
/** The time zone FreeScout must run in on this database server, as a PHP
 * zone name, or null when it cannot be told safely.
 *
 * FreeScout writes its timestamps as text in APP_TIMEZONE into TIMESTAMP
 * columns, and MySQL reads that text in the session's zone -- the server's,
 * since FreeScout sets none. The dump keeps the moments; after a move to a
 * server in another zone the application has to follow the new server, not
 * the old .env, or every time is off by the difference. */
function db_app_timezone($global, $system)
{
    $zone = ($global === null || $global === '' || strtoupper((string) $global) === 'SYSTEM') ? (string) $system : (string) $global;
    $upper = strtoupper($zone);
    if (preg_match('/^[+-]00:00$/', $zone) || in_array($upper, ['UTC', 'GMT', 'Z', 'ETC/UTC', 'ETC/GMT'], true)) {
        return 'UTC';
    }
    // What a Linux server in Switzerland, Germany or Austria reports as its
    // system zone. The abbreviation changes with daylight saving time; the
    // rules behind it are the same everywhere in that zone.
    if (in_array($upper, ['CET', 'CEST', 'MET', 'MEST', 'MEZ', 'MESZ'], true)) {
        return 'Europe/Zurich';
    }
    if (strpos($zone, '/') !== false && in_array($zone, timezone_identifiers_list(), true)) {
        return $zone;
    }

    return null;
}

/** Recreates what FreeScout keeps in public/ as links and what no archive
 * carries: public/modules/<alias> for every module with a Public folder, and
 * public/storage. Without them the login page has no stylesheet (building
 * public/css/builds fails on the missing module files) and logos are 404.
 * Absolute targets, as FreeScout writes them itself. */
function link_public_assets()
{
    $public = KS_ROOT.'/public';
    $result = ['modules' => 0, 'storage' => false, 'failed' => []];
    if (!is_dir($public)) {
        $result['failed'][] = 'public/';

        return $result;
    }
    ensure_dir($public.'/modules');
    foreach (glob(KS_ROOT.'/Modules/*/module.json') ?: [] as $json) {
        $dir = dirname($json);
        $meta = json_decode((string) @file_get_contents($json), true);
        $alias = is_array($meta) && isset($meta['alias']) ? (string) $meta['alias'] : '';
        if (!preg_match('/^[A-Za-z0-9_-]+$/', $alias) || !is_dir($dir.'/Public')) {
            continue;
        }
        $link = $public.'/modules/'.$alias;
        if (is_link($link)) {
            @unlink($link);
        } elseif (file_exists($link)) {
            continue;
        }
        if (@symlink($dir.'/Public', $link)) {
            $result['modules']++;
        } else {
            $result['failed'][] = 'public/modules/'.$alias;
        }
    }

    ensure_dir(KS_ROOT.'/storage/app/public');
    $storage = $public.'/storage';
    $result['storage'] = is_link($storage) || (!file_exists($storage) && @symlink(KS_ROOT.'/storage/app/public', $storage));
    if (!$result['storage']) {
        $result['failed'][] = 'public/storage';
    }

    return $result;
}

function step_finalise($budgetStart)
{
    $creds = db_credentials();
    if (!$creds) {
        return step_result(false, null, 'FEHLER: Keine Datenbank-Zugangsdaten hinterlegt.');
    }

    $appTimezone = null;
    try {
        $zone = db_connect($creds)->query('SELECT @@global.time_zone, @@system_time_zone')->fetch(PDO::FETCH_NUM);
        $appTimezone = db_app_timezone($zone[0], $zone[1]);
    } catch (Throwable $e) {
        // Then the finished page asks for it by hand.
    }

    $appKey = (string) state_get('app_key', '');
    if ($appKey === '') {
        $appKey = 'base64:'.base64_encode(random_bytes(32));
        state_set('app_key', $appKey);
        state_set('app_key_generated', true);
    }

    $appUrl = rtrim((string) state_get('app_url', ''), '/');
    if ($appUrl === '') {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $appUrl = $scheme.'://'.($_SERVER['HTTP_HOST'] ?? 'localhost');
    }

    $env = [
        'APP_NAME' => 'FreeScout',
        'APP_ENV' => 'production',
        'APP_KEY' => $appKey,
        'APP_DEBUG' => 'false',
        'APP_URL' => $appUrl,
        'APP_LOG' => 'daily',
        'DB_CONNECTION' => 'mysql',
        'DB_HOST' => $creds['host'],
        'DB_PORT' => (string) (int) $creds['port'],
        'DB_DATABASE' => $creds['database'],
        'DB_USERNAME' => $creds['username'],
        'DB_PASSWORD' => $creds['password'],
    ];
    if ($appTimezone !== null) {
        $env['APP_TIMEZONE'] = $appTimezone;
    }

    $lines = [
        '# Written by kickstart.php '.VERSION.' on '.date('c'),
        '# Review APP_URL and the mail settings before going live.',
        '',
    ];
    foreach ($env as $key => $value) {
        // Quote anything that is not plainly safe unquoted.
        $needsQuotes = $value === '' || preg_match('/[\s"\'#=$]/', $value);
        $lines[] = $key.'='.($needsQuotes ? '"'.str_replace(['\\', '"'], ['\\\\', '\\"'], $value).'"' : $value);
    }

    if (@file_put_contents(KS_ROOT.'/.env', implode("\n", $lines)."\n") === false) {
        return step_result(false, null, 'FEHLER: .env konnte nicht geschrieben werden.');
    }
    @chmod(KS_ROOT.'/.env', 0640);

    // Compiled config/routes/views from the source host would point at its
    // paths and its database. They must not survive into the restore.
    foreach (glob(KS_ROOT.'/bootstrap/cache/*.php') ?: [] as $cached) {
        @unlink($cached);
    }
    foreach (glob(KS_ROOT.'/storage/framework/views/*.php') ?: [] as $cached) {
        @unlink($cached);
    }

    foreach ([
        'storage/app', 'storage/framework/cache', 'storage/framework/sessions',
        'storage/framework/views', 'storage/logs', 'bootstrap/cache',
    ] as $dir) {
        ensure_dir(KS_ROOT.'/'.$dir);
        @chmod(KS_ROOT.'/'.$dir, 0775);
    }

    // The scratch directory holds database.sql in the clear and, for an
    // encrypted archive, a decrypted copy of the whole thing — both inside the
    // web root. Neither is needed any more, and leaving them until somebody
    // presses the cleanup button is not good enough.
    $scratch = work_dir();
    rmtree($scratch);
    $scratchGone = !is_dir($scratch);

    $links = link_public_assets();

    state_set('finished_at', date('c'));
    state_set('scratch_removed', $scratchGone);
    state_set('app_timezone', (string) $appTimezone);
    state_set('links', $links);

    return step_result(true, 100, 'Instanz fertiggestellt',
        '.env geschrieben, Caches geleert, '.$links['modules'].' Modul-Verknüpfungen'
        .($links['failed'] ? ', ACHTUNG: '.count($links['failed']).' Verknüpfungen fehlen' : '')
        .($scratchGone ? ', Arbeitsdateien gelöscht' : ', ACHTUNG: Arbeitsverzeichnis liess sich nicht löschen'));
}

// ---------------------------------------------------------------------------
// Request handling
// ---------------------------------------------------------------------------

function json_out(array $payload, $status = 200)
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('X-Robots-Tag: noindex, nofollow');
    echo json_encode($payload);
    exit;
}

// Prüfstrecken laden diese Datei nur als Funktionssammlung.
if (defined('KICKSTART_LIBRARY')) {
    return;
}

$token = token_ensure();
$task = isset($_REQUEST['task']) ? (string) $_REQUEST['task'] : '';
$isAjax = in_array($task, ['run', 'checks', 'manifest', 'dbtest', 'archives', 's3list', 'fetch_prepare', 'fetch'], true);

// --- Login ---------------------------------------------------------------

if ($task === 'login') {
    if (token_valid()) {
        setcookie('ks_token', token_supplied(), 0, '', '', !empty($_SERVER['HTTPS']), true);
        header('Location: '.KS_SELF);
        exit;
    }
    $loginError = 'Token stimmt nicht.';
}

if (!token_valid() && $task !== '') {
    if ($isAjax) {
        json_out(['error' => 'Nicht angemeldet.'], 403);
    }
    header('Location: '.KS_SELF);
    exit;
}

// --- AJAX ----------------------------------------------------------------

// --- Fetching an archive (URL or S3) ---------------------------------------

/** S3 access from the form. Used for listing and signing, never stored. */
function ks_s3_cfg_from_post()
{
    return [
        'endpoint' => trim((string) ($_POST['endpoint'] ?? '')),
        'region' => trim((string) ($_POST['region'] ?? '')),
        'bucket' => trim((string) ($_POST['bucket'] ?? '')),
        'access_key' => trim((string) ($_POST['access_key'] ?? '')),
        'secret_key' => (string) ($_POST['secret_key'] ?? ''),
        'path_style' => !empty($_POST['path_style']),
    ];
}

if ($task === 'archives') {
    json_out(['archives' => archives_available()]);
}

if ($task === 's3list') {
    $prefix = trim((string) ($_POST['prefix'] ?? ''), " /");
    $list = ks_s3_list(ks_s3_cfg_from_post(), $prefix === '' ? '' : $prefix.'/');
    if (isset($list['error'])) {
        json_out(['error' => $list['error']]);
    }
    foreach ($list as $i => $entry) {
        $list[$i]['size_human'] = human_bytes($entry['size']);
    }
    json_out(['archives' => $list]);
}

if ($task === 'fetch_prepare') {
    if (($_POST['mode'] ?? '') === 's3') {
        $key = (string) ($_POST['key'] ?? '');
        $url = ks_s3_presign(ks_s3_cfg_from_post(), $key, 86400);
        $name = basename($key);
    } else {
        $url = trim((string) ($_POST['url'] ?? ''));
        $name = rawurldecode(basename((string) parse_url($url, PHP_URL_PATH)));
    }
    if (!preg_match('#^https?://#i', $url)) {
        json_out(['error' => 'Bitte eine Adresse mit http:// oder https:// angeben.']);
    }
    if (!preg_match(ARCHIVE_NAME_PATTERN, $name)) {
        json_out(['error' => 'Der Dateiname «'.$name.'» ist kein Archiv dieses Moduls (freescout-backup-….fsback oder .fsback.enc).']);
    }
    if (is_file(KS_ROOT.'/'.$name)) {
        json_out(['error' => 'Ein Archiv mit diesem Namen liegt schon hier.']);
    }
    // Ein neuer Klick nach einem Abbruch setzt an der .part-Datei an, wenn sie
    // zum selben Archiv gehört; der Link wird dabei frisch signiert.
    $part = KS_ROOT.'/'.$name.'.part';
    $resume = (is_file($part) && state_get('download_name') === $name) ? (int) filesize($part) : 0;
    state_set('download_url', $url);
    state_set('download_name', $name);
    state_set('download_offset', $resume);
    json_out(['ok' => true, 'name' => $name, 'resume_offset' => $resume]);
}

if ($task === 'fetch') {
    $url = (string) state_get('download_url', '');
    $name = (string) state_get('download_name', '');
    if ($url === '' || !preg_match(ARCHIVE_NAME_PATTERN, $name)) {
        json_out(['error' => 'Kein Download vorbereitet.']);
    }
    $part = KS_ROOT.'/'.$name.'.part';
    // Die Datei ist der Stand, nicht der Zustand: reisst ein Request nach dem
    // Schreiben, aber vor state_set() ab, wüsste der Zustand von Bytes nichts,
    // die schon dastehen, und das nächste Stück landete an der falschen Stelle.
    clearstatcache();
    $r = download_chunked($url, $part, is_file($part) ? (int) filesize($part) : 0, microtime(true));
    if ($r['error'] !== null) {
        json_out(['error' => $r['error']]);
    }
    state_set('download_offset', $r['offset']);
    if ($r['done']) {
        @rename($part, KS_ROOT.'/'.$name);
        state_set('download_url', null);
        state_set('download_name', null);
        state_set('download_offset', null);
    }
    json_out([
        'done' => $r['done'],
        'offset_human' => human_bytes($r['offset']),
        'total_human' => $r['total'] !== null ? human_bytes($r['total']) : null,
        'percent' => $r['total'] ? (int) floor($r['offset'] * 100 / $r['total']) : null,
    ]);
}

if ($task === 'checks') {
    json_out(['checks' => checks_run()]);
}

if ($task === 'manifest') {
    $name = isset($_POST['archive']) ? (string) $_POST['archive'] : '';
    $previous = state_get('archive');
    state_set('archive', $name);
    $path = archive_path();
    if ($path === null) {
        json_out(['error' => 'Archiv nicht gefunden.']);
    }

    // An encrypted archive cannot be inspected here: manifest.json sits
    // thousands of tar entries in, so reaching it means decrypting most of the
    // file. All this step can do is prove the password, which is instant
    // because block 0 is authenticated. The manifest is read in its own phase
    // once the archive is decrypted.
    if (enc_is_encrypted($path)) {
        if (!enc_available()) {
            json_out(['error' => 'Dieses Archiv ist verschlüsselt, aber die PHP-Erweiterung openssl mit aes-256-gcm fehlt auf diesem Host.']);
        }
        $password = isset($_POST['password']) ? (string) $_POST['password'] : '';
        if ($password === '') {
            // Already proven for this very archive before a reload: the
            // restore needs it from the state anyway, so asking again only
            // sends somebody back to the emergency sheet for nothing.
            $known = (string) state_get('archive_password', '');
            if ($previous === $name && $known !== '' && enc_password_matches($path, $known)) {
                json_out(['encrypted' => true, 'password_ok' => true, 'remembered' => true,
                    'size' => human_bytes(filesize($path))]);
            }
            json_out(['encrypted' => true, 'need_password' => true, 'size' => human_bytes(filesize($path))]);
        }
        if (!enc_password_matches($path, $password)) {
            // The heading already says the password is wrong, so this line
            // carries the one thing that actually helps: the most common
            // reason for a password that used to work.
            json_out(['encrypted' => true, 'need_password' => true, 'size' => human_bytes(filesize($path)),
                'error' => 'Prüfe das Notfallblatt. Archive, die vor einer Passwortänderung '
                    .'erstellt wurden, brauchen weiterhin das damalige Passwort.']);
        }
        state_set('archive_password', $password);
        json_out([
            'encrypted' => true,
            'password_ok' => true,
            'size' => human_bytes(filesize($path)),
        ]);
    }

    state_set('archive_password', '');
    $result = archive_manifest($path);
    if (isset($result['error'])) {
        json_out(['error' => $result['error']]);
    }
    json_out([
        'manifest' => $result['manifest'],
        'size' => human_bytes(filesize($path)),
        'suggested_version' => $result['manifest']['app_version'] ?? null,
    ]);
}

if ($task === 'dbtest') {
    $creds = [
        'host' => trim((string) ($_POST['host'] ?? '')),
        'port' => (int) ($_POST['port'] ?? 3306) ?: 3306,
        'database' => trim((string) ($_POST['database'] ?? '')),
        'username' => trim((string) ($_POST['username'] ?? '')),
        'password' => (string) ($_POST['password'] ?? ''),
    ];
    // After a reload the page cannot show the password again (it never puts
    // it into the HTML). An empty field for the same server, database and
    // user therefore means «the one tested before».
    $saved = db_credentials();
    if ($creds['password'] === '' && $saved && $saved['host'] === $creds['host'] && (int) $saved['port'] === $creds['port']
        && $saved['database'] === $creds['database'] && $saved['username'] === $creds['username']) {
        $creds['password'] = (string) $saved['password'];
    }
    try {
        $pdo = db_connect($creds, false);
        $exists = $pdo->query('SHOW DATABASES LIKE '.$pdo->quote($creds['database']))->fetch();
        if (!$exists) {
            if (!empty($_POST['create'])) {
                $pdo->exec('CREATE DATABASE `'.str_replace('`', '``', $creds['database']).'` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
            } else {
                json_out(['error' => 'Die Datenbank «'.$creds['database'].'» existiert nicht. Anlegen ankreuzen oder von Hand erstellen.']);
            }
        }
        $pdo = db_connect($creds);
        $tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_NUM);
        state_set('db', $creds);
        json_out([
            'ok' => true,
            'server' => $pdo->getAttribute(PDO::ATTR_SERVER_VERSION),
            'tables' => count($tables),
        ]);
    } catch (Throwable $e) {
        json_out(['error' => $e->getMessage()]);
    }
}

if ($task === 'run') {
    $phase = (string) ($_POST['phase'] ?? '');
    $budgetStart = microtime(true);

    // Options arriving with the first call of the run.
    if (!empty($_POST['options'])) {
        $options = json_decode((string) $_POST['options'], true);
        if (is_array($options)) {
            foreach (['core_version', 'core_wanted', 'app_key', 'app_url', 'db_drop_tables', 'use_system_tar'] as $key) {
                if (array_key_exists($key, $options)) {
                    state_set($key, $options[$key]);
                }
            }
        }
    }

    try {
        switch ($phase) {
            case 'decrypt':
                $result = step_decrypt($budgetStart);
                break;
            case 'read_manifest':
                $result = step_read_manifest($budgetStart);
                break;
            case 'core_download':
                $result = step_core_download($budgetStart);
                break;
            case 'core_extract':
                $result = step_core_extract($budgetStart);
                break;
            case 'archive':
                $result = step_archive_extract($budgetStart);
                break;
            case 'database':
                $result = step_db_import($budgetStart);
                break;
            case 'finalise':
                $result = step_finalise($budgetStart);
                break;
            default:
                json_out(['error' => 'Unbekannter Schritt: '.$phase], 400);
        }
    } catch (Throwable $e) {
        json_out(['error' => get_class($e).': '.$e->getMessage()]);
    }

    json_out($result);
}

if ($task === 'cleanup') {
    // Glob rather than work_dir(): an abandoned earlier attempt may have left
    // a directory under a different suffix, and those are exactly the ones
    // worth sweeping up.
    foreach (glob(KS_ROOT.'/'.WORK_DIR_PREFIX.'-*') ?: [] as $leftover) {
        rmtree($leftover);
    }
    rmtree(work_dir());
    foreach (glob(KS_ROOT.'/*.part') ?: [] as $leftover) {
        @unlink($leftover);
    }
    // The archive holds the whole instance and sits in the web root. With
    // FreeScout's .htaccess it is out of reach, on nginx with this folder as
    // the web root it is one URL away. Offered ticked on the finished page.
    if (!empty($_POST['delete_archives'])) {
        foreach (archives_available() as $archive) {
            @unlink(KS_ROOT.'/'.$archive['name']);
        }
    }
    htaccess_release();
    @unlink(state_path());
    @unlink(state_path().'.tmp.php');
    @unlink(KS_ROOT.'/'.TOKEN_FILE);
    @unlink(KS_ROOT.'/'.TOKEN_FILE.'.tmp.php');
    $self = KS_ROOT.'/'.KS_SELF;
    @unlink($self);
    json_out(['ok' => true, 'self_deleted' => !is_file($self)]);
}

// ---------------------------------------------------------------------------
// HTML
// ---------------------------------------------------------------------------

$loggedIn = token_valid();
$state = state_load();
$finished = !empty($state['finished_at']);
$archivesNow = $loggedIn ? archives_available() : [];
// The database form after a reload: everything but the password, which
// never goes into the page. dbtest takes an empty field as «as before».
$dbSaved = $loggedIn && isset($state['db']) && is_array($state['db']) ? $state['db'] : [];
$dbForm = [
    'host' => (string) ($dbSaved['host'] ?? 'localhost'),
    'port' => (string) ($dbSaved['port'] ?? '3306'),
    'database' => (string) ($dbSaved['database'] ?? ''),
    'username' => (string) ($dbSaved['username'] ?? ''),
];

header('X-Robots-Tag: noindex, nofollow');
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>FreeScout kickstart <?= VERSION ?></title>
<style>
    :root {
        --bg: #f4f6f8; --card: #fff; --ink: #22262a; --muted: #6c7278;
        --line: #dfe3e8; --accent: #4a6fd4; --ok: #3f9142; --warn: #b8860b; --err: #b94a48;
    }
    * { box-sizing: border-box; }
    body {
        margin: 0; padding: 24px 16px 64px;
        font: 14px/1.55 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        background: var(--bg); color: var(--ink);
    }
    .wrap { max-width: 820px; margin: 0 auto; }
    h1 { font-size: 20px; margin: 0 0 4px; }
    h1 small { font-weight: 400; color: var(--muted); font-size: 13px; }
    h2 { font-size: 15px; margin: 0 0 12px; }
    .card {
        background: var(--card); border: 1px solid var(--line); border-radius: 10px;
        padding: 20px; margin-bottom: 16px;
    }
    .steps { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 20px; padding: 0; list-style: none; }
    .steps li {
        font-size: 12px; padding: 4px 10px; border-radius: 20px;
        background: #e7eaee; color: var(--muted);
    }
    .steps li.is-active { background: var(--accent); color: #fff; }
    .steps li.is-done { background: #dcecdd; color: var(--ok); }
    label { display: block; font-weight: 600; margin: 14px 0 4px; font-size: 13px; }
    label.inline { display: flex; align-items: center; gap: 8px; font-weight: 400; margin: 8px 0; }
    input[type=text], input[type=password], input[type=number], select, textarea {
        width: 100%; padding: 8px 10px; border: 1px solid var(--line);
        border-radius: 6px; font: inherit; background: #fff;
    }
    textarea { font-family: Menlo, Consolas, monospace; font-size: 12px; }
    .hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
    .row { display: flex; gap: 12px; flex-wrap: wrap; }
    .row > * { flex: 1 1 160px; }
    button {
        font: inherit; font-weight: 600; padding: 9px 16px; border-radius: 6px;
        border: 1px solid transparent; background: var(--accent); color: #fff; cursor: pointer;
    }
    button.secondary { background: #fff; border-color: var(--line); color: var(--ink); font-weight: 400; }
    button[disabled] { opacity: .5; cursor: default; }
    .actions { display: flex; gap: 8px; margin-top: 20px; align-items: center; }
    .actions .spacer { flex: 1; }
    table { width: 100%; border-collapse: collapse; font-size: 13px; }
    th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
    th { font-size: 12px; color: var(--muted); font-weight: 600; }
    .pill { font-size: 11px; padding: 1px 7px; border-radius: 10px; }
    .pill.ok { background: #dcecdd; color: var(--ok); }
    .pill.no { background: #f6dcdb; color: var(--err); }
    .pill.warn { background: #f7ecd0; color: var(--warn); }
    .note { border-left: 3px solid var(--warn); background: #fdf8ec; padding: 10px 12px; border-radius: 0 6px 6px 0; margin: 14px 0; font-size: 13px; }
    .note.bad { border-color: var(--err); background: #fdf0f0; }
    .note.good { border-color: var(--ok); background: #f0f7f0; }
    .note strong { display: block; margin-bottom: 3px; }
    #log {
        font-family: Menlo, Consolas, monospace; font-size: 12px; line-height: 1.5;
        background: #1e2126; color: #d6dae0; border-radius: 6px; padding: 12px;
        max-height: 320px; overflow-y: auto; white-space: pre-wrap; margin-top: 14px;
    }
    /* An empty log is a black bar sitting under the summary, which reads as
       part of the layout rather than as an empty container. */
    #log:empty { display: none; }
    #log .e { color: #ff8f8f; }
    #log .d { color: #8b939c; }
    .bar { height: 6px; background: #e7eaee; border-radius: 3px; overflow: hidden; margin-top: 12px; }
    .bar > i { display: block; height: 6px; background: var(--accent); width: 0; transition: width .25s; }
    .kv { font-size: 13px; }
    .kv div { display: flex; gap: 10px; padding: 3px 0; }
    .kv span:first-child { color: var(--muted); min-width: 150px; }
    code { background: #eceff2; padding: 1px 5px; border-radius: 4px; font-size: 12px; }
</style>
</head>
<body>
<div class="wrap">
<h1>FreeScout kickstart <small>Version <?= VERSION ?> · Wiederherstellung aus einem .fsback</small></h1>

<?php if (!$loggedIn): ?>
    <div class="card">
        <h2>Zugangstoken</h2>
        <?php if ($token === null): ?>
            <div class="note bad">
                <strong>Verzeichnis nicht beschreibbar</strong>
                <?= htmlspecialchars(KS_ROOT) ?> lässt sich nicht beschreiben, deshalb konnte kein
                Token erzeugt werden. Ohne beschreibbares Verzeichnis ist eine Wiederherstellung
                ohnehin nicht möglich — bitte die Rechte korrigieren und neu laden.
            </div>
        <?php else: ?>
            <p class="hint">
                <strong>Das Token hast Du nicht vorher</strong> — kickstart hat es eben beim ersten
                Aufruf erzeugt. Es steht nicht auf dem Notfallblatt und ist nicht das Archivpasswort;
                das kommt erst im Schritt «Archiv».
            </p>
            <p class="hint">
                Öffne die Datei <code><?= TOKEN_FILE ?></code> neben dieser Datei per SFTP, SSH oder
                im Dateimanager des Hosters und gib die zweite Zeile hier ein; die erste sorgt dafür,
                dass der Webserver die Datei niemandem ausliefert. Das ist absichtlich so: dieses
                Skript darf ein Verzeichnis überschreiben und eine Datenbank leeren, also muss es
                beweisen, dass am anderen Ende jemand mit Dateizugriff sitzt.
            </p>
            <?php if (!empty($loginError)): ?>
                <div class="note bad"><?= htmlspecialchars($loginError) ?></div>
            <?php endif; ?>
            <form method="post" action="?task=login">
                <label for="tok">Token</label>
                <input type="text" id="tok" name="ks_token" autocomplete="off" autofocus
                       placeholder="32 Hexzeichen">
                <div class="actions">
                    <button type="submit">Weiter</button>
                </div>
            </form>
        <?php endif; ?>
    </div>
<?php elseif ($finished): ?>
    <div class="card">
        <h2>Wiederherstellung abgeschlossen</h2>
        <div class="note good">
            <strong>Fertig am <span data-ts="<?= (int) strtotime($state['finished_at']) ?>"><?= htmlspecialchars(date('d.m.Y H:i', strtotime($state['finished_at']))) ?></span></strong>
            Datenbank importiert, Dateien entpackt, <code>.env</code> geschrieben<?php
            if (!empty($state['app_timezone'])): ?>, Zeitzone <code>APP_TIMEZONE=<?= htmlspecialchars($state['app_timezone']) ?></code>
            passend zum Datenbankserver<?php endif; ?>.
        </div>
        <?php $links = isset($state['links']) && is_array($state['links']) ? $state['links'] : null; ?>
        <?php if ($links && !empty($links['failed'])): ?>
            <div class="note bad">
                <strong>Verknüpfungen in public/ fehlen</strong>
                Der Host erlaubt kickstart keine symbolischen Links. Ohne sie fehlen der Anmeldeseite
                Stylesheet und Logo. Mit Shell-Zugang: <code>php artisan storage:link</code> und je Modul
                <code>php artisan freescout:module-install &lt;alias&gt;</code>. Fehlend:
                <?= htmlspecialchars(implode(', ', $links['failed'])) ?>
            </div>
        <?php endif; ?>
        <?php if (isset($state['scratch_removed']) && !$state['scratch_removed']): ?>
            <div class="note bad">
                <strong>Arbeitsverzeichnis konnte nicht gelöscht werden</strong>
                Es enthält <code>database.sql</code> im Klartext und bei einem verschlüsselten
                Archiv eine entschlüsselte Kopie davon — beides im Webroot. Bitte den Ordner
                <code><?= htmlspecialchars(basename(work_dir())) ?></code> von Hand entfernen,
                oder unten auf Löschen klicken.
            </div>
        <?php endif; ?>
        <?php if (!empty($state['app_key_generated'])): ?>
            <div class="note bad">
                <strong>Ein neuer APP_KEY wurde erzeugt</strong>
                Damit sind alle mit dem alten Key verschlüsselten Werte unlesbar: Mailbox-Passwörter
                (<code>in_password</code>/<code>out_password</code>), OAuth-Tokens, Bexio-Tokens und
                Calendar-Zugangsdaten. Diese Zugänge müssen neu eingegeben werden. Vault ist nicht
                betroffen — das verschlüsselt im Browser.
            </div>
        <?php endif; ?>
        <p><strong>Was jetzt noch zu tun ist</strong></p>
        <ul class="hint" style="font-size:13px">
            <li>Webserver-Wurzel auf das Unterverzeichnis <code>public/</code> zeigen lassen.</li>
            <li>Dateibesitzer auf den Webserver-Benutzer setzen, z.&nbsp;B.
                <code>chown -R www-data:www-data .</code></li>
            <li>Datenbank auf den Stand des Codes bringen — das Backup kann aus einer älteren
                Schemaversion stammen: <code>php artisan migrate --force</code>, oder ohne Shell
                nach dem Anmelden unter Verwalten → System → Tools mit «Migrate DB».</li>
            <?php if (empty($state['app_timezone'])): ?>
                <li><code>APP_TIMEZONE</code> in <code>.env</code> auf die Zeitzone des Datenbankservers
                    setzen; kickstart konnte sie nicht bestimmen. Stimmt sie nicht, zeigt FreeScout
                    alle Zeiten um den Unterschied verschoben.</li>
            <?php endif; ?>
            <li>In <code>.env</code> die Mail- und Queue-Einstellungen nachtragen; kickstart schreibt
                nur das Minimum für einen Start.</li>
            <li>Cron wieder einrichten: <code>* * * * * php artisan schedule:run</code></li>
        </ul>
        <?php if ($archivesNow): ?>
            <label class="inline">
                <input type="checkbox" id="cleanup-archives" checked>
                Auch das Archiv löschen:
                <?= implode(', ', array_map(function ($a) { return '<code>'.htmlspecialchars($a['name']).'</code>'; }, $archivesNow)) ?>
            </label>
            <p class="hint">Es enthält die ganze Instanz und liegt im Web-Verzeichnis. Eine Kopie bleibt in der Ablage.</p>
        <?php endif; ?>
        <div class="actions">
            <button id="cleanup">kickstart.php, Token und Arbeitsdateien löschen</button>
            <div class="spacer"></div>
        </div>
        <div id="log" style="display:none"></div>
    </div>
<?php else: ?>
    <ul class="steps" id="steps">
        <li data-step="1" class="is-active">1 · Prüfung</li>
        <li data-step="2">2 · Archiv</li>
        <li data-step="3">3 · FreeScout-Core</li>
        <li data-step="4">4 · Datenbank</li>
        <li data-step="5">5 · Schlüssel</li>
        <li data-step="6">6 · Wiederherstellen</li>
    </ul>

    <!-- 1 -->
    <div class="card" data-panel="1">
        <h2>Systemprüfung</h2>
        <table id="checks"><tbody><tr><td>Wird geprüft …</td></tr></tbody></table>
        <div class="actions">
            <div class="spacer"></div>
            <button id="to2" disabled>Weiter</button>
        </div>
    </div>

    <!-- 2 -->
    <div class="card" data-panel="2" style="display:none">
        <h2>Archiv wählen</h2>
        <p class="hint">
            Lade das <code>.fsback</code> per FTP oder SCP neben diese Datei — nicht über den
            Browser. Ein Backup ist typischerweise mehrere hundert Megabyte gross, und ein
            HTTP-Upload dieser Grösse scheitert an <code>upload_max_filesize</code>, bevor er
            an der Zeit scheitert.
        </p>
        <div id="archives"></div>
        <details id="fetch-box"<?= $archivesNow ? '' : ' open' ?> style="margin:14px 0">
            <summary style="cursor:pointer">Archiv liegt noch nicht hier? Von einer Adresse oder aus einem S3-Speicher holen</summary>
            <label class="inline"><input type="radio" name="fetchmode" value="url" checked> Von einer Adresse</label>
            <label class="inline"><input type="radio" name="fetchmode" value="s3"> Aus einem S3-Speicher (Swiss Backup, Amazon S3 …)</label>
            <div id="fetch-url">
                <label for="fetch-url-input">Adresse des Archivs</label>
                <input type="text" id="fetch-url-input" placeholder="https://…/freescout-backup-….fsback.enc">
                <p class="hint">Zum Beispiel der «Link für kickstart» von der Backup-Seite. Der Server muss Teilabrufe (HTTP Range) können, sonst geht es nur bis zu 8 MB.</p>
            </div>
            <div id="fetch-s3" style="display:none">
                <label for="fetch-endpoint">Endpunkt</label>
                <input type="text" id="fetch-endpoint" value="https://s3.swiss-backup02.infomaniak.com">
                <p class="hint">Bei Swiss Backup ist die Zahl nach swiss-backup der Cluster aus dem Infomaniak Manager. Für Amazon S3 leer lassen.</p>
                <label for="fetch-region">Region</label>
                <input type="text" id="fetch-region" value="us-east-1">
                <label for="fetch-bucket">Bucket</label>
                <input type="text" id="fetch-bucket">
                <label for="fetch-prefix">Präfix</label>
                <input type="text" id="fetch-prefix" placeholder="z. B. freescout/">
                <p class="hint">Wie in den Einstellungen der Ablage und auf dem Notfallblatt. Leer, wenn die Archive direkt im Bucket liegen.</p>
                <label for="fetch-access">Zugriffsschlüssel</label>
                <input type="text" id="fetch-access" autocomplete="off">
                <label for="fetch-secret">Geheimer Schlüssel</label>
                <input type="password" id="fetch-secret" autocomplete="new-password">
                <label class="inline"><input type="checkbox" id="fetch-pathstyle" checked> Pfad-Stil (Swiss Backup ja, Amazon S3 nein)</label>
                <p class="hint">Der geheime Schlüssel wird nur zum Auflisten und zum Signieren eines Download-Links gebraucht und nirgends gespeichert.</p>
                <div class="actions" style="margin-top:6px">
                    <button type="button" class="secondary" id="fetch-s3-list">Archive auflisten</button>
                    <div class="spacer"></div>
                </div>
                <div id="fetch-s3-archives"></div>
            </div>
            <div class="actions" style="margin-top:10px">
                <button type="button" id="fetch-start">Herunterladen</button>
                <div class="spacer"></div>
            </div>
            <div id="fetch-progress"></div>
        </details>
        <div id="archive-password-wrap" style="display:none">
            <label for="archive-password">Archivpasswort</label>
            <input type="password" id="archive-password" autocomplete="new-password">
            <p class="hint">Dieses Archiv ist verschlüsselt. Das Passwort steht auf dem Notfallblatt, das beim Setzen des Passworts gedruckt wurde. Der APP_KEY steckt im Archiv selbst — er muss nicht separat eingegeben werden.</p>
            <div class="actions" style="margin-top:10px">
                <button type="button" class="secondary" id="archive-password-check">Passwort prüfen</button>
                <div class="spacer"></div>
            </div>
        </div>
        <div id="manifest" style="display:none">
            <div class="note good" id="manifest-note"></div>
            <div class="kv" id="manifest-kv"></div>
        </div>
        <div class="actions">
            <button class="secondary" data-back="1">Zurück</button>
            <div class="spacer"></div>
            <button id="to3" disabled>Weiter</button>
        </div>
    </div>

    <!-- 3 -->
    <div class="card" data-panel="3" style="display:none">
        <h2>FreeScout-Core</h2>
        <p class="hint">
            Das Backup enthält Datenbank, Anhänge und die Module — <strong>nicht</strong> FreeScout
            selbst. Der Core wird deshalb separat beschafft. Der Quell-Zipball von GitHub enthält
            <code>vendor/</code>, ist also lauffähig; Composer wird auf diesem Host nicht gebraucht.
        </p>
        <label class="inline">
            <input type="radio" name="coremode" value="download" checked>
            Passende Version von GitHub laden
        </label>
        <label for="corever">Version</label>
        <input type="text" id="corever" placeholder="z. B. 1.8.236">
        <p class="hint" id="corever-hint">Vorbelegt aus <code>manifest.json</code>. Tags: github.com/<?= CORE_REPO ?>/releases</p>
        <label class="inline">
            <input type="radio" name="coremode" value="skip">
            Core ist schon vorhanden oder wird von Hand entpackt
        </label>
        <p class="hint">
            Von Hand entpackt: FreeScouts <code>.htaccess</code> im Hauptordner leitet jeden Aufruf
            nach <code>public/</code> um, auch den von kickstart.php. Die Datei deshalb
            vorher umbenennen (z.&nbsp;B. in <code>.htaccess.aus</code>) und erst nach der
            Wiederherstellung zurück.
        </p>
        <div class="actions">
            <button class="secondary" data-back="2">Zurück</button>
            <div class="spacer"></div>
            <button id="to4">Weiter</button>
        </div>
    </div>

    <!-- 4 -->
    <div class="card" data-panel="4" style="display:none">
        <h2>Datenbank</h2>
        <div class="row">
            <div><label for="dbhost">Host</label><input type="text" id="dbhost" value="<?= htmlspecialchars($dbForm['host']) ?>"></div>
            <div style="flex:0 0 110px"><label for="dbport">Port</label><input type="number" id="dbport" value="<?= htmlspecialchars($dbForm['port']) ?>"></div>
        </div>
        <label for="dbname">Datenbank</label><input type="text" id="dbname" placeholder="z. B. freescout" value="<?= htmlspecialchars($dbForm['database']) ?>">
        <div class="row">
            <div><label for="dbuser">Benutzer</label><input type="text" id="dbuser" value="<?= htmlspecialchars($dbForm['username']) ?>"></div>
            <div><label for="dbpass">Passwort</label><input type="password" id="dbpass" autocomplete="new-password"<?= $dbSaved ? ' placeholder="gespeichert — leer lassen"' : '' ?>></div>
        </div>
        <label class="inline"><input type="checkbox" id="dbcreate"> Datenbank anlegen, falls sie fehlt</label>
        <label class="inline"><input type="checkbox" id="dbdrop" checked> Vorhandene Tabellen vorher löschen</label>
        <p class="hint">
            Ohne Löschen bricht der Import an der ersten bereits existierenden Tabelle ab. Bei
            einem leeren Ziel ist der Haken harmlos.
        </p>
        <div id="dbresult"></div>
        <div class="actions">
            <button class="secondary" data-back="3">Zurück</button>
            <button class="secondary" id="dbtest">Verbindung testen</button>
            <div class="spacer"></div>
            <button id="to5" disabled>Weiter</button>
        </div>
    </div>

    <!-- 5 -->
    <div class="card" data-panel="5" style="display:none">
        <h2>APP_KEY</h2>
        <div class="note" id="appkey-warning">
            <strong>Der wichtigste Punkt dieses Assistenten</strong>
            Laravel verschlüsselt mehrere Datenbankspalten mit dem <code>APP_KEY</code>. Das
            Backup enthält kein <code>.env</code>, der Schlüssel ist also nicht im Archiv. Mit
            einem neuen Schlüssel sind nach der Wiederherstellung unlesbar: Mailbox-Passwörter
            (<code>in_password</code>, <code>out_password</code>), OAuth-Tokens
            (<code>a_token</code>, <code>r_token</code>), die Bexio-Tokens und die
            Calendar-Zugangsdaten. Vault ist nicht betroffen — dort wird im Browser verschlüsselt.
        </div>
        <div class="note good" id="appkey-from-archive" style="display:none">
            <strong>Der APP_KEY kommt aus dem Archiv</strong>
            Dieses Archiv ist verschlüsselt und enthält deshalb den Schlüssel selbst. Er wird beim
            Entschlüsseln gelesen und übernommen — hier ist nichts einzugeben. Nur wenn Du
            bewusst einen anderen Schlüssel verwenden willst, trag ihn unten ein.
        </div>
        <label for="appkey" id="appkey-label">Alter APP_KEY aus dem <code>.env</code> der Quellinstanz</label>
        <input type="text" id="appkey" placeholder="base64:..." autocomplete="off">
        <p class="hint" id="appkey-hint">
            Leer lassen erzeugt einen neuen Schlüssel — dann müssen die oben genannten Zugänge
            danach neu eingegeben werden. Alles andere bleibt vollständig erhalten.
        </p>
        <label for="appurl">APP_URL</label>
        <input type="text" id="appurl">
        <div class="actions">
            <button class="secondary" data-back="4">Zurück</button>
            <div class="spacer"></div>
            <button id="to6">Weiter</button>
        </div>
    </div>

    <!-- 6 -->
    <div class="card" data-panel="6" style="display:none">
        <h2>Wiederherstellen</h2>
        <div class="kv" id="summary"></div>
        <div class="note bad" id="destructive">
            <strong>Ab hier wird geschrieben</strong>
            Dateien in <?= htmlspecialchars(KS_ROOT) ?> werden angelegt und überschrieben, und die
            gewählte Datenbank wird gefüllt<span id="dropnote"></span>.
        </div>
        <div class="bar"><i id="bar"></i></div>
        <div id="log"></div>
        <div class="actions">
            <button class="secondary" data-back="5" id="back6">Zurück</button>
            <div class="spacer"></div>
            <button id="start">Wiederherstellung starten</button>
        </div>
    </div>
<?php endif; ?>

<p class="hint" style="text-align:center; margin-top:24px">
    kickstart.php ist Teil des Backup-Moduls von let's automate · AGPL-3.0 ·
    Diese Datei nach der Wiederherstellung löschen.
</p>
</div>

<script>
(function () {
    var $ = function (id) { return document.getElementById(id); };
    var post = function (task, data) {
        var body = new URLSearchParams();
        Object.keys(data || {}).forEach(function (k) { body.append(k, data[k]); });
        return fetch('?task=' + task, {
            method: 'POST',
            body: body,
            credentials: 'same-origin',
            headers: {'X-Requested-With': 'XMLHttpRequest'}
        }).then(function (r) { return r.json(); });
    };

    // Server clocks often run in UTC; times are shown in the browser's zone.
    document.querySelectorAll('[data-ts]').forEach(function (el) {
        var d = new Date(parseInt(el.getAttribute('data-ts'), 10) * 1000);
        if (!isNaN(d.getTime())) {
            el.textContent = d.toLocaleString('de-CH', {day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'});
        }
    });

    // --- cleanup on the finished page ---
    var cleanupBtn = $('cleanup');
    if (cleanupBtn) {
        cleanupBtn.addEventListener('click', function () {
            var withArchive = $('cleanup-archives') && $('cleanup-archives').checked;
            if (!confirm(withArchive
                ? 'kickstart.php, das Token, die Arbeitsdateien und das Archiv jetzt löschen?'
                : 'kickstart.php, das Token und die Arbeitsdateien jetzt löschen?')) { return; }
            cleanupBtn.disabled = true;
            post('cleanup', withArchive ? {delete_archives: '1'} : {}).then(function (r) {
                var log = $('log');
                log.style.display = 'block';
                log.textContent = r.self_deleted
                    ? 'Gelöscht. Diese Seite kann geschlossen werden.'
                    : 'Arbeitsdateien gelöscht, aber kickstart.php selbst nicht — bitte von Hand entfernen.';
            });
        });
        return;
    }

    if (!$('steps')) { return; }

    // --- wizard navigation ---
    var current = 1;
    var show = function (n) {
        current = n;
        document.querySelectorAll('[data-panel]').forEach(function (p) {
            p.style.display = (p.getAttribute('data-panel') == n) ? '' : 'none';
        });
        document.querySelectorAll('#steps li').forEach(function (li) {
            var s = parseInt(li.getAttribute('data-step'), 10);
            li.className = s === n ? 'is-active' : (s < n ? 'is-done' : '');
        });
        window.scrollTo(0, 0);
    };
    document.querySelectorAll('[data-back]').forEach(function (b) {
        b.addEventListener('click', function () { show(parseInt(b.getAttribute('data-back'), 10)); });
    });

    // --- step 1: checks ---
    var systemTar = false;
    post('checks', {}).then(function (r) {
        var rows = '', fatal = false;
        (r.checks || []).forEach(function (c) {
            if (c.fatal) { fatal = true; }
            if (c.label === 'Systembefehl tar' && c.ok) { systemTar = true; }
            var cls = c.ok ? 'ok' : (c.fatal ? 'no' : 'warn');
            var word = c.ok ? 'ok' : (c.fatal ? 'fehlt' : 'Hinweis');
            rows += '<tr><td>' + c.label + '</td><td><span class="pill ' + cls + '">' + word +
                    '</span></td><td class="hint" style="margin:0">' + c.detail + '</td></tr>';
        });
        $('checks').innerHTML = '<tbody>' + rows + '</tbody>';
        $('to2').disabled = fatal;
        if (fatal) {
            $('checks').insertAdjacentHTML('afterend',
                '<div class="note bad"><strong>Nicht startklar</strong>Mindestens eine zwingende ' +
                'Voraussetzung fehlt. Bitte oben beheben und neu laden.</div>');
        }
    });
    $('to2').addEventListener('click', function () { show(2); loadArchives(); });

    // --- step 2: archive ---
    var manifest = null;
    var archiveEncrypted = false;
    var archivePasswordOk = false;
    function loadArchives() {
        if ($('archives').dataset.loaded) { return; }
        $('archives').dataset.loaded = '1';
        renderArchives(<?= json_encode($loggedIn ? archives_available() : []) ?>);
    }
    function renderArchives(list) {
        if (!list.length) {
            // The normal case when the backups live in a remote storage:
            // nothing went wrong, the archive simply is not here yet.
            $('archives').innerHTML = '<div class="note"><strong>Noch kein Archiv hier</strong>' +
                'Lade die <code>.fsback</code>-Datei per SFTP neben kickstart.php und lade die Seite ' +
                'neu — oder hol sie unten von einer Adresse oder aus dem S3-Speicher.</div>';
            $('fetch-box').open = true;
            return;
        }
        var rows = '';
        list.forEach(function (a, i) {
            var when = a.taken ? 'Sicherung vom ' + a.taken : 'Datei vom ' + a.mtime;
            rows += '<label class="inline"><input type="radio" name="arch" value="' +
                    a.name.replace(/"/g, '&quot;') + '"' + (i === 0 ? ' checked' : '') + '> ' +
                    escapeHtml(a.name) + ' <span class="hint" style="margin:0">· ' + a.size_human +
                    ' · ' + when + (a.encrypted ? ' · verschlüsselt' : '') + '</span></label>';
        });
        $('archives').innerHTML = rows;
        document.querySelectorAll('input[name=arch]').forEach(function (r) {
            r.addEventListener('change', readManifest);
        });
        readManifest();
    }
    // --- Archiv holen: von einer Adresse oder aus einem S3-Speicher ---
    document.querySelectorAll('input[name=fetchmode]').forEach(function (r) {
        r.addEventListener('change', function () {
            var s3 = document.querySelector('input[name=fetchmode]:checked').value === 's3';
            $('fetch-url').style.display = s3 ? 'none' : 'block';
            $('fetch-s3').style.display = s3 ? 'block' : 'none';
        });
    });
    function s3Fields() {
        return {
            endpoint: $('fetch-endpoint').value, region: $('fetch-region').value, bucket: $('fetch-bucket').value,
            prefix: $('fetch-prefix').value, access_key: $('fetch-access').value, secret_key: $('fetch-secret').value,
            path_style: $('fetch-pathstyle').checked ? '1' : ''
        };
    }
    $('fetch-s3-list').addEventListener('click', function () {
        $('fetch-s3-archives').innerHTML = '<p class="hint">Liste wird geladen …</p>';
        post('s3list', s3Fields()).then(function (r) {
            if (r.error) {
                $('fetch-s3-archives').innerHTML = '<div class="note bad">' + escapeHtml(r.error) + '</div>';
                return;
            }
            if (!r.archives.length) {
                $('fetch-s3-archives').innerHTML = '<div class="note bad">Unter diesem Präfix liegt kein Archiv dieses Moduls.</div>';
                return;
            }
            var rows = '';
            r.archives.forEach(function (a, i) {
                rows += '<label class="inline"><input type="radio" name="s3arch" value="' + escapeHtml(a.key) + '"' +
                        (i === 0 ? ' checked' : '') + '> ' + escapeHtml(a.key) +
                        ' <span class="hint" style="margin:0">· ' + escapeHtml(a.size_human) + '</span></label>';
            });
            $('fetch-s3-archives').innerHTML = rows;
        }).catch(function (e) {
            $('fetch-s3-archives').innerHTML = '<div class="note bad">' + escapeHtml(String(e)) + '</div>';
        });
    });
    $('fetch-start').addEventListener('click', function () {
        var mode = document.querySelector('input[name=fetchmode]:checked').value;
        var payload;
        if (mode === 's3') {
            var sel = document.querySelector('input[name=s3arch]:checked');
            if (!sel) {
                $('fetch-progress').innerHTML = '<div class="note bad">Bitte zuerst die Archive auflisten und eines wählen.</div>';
                return;
            }
            payload = s3Fields();
            payload.mode = 's3';
            payload.key = sel.value;
        } else {
            payload = {mode: 'url', url: $('fetch-url-input').value};
        }
        var fail = function (msg) {
            $('fetch-progress').innerHTML = '<div class="note bad">' + escapeHtml(String(msg)) + '</div>';
            $('fetch-start').disabled = false;
        };
        var step = function () {
            post('fetch', {}).then(function (r) {
                if (r.error) { fail(r.error); return; }
                $('fetch-progress').innerHTML = '<p class="hint">' + escapeHtml(r.offset_human) +
                    (r.total_human ? ' von ' + escapeHtml(r.total_human) : '') +
                    (r.percent !== null ? ' (' + r.percent + ' %)' : '') + '</p>';
                if (!r.done) { step(); return; }
                $('fetch-progress').innerHTML = '<div class="note good">Archiv geholt.</div>';
                $('fetch-start').disabled = false;
                post('archives', {}).then(function (a) { renderArchives(a.archives || []); });
            }).catch(fail);
        };
        $('fetch-start').disabled = true;
        $('fetch-progress').innerHTML = '<p class="hint">Download wird vorbereitet …</p>';
        post('fetch_prepare', payload).then(function (r) {
            if (r.error) { fail(r.error); return; }
            step();
        }).catch(fail);
    });
    function readManifest(password) {
        var sel = document.querySelector('input[name=arch]:checked');
        if (!sel) { return; }
        $('to3').disabled = true;
        $('manifest').style.display = 'none';
        var payload = {archive: sel.value};
        if (password) { payload.password = password; }
        post('manifest', payload).then(function (r) {
            // An encrypted archive cannot show a manifest yet — see the
            // server side for why. It only proves the password here.
            if (r.encrypted) {
                archiveEncrypted = true;
                $('archive-password-wrap').style.display = '';
                if (r.password_ok) {
                    archivePasswordOk = true;
                    $('manifest').style.display = '';
                    $('manifest-note').className = 'note good';
                    $('manifest-note').innerHTML = '<strong>Passwort stimmt' +
                        (r.remembered ? ' (schon geprüft)' : '') + '</strong>' +
                        'Das Archiv wird beim Wiederherstellen entschlüsselt; Version und APP_KEY ' +
                        'werden dann aus dem Archiv gelesen.';
                    $('manifest-kv').innerHTML = kv('Archiv', 'verschlüsselt (AES-256-GCM)') + kv('Archivgrösse', r.size);
                    $('to3').disabled = false;
                } else {
                    archivePasswordOk = false;
                    $('manifest').style.display = r.error ? '' : 'none';
                    if (r.error) {
                        $('manifest-note').className = 'note bad';
                        $('manifest-note').innerHTML = '<strong>Passwort stimmt nicht</strong>' + r.error;
                        $('manifest-kv').innerHTML = '';
                    }
                }
                return;
            }

            archiveEncrypted = false;
            archivePasswordOk = false;
            $('archive-password-wrap').style.display = 'none';

            if (r.error) {
                $('manifest').style.display = '';
                $('manifest-note').className = 'note bad';
                $('manifest-note').innerHTML = '<strong>Archiv unbrauchbar</strong>' + r.error;
                $('manifest-kv').innerHTML = '';
                return;
            }
            manifest = r.manifest;
            var mods = manifest.modules || {};
            var names = Object.keys(mods);
            $('manifest').style.display = '';
            $('manifest-note').className = 'note good';
            $('manifest-note').innerHTML = '<strong>Archiv gelesen</strong>Gültiges Backup dieses Moduls.';
            $('manifest-kv').innerHTML =
                kv('FreeScout-Version', manifest.app_version || '—') +
                kv('Erstellt', (manifest.created_at || '—').replace('T', ' ').substring(0, 19)) +
                kv('Archivgrösse', r.size) +
                kv('Module (' + names.length + ')', names.length ? names.join(', ') : '—');
            if (manifest.app_version) { $('corever').value = manifest.app_version; }
            $('to3').disabled = false;
        });
    }
    function kv(k, v) { return '<div><span>' + k + '</span><span>' + v + '</span></div>'; }

    $('archive-password-check').addEventListener('click', function () {
        readManifest($('archive-password').value);
    });
    $('archive-password').addEventListener('keydown', function (e) {
        if (e.key === 'Enter') { e.preventDefault(); readManifest($('archive-password').value); }
    });

    $('to3').addEventListener('click', function () {
        show(3);
        // With an encrypted archive the version is only known after
        // decryption, so the field may legitimately stay empty.
        if (archiveEncrypted && !$('corever').value) {
            $('corever-hint').innerHTML = 'Leer lassen — die Version wird beim Entschlüsseln aus dem ' +
                'Archiv gelesen. Nur ausfüllen, wenn eine andere Version installiert werden soll.';
        }
    });
    $('to4').addEventListener('click', function () {
        show(4);
        if (!$('appurl').value) { $('appurl').value = location.origin; }
    });

    // --- step 4: database ---
    var dbOk = false;
    $('dbtest').addEventListener('click', function () {
        $('dbresult').innerHTML = '<p class="hint">Wird getestet …</p>';
        post('dbtest', {
            host: $('dbhost').value, port: $('dbport').value, database: $('dbname').value,
            username: $('dbuser').value, password: $('dbpass').value,
            create: $('dbcreate').checked ? 1 : ''
        }).then(function (r) {
            if (r.error) {
                dbOk = false;
                $('to5').disabled = true;
                $('dbresult').innerHTML = '<div class="note bad"><strong>Keine Verbindung</strong>' +
                    escapeHtml(r.error) + '</div>';
                return;
            }
            dbOk = true;
            $('to5').disabled = false;
            var warn = r.tables > 0
                ? '<div class="note"><strong>' + r.tables + ' Tabellen bereits vorhanden</strong>' +
                  ($('dbdrop').checked
                      ? 'Sie werden vor dem Import gelöscht.'
                      : 'Ohne «Vorhandene Tabellen löschen» bricht der Import ab.') + '</div>'
                : '';
            $('dbresult').innerHTML = '<div class="note good"><strong>Verbindung steht</strong>' +
                'MySQL ' + escapeHtml(r.server) + ', ' + r.tables + ' Tabellen.</div>' + warn;
        });
    });
    $('to5').addEventListener('click', function () {
        show(5);
        // Exactly one of the two blocks applies. Showing the warning about a
        // missing key next to the note saying the key is in the archive would
        // contradict itself on the same screen.
        $('appkey-from-archive').style.display = archiveEncrypted ? '' : 'none';
        $('appkey-warning').style.display = archiveEncrypted ? 'none' : '';
        $('appkey-hint').textContent = archiveEncrypted
            ? 'Leer lassen ist hier das Normale — der Schlüssel kommt aus dem Archiv.'
            : 'Leer lassen erzeugt einen neuen Schlüssel — dann müssen die oben genannten Zugänge '
              + 'danach neu eingegeben werden. Alles andere bleibt vollständig erhalten.';
        $('appkey-label').textContent = archiveEncrypted
            ? 'Abweichender APP_KEY (optional)'
            : 'Alter APP_KEY aus dem .env der Quellinstanz';
    });
    $('to6').addEventListener('click', function () {
        show(6);
        var mode = document.querySelector('input[name=coremode]:checked').value;
        $('summary').innerHTML =
            kv('Archiv', document.querySelector('input[name=arch]:checked').value) +
            kv('FreeScout-Core', mode !== 'download'
                ? 'schon vorhanden'
                : ($('corever').value
                    ? 'GitHub ' + $('corever').value
                    : 'GitHub, Version aus dem Archiv')) +
            kv('Datenbank', $('dbuser').value + '@' + $('dbhost').value + ' / ' + $('dbname').value) +
            kv('APP_KEY', $('appkey').value
                ? 'von Hand eingegeben'
                : (archiveEncrypted ? 'aus dem Archiv' : 'wird neu erzeugt')) +
            kv('Entpacker', systemTar ? 'Systembefehl tar' : 'PHP (in Häppchen)');
        $('dropnote').textContent = $('dbdrop').checked ? ' — vorhandene Tabellen werden gelöscht' : '';
    });

    // --- step 6: run ---
    function logLine(text, cls) {
        var log = $('log');
        var span = document.createElement('div');
        if (cls) { span.className = cls; }
        span.textContent = text;
        log.appendChild(span);
        log.scrollTop = log.scrollHeight;
    }
    function escapeHtml(s) {
        return String(s).replace(/[&<>"]/g, function (c) {
            return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[c];
        });
    }

    $('start').addEventListener('click', function () {
        if (!confirm('Wiederherstellung jetzt starten? Dateien und Datenbank werden überschrieben.')) {
            return;
        }
        $('start').disabled = true;
        $('back6').disabled = true;

        var mode = document.querySelector('input[name=coremode]:checked').value;

        // Decryption and reading the manifest come first: for an encrypted
        // archive the FreeScout version and the APP_KEY only become known
        // once the manifest is reachable, and the core download needs the
        // version.
        var phases = [];
        phases.push(['decrypt', 'Archiv entschlüsseln']);
        phases.push(['read_manifest', 'Manifest lesen']);
        if (mode === 'download') { phases.push(['core_download', 'FreeScout-Core laden']); }
        phases.push(['core_extract', 'Core entpacken']);
        phases.push(['archive', 'Archiv entpacken']);
        phases.push(['database', 'Datenbank importieren']);
        phases.push(['finalise', 'Fertigstellen']);

        var options = JSON.stringify({
            core_wanted: mode === 'download' ? 1 : 0,
            core_version: mode === 'download' ? $('corever').value : '',
            app_key: $('appkey').value,
            app_url: $('appurl').value,
            db_drop_tables: $('dbdrop').checked ? 1 : 0,
            use_system_tar: systemTar ? 1 : 0
        });

        var pi = 0, firstCall = true;
        function runPhase() {
            if (pi >= phases.length) {
                logLine('');
                logLine('Fertig. Seite wird neu geladen …');
                setTimeout(function () { location.href = location.pathname; }, 1200);
                return;
            }
            var phase = phases[pi][0], label = phases[pi][1];
            var payload = {phase: phase};
            if (firstCall) { payload.options = options; firstCall = false; }

            post('run', payload).then(function (r) {
                if (r.error) {
                    logLine('ABBRUCH: ' + r.error, 'e');
                    $('back6').disabled = false;
                    return;
                }
                if (r.progress !== null && r.progress !== undefined) {
                    $('bar').style.width = Math.max(2, r.progress) + '%';
                }
                logLine((r.done ? '✓ ' : '· ') + label + ' — ' + r.message,
                        /FEHLER/.test(r.message) ? 'e' : null);
                if (r.detail) { logLine('    ' + r.detail, 'd'); }

                if (/FEHLER|ABBRUCH/.test(r.message)) {
                    $('back6').disabled = false;
                    return;
                }
                if (r.done) { pi++; $('bar').style.width = '0'; }
                setTimeout(runPhase, 50);
            }).catch(function (e) {
                logLine('Netzwerkfehler: ' + e.message + ' — noch ein Versuch …', 'e');
                setTimeout(runPhase, 2000);
            });
        }
        logLine('Wiederherstellung gestartet ' + new Date().toLocaleTimeString());
        runPhase();
    });
})();
</script>
</body>
</html>
