#!/usr/bin/env bash
# DataCoreLink Virtualizor mirror installer. Requires an existing Virtualizor host.
set -euo pipefail
SCRIPT_VERSION="2.8.1"
VIRT_DIR="/usr/local/virtualizor"
UNIV_PHP="${VIRT_DIR}/universal.php"
EMPS_PHP="/usr/local/emps/bin/php"
STATE_DIR="${VIRT_DIR}/scripts/dcl-mirror"
GUARD_SCRIPT="${VIRT_DIR}/scripts/dcl_mirror_guard.sh"
CRON_FILE="/etc/cron.d/datacorelink-mirror-guard"
CLI_BIN="/usr/local/bin/dcl-mirror"
LOCK_FILE="/run/lock/datacorelink-mirror-install.lock"
LEGACY_GUARD="${VIRT_DIR}/scripts/bahari_mirror_guard.sh"
LEGACY_CRON="${CRON_FILE%/*}/bahari-virtualizor-guard"
# Retired: plain-HTTP private mirror. Recognized only to migrate saved targets away from it.
LEGACY_PRIVATE_MIRROR="http://10.20.30.101/virtualizor"
DOMAIN_MIRROR="https://mirror.datacorelink.com/virtualizor"
UPDATE_CHECK_URL="https://mirror.datacorelink.com/v.version"
UPDATE_SCRIPT_URL="https://mirror.datacorelink.com/v.sh"
UPDATE_SIG_URL="https://mirror.datacorelink.com/v.sh.minisig"
# Pinned minisign public key (base64 line of the .pub file), embedded at release
# build time. Releases are signed offline; the private key never reaches a server.
SIGNING_PUBKEY="RWTjJpUTHdnY+LMOAUC6HyX84k/8xhsHp+EjKJ6k06yWWxjNOy40oaQF"
RELEASE_COMMENT="dcl-mirror-installer file=v.sh version="
# DCL-OS Virtualizor theme package. Its SHA256 is embedded at release build time,
# so this signed installer vouches for the exact archive it installs as root.
THEME_SHA256="c5dbe56b85a7d6ce011bbb417cd8a32a561c3405f5c1c320fec7e8dbb654f0c1"
THEME_URL_BASE="https://mirror.datacorelink.com/dcl-theme"
PANEL_PHP="/usr/local/emps/bin/php"
REPORT_URL="https://mirror.datacorelink.com/api/virtualizor/v1/report"
SIGNAL_URL="https://mirror.datacorelink.com/api/virtualizor/v1/signal"

fail() { echo "[!] $*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || fail "Run as root."
[[ $# -le 1 ]] || fail "Use at most one option."
# --revoke: DCL-OS blocked this server. Restore the original Virtualizor settings
# exactly like --restore, after switching the panel back to the default theme.
REVOKE=0
if [[ ${1:-} == --revoke ]]; then
    REVOKE=1
    set -- --restore
fi
case "${1:-}" in ''|--auto-update|--enforce|--restore) ;; *) fail "Unknown option: $1" ;; esac
DEPENDENCIES=(flock mktemp install cp mv rm)
if [[ ${1:-} != --restore && ${1:-} != --enforce ]]; then
    DEPENDENCIES+=(curl timeout)
fi
for dependency in "${DEPENDENCIES[@]}"; do
    command -v "$dependency" >/dev/null || fail "Required command missing: $dependency"
done
# EMPS may omit tokenizer or use an older PHP. Prefer it when compatible,
# otherwise use an existing system interpreter; never change the host PHP setup.
PHP_SELECTED=""
for candidate in "$EMPS_PHP" /usr/bin/php /usr/local/bin/php; do
    if [[ -x $candidate ]] && "$candidate" -r 'exit(version_compare(PHP_VERSION, "7.0.0", ">=") && function_exists("json_decode") && function_exists("preg_match") ? 0 : 1);' 2>/dev/null; then
        PHP_SELECTED=$candidate
        break
    fi
done
[[ -n $PHP_SELECTED ]] || fail "No compatible PHP CLI found. PHP 7.0+ with JSON/PCRE is required (EMPS or system PHP); configuration unchanged."
if [[ ${1:-} != --restore ]]; then
    [[ $SIGNING_PUBKEY =~ ^[A-Za-z0-9+/]{56}$ ]] || fail "This installer build has no pinned release signing key; use a signed release."
fi
EMPS_PHP=$PHP_SELECTED
[[ ! -L "$UNIV_PHP" ]] || fail "universal.php must not be a symlink."
if [[ ${1:-} != --restore ]]; then
    [[ -f "$UNIV_PHP" ]] || fail "Virtualizor configuration not found at $UNIV_PHP"
fi
if [[ ${1:-} != --restore && ${1:-} != --enforce ]]; then
    cron_active() {
        if command -v systemctl >/dev/null && { systemctl is-active --quiet cron.service 2>/dev/null || systemctl is-active --quiet crond.service 2>/dev/null; }; then
            return 0
        fi
        command -v pgrep >/dev/null && { pgrep -x cron >/dev/null || pgrep -x crond >/dev/null; }
    }
    cron_active || fail "No active cron/crond daemon detected. Start the host scheduler, then retry; configuration unchanged."
fi
# Restore excludes both the updater and installer, in the same lock order.
if [[ ${1:-} == --restore ]]; then
    exec 8>"${LOCK_FILE%.lock}-guard.lock"
    flock -w 30 8 || fail "An update is running; retry restore later."
fi
exec 9>"$LOCK_FILE"
flock -w 30 9 || fail "Another mirror operation is running; try again later."
install -d -m 700 "$STATE_DIR"
# Status reports for the DCL-OS install list are on by default; this opts out for good.
[[ ${DCL_NO_REPORT:-} != 1 ]] || : > "$STATE_DIR/no-report"
WORK=$(mktemp -d "$STATE_DIR/work.XXXXXX")
# Do not mutate managed files until every snapshot is complete.
MANAGED=("$UNIV_PHP" "$GUARD_SCRIPT" "$CRON_FILE" "$CLI_BIN" "$STATE_DIR/installer.sh" "$STATE_DIR/target" "$STATE_DIR/previous.php" "$STATE_DIR/original.php" "$LEGACY_CRON" "$LEGACY_GUARD" "$STATE_DIR/verify-signature.php")
PUBLICATION_FILES=()
# Rename a complete file within its destination filesystem. Never truncate a
# script that a running Bash process may still be reading through an open fd.
publish_file() {
    local source=$1 destination=$2 mode=${3:-preserve} staged
    staged=$(mktemp "${destination%/*}/.${destination##*/}.publish.XXXXXX") || return 1
    PUBLICATION_FILES+=("$staged")
    if [[ $mode == preserve ]]; then
        cp -p "$source" "$staged" || return 1
    else
        install -m "$mode" "$source" "$staged" || return 1
    fi
    mv -f "$staged" "$destination"
}
SNAPSHOTS_READY=0
DIRTY=0
cleanup() {
    status=$?
    trap - EXIT
    trap '' HUP INT TERM
    set +e
    rollback_failed=0
    if [[ $status -ne 0 && $SNAPSHOTS_READY -eq 1 && $DIRTY -eq 1 ]]; then
        for index in "${!MANAGED[@]}"; do
            if [[ -f $WORK/saved.$index ]]; then
                if ! publish_file "$WORK/saved.$index" "${MANAGED[$index]}"; then
                    rollback_failed=1
                fi
            elif ! rm -f -- "${MANAGED[$index]}"; then
                rollback_failed=1
            fi
        done
        if [[ $rollback_failed -eq 0 ]]; then
            echo "[!] Operation failed; previous configuration restored." >&2
        else
            echo "[!] Rollback incomplete. Recovery snapshots retained in $WORK" >&2
        fi
    fi
    if [[ ${#PUBLICATION_FILES[@]} -gt 0 ]]; then
        rm -f -- "${PUBLICATION_FILES[@]}"
    fi
    [[ $rollback_failed -ne 0 ]] || rm -rf -- "$WORK"
    exit "$status"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
for index in "${!MANAGED[@]}"; do
    if [[ -e ${MANAGED[$index]} || -L ${MANAGED[$index]} ]]; then
        [[ -f ${MANAGED[$index]} && ! -L ${MANAGED[$index]} ]] || fail "Managed path is not a regular file."
        cp -p "${MANAGED[$index]}" "$WORK/saved.$index"
    fi
done
SNAPSHOTS_READY=1
legacy_validate() {
    if [[ -f $LEGACY_GUARD ]]; then
        local legacy_hash
        legacy_hash=$("$EMPS_PHP" -r 'echo hash_file("sha256", $argv[1]);' -- "$LEGACY_GUARD")
        [[ $legacy_hash == ba231c657c4bb138a8d2c51626539635dcffb067dfbe8da2e8e45dbc3d5dc3f4 ]] \
            || fail "Legacy mirror guard was modified; review $LEGACY_GUARD before migration."
    fi
    if [[ -f $LEGACY_CRON ]]; then
        local line
        while IFS= read -r line || [[ -n $line ]]; do
            line=${line%$'\r'}
            line="${line#"${line%%[![:space:]]*}"}"
            line="${line%"${line##*[![:space:]]}"}"
            case "$line" in
                ''|\#*|'SHELL=/bin/bash'|'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin') ;;
                "19 0,12 * * * root $LEGACY_GUARD >/dev/null 2>&1"|"@reboot root $LEGACY_GUARD >/dev/null 2>&1") ;;
                *) fail "Legacy cron contains an unknown command; review $LEGACY_CRON before migration." ;;
            esac
        done < "$LEGACY_CRON"
    fi
}
legacy_remove() {
    [[ -f $LEGACY_GUARD || -f $LEGACY_CRON ]] || return 0
    # Revalidate immediately before removal; an operator may have edited it.
    legacy_validate
    local archive
    install -d -m 700 "$STATE_DIR/legacy"
    archive=$(mktemp -d "$STATE_DIR/legacy/migration.XXXXXX")
    [[ ! -f $LEGACY_GUARD ]] || cp -p "$LEGACY_GUARD" "$archive/bahari_mirror_guard.sh"
    [[ ! -f $LEGACY_CRON ]] || cp -p "$LEGACY_CRON" "$archive/bahari-virtualizor-guard"
    rm -f -- "$LEGACY_CRON" "$LEGACY_GUARD"
    echo "[✓] Archived and removed legacy mirror guard/cron: $archive"
}
if [[ ${1:-} != --enforce ]]; then
    legacy_validate
fi
# Token inspection never evaluates the panel configuration or matches comments.
cat > "$WORK/mirrors.php" <<'PHP'
<?php
function mirrorTokens($code) {
    $tokens = [];
    if (function_exists('token_get_all')) {
        $offset = 0;
        foreach (token_get_all($code) as $token) {
            $text = is_array($token) ? $token[1] : $token;
            $id = is_array($token) ? token_name($token[0]) : null;
            if (!in_array($id, ['T_WHITESPACE', 'T_COMMENT', 'T_DOC_COMMENT'], true)) $tokens[] = [$id, $text, $offset];
            $offset += strlen($text);
        }
        return $tokens;
    }
    // Small fail-closed reader for EMPS builds without the tokenizer extension.
    // Never eval/include the configuration. Require one ordinary PHP source block.
    if (!preg_match('/\A\s*<\?php\s/', $code, $opening)) throw new RuntimeException('Without tokenizer, configuration must start with an ordinary PHP opening tag.');
    $offset = strlen($opening[0]);
    $length = strlen($code);
    while ($offset < $length) {
        $tail = substr($code, $offset);
        if (substr($tail, 0, 3) === '<<<' || substr($tail, 0, 2) === '?>' || substr($tail, 0, 2) === '<?') {
            // A trailing closing tag is safe; source after it is not parsed as PHP.
            if (preg_match('/\A\?>\s*\z/', $tail)) break;
            throw new RuntimeException('Heredoc/multiple PHP blocks require a PHP CLI with tokenizer; configuration unchanged.');
        }
        if (preg_match('~\A(?:\s+|//[^\r\n]*|\#[^\r\n]*|/\*.*?\*/)~s', $tail, $skip)) {
            $offset += strlen($skip[0]);
            continue;
        }
        $char = $code[$offset];
        if ($char === "'" || $char === '"' || $char === '`') {
            $start = $offset++;
            $closed = false;
            while ($offset < $length) {
                if ($code[$offset] === '\\') { $offset += 2; continue; }
                if ($code[$offset++] === $char) { $closed = true; break; }
            }
            if (!$closed) throw new RuntimeException('Unterminated quoted string; configuration unchanged.');
            $literal = substr($code, $start, $offset - $start);
            // Dynamic strings are not literal mirror settings.
            $id = $char === '`' || ($char === '"' && strpos($literal, '$') !== false) ? 'DYNAMIC_STRING' : 'T_CONSTANT_ENCAPSED_STRING';
            $tokens[] = [$id, $literal, $start];
        } elseif (preg_match('/\A\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*/', $tail, $variable)) {
            $tokens[] = ['T_VARIABLE', $variable[0], $offset];
            $offset += strlen($variable[0]);
        } else {
            $tokens[] = [null, $char, $offset++];
        }
    }
    return $tokens;
}
function mirrorAssignment($code) {
    $tokens = mirrorTokens($code);
    $found = [];
    foreach ($tokens as $i => $token) {
        if ($token[0] !== 'T_VARIABLE' || $token[1] !== '$globals') continue;
        if (($tokens[$i + 1][1] ?? null) !== '[' ||
            !in_array($tokens[$i + 2][1] ?? null, ["'mirrors_by_speed'", '"mirrors_by_speed"'], true) ||
            ($tokens[$i + 3][1] ?? null) !== ']' || ($tokens[$i + 4][1] ?? null) !== '=') continue;
        if (($tokens[$i + 5][0] ?? null) !== 'T_CONSTANT_ENCAPSED_STRING' || ($tokens[$i + 6][1] ?? null) !== ';') {
            throw new RuntimeException('Mirror assignment must contain literal JSON; configuration unchanged.');
        }
        $literal = $tokens[$i + 5][1];
        $inner = substr($literal, 1, -1);
        $json = $literal[0] === "'" ? str_replace(["\\'", "\\\\"], ["'", "\\"], $inner) : stripcslashes($inner);
        $value = json_decode($json, true);
        if (!is_array($value) || array_filter($value, function ($item) { return !is_string($item); })) {
            throw new RuntimeException('Invalid mirrors_by_speed JSON; configuration unchanged.');
        }
        $end = $tokens[$i + 6][2] + 1;
        $found[] = ['offset' => $token[2], 'length' => $end - $token[2], 'value' => $value];
    }
    if (count($found) !== 1) throw new RuntimeException('Expected exactly one active literal mirrors_by_speed assignment; configuration unchanged.');
    return $found[0];
}
try {
    $path = $argv[1];
    $code = file_get_contents($path);
    $current = mirrorAssignment($code);
    if ($argv[2] === '--restore') {
        $original = file_get_contents($argv[3]);
        $saved = mirrorAssignment($original);
        $assignment = substr($original, $saved['offset'], $saved['length']);
    } else {
        $target = $argv[2];
        // Retired entries are removed: old hosts, the plain-HTTP private mirror and
        // the unaffiliated third-party mirror earlier releases appended.
        $legacy = ['http://202.168.151.121/virtualizor', 'https://bahari-os.bahari.top/virtualizor', 'http://10.20.30.121:8080/virtualizor', 'temp_reset',
            'http://10.20.30.101/virtualizor', 'https://mirror.resellercenter.ir', 'https://mirror.resellercenter.ir/'];
        $mirrors = [$target];
        foreach (array_merge($current['value'], ['https://files.virtualizor.com']) as $mirror) {
            if (!in_array($mirror, $legacy, true) && !in_array($mirror, $mirrors, true)) $mirrors[] = $mirror;
        }
        $encoded = json_encode($mirrors, JSON_UNESCAPED_SLASHES);
        if ($encoded === false) throw new RuntimeException('Mirror JSON encoding failed.');
        $assignment = '$globals[\'mirrors_by_speed\'] = '.var_export($encoded, true).';';
    }
    $result = substr_replace($code, $assignment, $current['offset'], $current['length']);
    if (file_put_contents($path, $result) === false) throw new RuntimeException('Failed to stage mirror configuration.');
} catch (Throwable $error) {
    fwrite(STDERR, $error->getMessage()."\n");
    exit(1);
}
PHP

# minisign (prehashed "ED") verification for PHP 7.0+: libsodium when available,
# otherwise the OpenSSL >= 1.1.1 CLI. Missing primitives fail closed.
cat > "$WORK/verify-signature.php" <<'PHP'
<?php
function verifyFail($message) { fwrite(STDERR, $message."\n"); exit(1); }
function verifyOpenssl($directory, $publicKey, $message, $signature) {
    $pem = $directory.'/key.pem'; $input = $directory.'/message.bin'; $sig = $directory.'/signature.bin';
    $der = "\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00".$publicKey;
    if (file_put_contents($pem, "-----BEGIN PUBLIC KEY-----\n".base64_encode($der)."\n-----END PUBLIC KEY-----\n") === false
        || file_put_contents($input, $message) === false || file_put_contents($sig, $signature) === false) verifyFail('Could not stage signature verification.');
    exec('openssl pkeyutl -verify -pubin -inkey '.escapeshellarg($pem).' -rawin -in '.escapeshellarg($input).' -sigfile '.escapeshellarg($sig).' 2>/dev/null', $output, $status);
    @unlink($pem); @unlink($input); @unlink($sig);
    return $status === 0;
}
function verifyPythonScript() {
    return 'import sys, hashlib'."\n"
        .'from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey'."\n"
        .'key, signature, glob, comment = [bytes.fromhex(v) for v in sys.argv[2:6]]'."\n"
        .'digest = hashlib.blake2b(digest_size=64)'."\n"
        .'with open(sys.argv[1], "rb") as stream:'."\n"
        .'    for chunk in iter(lambda: stream.read(65536), b""): digest.update(chunk)'."\n"
        .'public = Ed25519PublicKey.from_public_bytes(key)'."\n"
        .'public.verify(signature, digest.digest())'."\n"
        .'public.verify(glob, signature + comment)'."\n";
}
function verifyPythonAvailable() {
    exec('python3 -c '.escapeshellarg('from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey').' 2>/dev/null', $output, $status);
    return $status === 0;
}
function verifyPython($file, $publicKey, $signature, $global, $comment) {
    exec('python3 -c '.escapeshellarg(verifyPythonScript()).' '.escapeshellarg($file).' '.bin2hex($publicKey).' '.bin2hex($signature).' '.bin2hex($global).' '.bin2hex($comment).' 2>/dev/null', $output, $status);
    return $status === 0;
}
if ($argc !== 5) verifyFail('Usage: verify-signature.php PUBKEY FILE SIGNATURE TRUSTED_COMMENT');
list(, $encodedKey, $file, $signatureFile, $expectedComment) = $argv;
$key = base64_decode($encodedKey, true);
if ($key === false || strlen($key) !== 42 || substr($key, 0, 2) !== 'Ed') verifyFail('Invalid pinned signing key.');
$lines = @file($signatureFile, FILE_IGNORE_NEW_LINES);
if (!is_array($lines) || count($lines) < 4 || strlen(implode('', $lines)) > 1024) verifyFail('Invalid release signature file.');
$lines = array_map(function ($line) { return rtrim($line, "\r"); }, $lines);
if (strpos($lines[0], 'untrusted comment: ') !== 0 || strpos($lines[2], 'trusted comment: ') !== 0) verifyFail('Invalid release signature file.');
$blob = base64_decode($lines[1], true);
$global = base64_decode($lines[3], true);
if ($blob === false || strlen($blob) !== 74 || $global === false || strlen($global) !== 64) verifyFail('Invalid release signature encoding.');
if (substr($blob, 0, 2) !== 'ED') verifyFail('Only prehashed minisign signatures are accepted.');
if (!hash_equals(substr($key, 2, 8), substr($blob, 2, 8))) verifyFail('Release was signed with a different key.');
$signature = substr($blob, 10, 64);
$publicKey = substr($key, 10, 32);
$comment = substr($lines[2], strlen('trusted comment: '));
if (!hash_equals($expectedComment, $comment)) verifyFail('Signed release metadata does not match the published version.');
if (function_exists('sodium_crypto_sign_verify_detached') && function_exists('sodium_crypto_generichash_init')) {
    $state = sodium_crypto_generichash_init('', 64);
    $handle = fopen($file, 'rb');
    if (!$handle) verifyFail('Release file is unreadable.');
    while (!feof($handle)) {
        $chunk = fread($handle, 65536);
        if ($chunk === false) verifyFail('Release file is unreadable.');
        sodium_crypto_generichash_update($state, $chunk);
    }
    fclose($handle);
    $digest = sodium_crypto_generichash_final($state, 64);
    $valid = sodium_crypto_sign_verify_detached($signature, $digest, $publicKey)
        && sodium_crypto_sign_verify_detached($global, $signature.$comment, $publicKey);
} elseif (verifyPythonAvailable()) {
    // EL8 hosts ship platform Python with cryptography but PHP without sodium and
    // OpenSSL 1.1.1 without `pkeyutl -rawin`.
    $valid = verifyPython($file, $publicKey, $signature, $global, $comment);
} else {
    $digest = shell_exec('openssl dgst -blake2b512 -binary '.escapeshellarg($file).' 2>/dev/null');
    if (!is_string($digest) || strlen($digest) !== 64) verifyFail('No signature primitive available (libsodium, Python cryptography or OpenSSL 3).');
    $directory = dirname($signatureFile);
    $valid = verifyOpenssl($directory, $publicKey, $digest, $signature) && verifyOpenssl($directory, $publicKey, $signature.$comment, $global);
}
if (!$valid) verifyFail('Release signature is invalid.');
PHP
"$EMPS_PHP" -l "$WORK/verify-signature.php" >/dev/null || fail "Signature verifier failed PHP syntax validation."

file_sha256() { "$EMPS_PHP" -r 'echo hash_file("sha256", $argv[1]);' -- "$1"; }
# Install, update or repair the DCL-OS Virtualizor theme from the package whose
# SHA256 this signed installer pins. The verified archive is cached so hourly
# repair works offline. Theme problems never undo the mirror configuration.
theme_sync() {
    local archive="$STATE_DIR/theme.tar.gz"
    [[ $THEME_SHA256 =~ ^[a-f0-9]{64}$ ]] || return 0
    if [[ -f $STATE_DIR/theme-disabled ]]; then
        return 0
    fi
    command -v python3 >/dev/null && command -v tar >/dev/null || { echo "[!] DCL theme needs python3 and tar; theme not installed (mirror unaffected)." >&2; return 1; }
    if [[ ! -f $archive || $(file_sha256 "$archive") != "$THEME_SHA256" ]]; then
        command -v curl >/dev/null || { echo "[!] No verified DCL theme package cached and curl is unavailable." >&2; return 1; }
        curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 5 --max-time 120 --max-filesize 16777216 \
            "$THEME_URL_BASE/$THEME_SHA256.tar.gz" -o "$WORK/theme.tar.gz" || { echo "[!] DCL theme package download failed; retried hourly." >&2; return 1; }
        [[ $(file_sha256 "$WORK/theme.tar.gz") == "$THEME_SHA256" ]] || { echo "[!] DCL theme package SHA256 mismatch; nothing installed." >&2; return 1; }
        publish_file "$WORK/theme.tar.gz" "$archive" 600 || return 1
    fi
    rm -rf -- "$WORK/theme" && mkdir -m 700 "$WORK/theme" || return 1
    tar -xzf "$archive" -C "$WORK/theme" --no-same-owner --no-same-permissions || { echo "[!] DCL theme package could not be extracted." >&2; return 1; }
    [[ -x $PANEL_PHP ]] || { echo "[!] Virtualizor EMPS PHP is missing; DCL theme not installed." >&2; return 1; }
    python3 "$WORK/theme/install-media-theme.py" sync --lock-held --root "$VIRT_DIR" --php "$PANEL_PHP" --state "$STATE_DIR" --backup-dir "$STATE_DIR" \
        || { echo "[!] DCL theme sync stopped; the current theme was left as it was." >&2; return 1; }
    publish_file "$WORK/theme/install-media-theme.py" "$STATE_DIR/install-media-theme.py" 700 || return 1
}
THEME_RESULT=""
# Tell DCL-OS this server uses the mirror (its admin list of installs): hostname,
# Virtualizor/OS/installer/theme versions and the event. The address is the one
# DCL-OS sees. Best effort only; opt out with DCL_NO_REPORT=1 or dcl-mirror report-off.
report_status() {
    local event=$1 theme_state=none version patch os name
    [[ ! -f $STATE_DIR/no-report ]] || return 0
    command -v curl >/dev/null || return 0
    if [[ -f $STATE_DIR/theme-disabled ]]; then
        theme_state=disabled
    elif [[ $THEME_RESULT == failed ]]; then
        theme_state=failed
    elif [[ -f $STATE_DIR/install-media-theme.py ]]; then
        theme_state=managed
    fi
    # Read as text; the panel configuration is never executed here.
    version=$(sed -n "s/^\$globals\['version'\] = '\([0-9.]*\)';.*/\1/p" "$VIRT_DIR/globals.php" 2>/dev/null | head -n 1) || version=""
    patch=$(sed -n "s/^\$globals\['patch'\] = '\([0-9]*\)';.*/\1/p" "$VIRT_DIR/globals.php" 2>/dev/null | head -n 1) || patch=""
    [[ -z $version || -z $patch ]] || version="$version.$patch"
    os=$(. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-}") || os=""
    # hostname -f can wait on DNS; never let it stall the hourly check.
    name=$(timeout 5 hostname -f 2>/dev/null) || name=$(hostname 2>/dev/null) || name=""
    "$EMPS_PHP" -r '
        $hostname = preg_match("/\\A[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?\\z/", $argv[2]) ? $argv[2] : null;
        $version = preg_match("/\\A[0-9][0-9.]{0,31}\\z/", $argv[3]) ? $argv[3] : null;
        $os = substr(trim(preg_replace("/[^A-Za-z0-9 .,()\\/_+-]/", "", $argv[4])), 0, 120);
        echo json_encode(["event" => $argv[1], "hostname" => $hostname, "virtualizor_version" => $version, "os" => $os === "" ? null : $os,
            "installer_version" => $argv[5], "theme_sha256" => preg_match("/\\A[a-f0-9]{64}\\z/", $argv[6]) ? $argv[6] : null, "theme_state" => $argv[7]]);' \
        -- "$event" "$name" "$version" "$os" "$SCRIPT_VERSION" "$THEME_SHA256" "$theme_state" > "$WORK/report.json" 2>/dev/null || return 0
    curl --silent --output /dev/null --proto '=https' --proto-redir '=https' --connect-timeout 5 --max-time 10 --max-filesize 4096 \
        -H 'Content-Type: application/json' -H 'Accept: application/json' --data-binary "@$WORK/report.json" "$REPORT_URL" || true
}

if [[ ${1:-} == --restore ]]; then
    if [[ $REVOKE == 1 ]]; then
        echo "[!] DataCoreLink revoked DCL-OS access for this server; removing DCL-OS and restoring the original Virtualizor settings."
        report_status revoked
        if [[ -f $STATE_DIR/install-media-theme.py ]] && command -v python3 >/dev/null; then
            python3 "$STATE_DIR/install-media-theme.py" disable --lock-held --root "$VIRT_DIR" --php "$PANEL_PHP" --state "$STATE_DIR" \
                || echo "[!] The default Virtualizor theme could not be selected; review the theme setting." >&2
        fi
    fi
    [[ -f "$STATE_DIR/original.php" ]] || fail "No preserved original backup. Legacy .bak files require operator review."
    "$EMPS_PHP" -l "$STATE_DIR/original.php" >/dev/null || fail "Original backup failed PHP syntax validation."
    if [[ -f "$UNIV_PHP" ]]; then
        "$EMPS_PHP" -l "$UNIV_PHP" >/dev/null || fail "Current universal.php is invalid; manual recovery required."
        cp -p "$UNIV_PHP" "$WORK/restored.php"
        "$EMPS_PHP" "$WORK/mirrors.php" "$WORK/restored.php" --restore "$STATE_DIR/original.php"
    else
        cp -p "$STATE_DIR/original.php" "$WORK/restored.php"
    fi
    "$EMPS_PHP" -l "$WORK/restored.php" >/dev/null || fail "Restore syntax validation failed."
    DIRTY=1
    mv -f "$WORK/restored.php" "$UNIV_PHP"
    rm -f "$CRON_FILE" "$GUARD_SCRIPT" "$CLI_BIN"
    legacy_remove
    echo "[✓] Restored original mirror settings; other current settings preserved (missing files recovered from backup)."
    echo "[*] Preserved backup and local installer remain in $STATE_DIR."
    exit 0
fi

SELECTED="$DOMAIN_MIRROR"
if [[ ${1:-} == --enforce && -f "$STATE_DIR/target" ]]; then
    SAVED=$(cat "$STATE_DIR/target")
    # A target saved by <= 2.2.4 may name the retired HTTP mirror; enforce HTTPS.
    [[ $SAVED == "$DOMAIN_MIRROR" || $SAVED == "$LEGACY_PRIVATE_MIRROR" ]] || fail "Invalid saved mirror."
fi
"$EMPS_PHP" -l "$UNIV_PHP" >/dev/null || fail "Existing universal.php has invalid PHP syntax."
DIRTY=1
# Preserve the first configuration permanently, separately from rotating diagnostics.
if [[ ! -f "$STATE_DIR/original.php" ]]; then
    cp -p "$UNIV_PHP" "$WORK/original.php"
    mv "$WORK/original.php" "$STATE_DIR/original.php"
fi
cp -p "$UNIV_PHP" "$WORK/universal.php"
"$EMPS_PHP" "$WORK/mirrors.php" "$WORK/universal.php" "$SELECTED"
"$EMPS_PHP" -l "$WORK/universal.php" >/dev/null || fail "Updated configuration failed PHP syntax validation; original unchanged."
if ! cmp -s "$UNIV_PHP" "$WORK/universal.php"; then
    cp -p "$UNIV_PHP" "$STATE_DIR/previous.php"
    mv -f "$WORK/universal.php" "$UNIV_PHP"
fi
if [[ ${1:-} == --enforce ]]; then
    DIRTY=0
    theme_sync || THEME_RESULT=failed
    report_status heartbeat
    exit 0
fi

printf '%s\n' "$SELECTED" > "$WORK/target"
publish_file "$WORK/target" "$STATE_DIR/target" 600
# Keep a local installer so repair and restore do not depend on a working network.
# bash <file> is used for updates. Initial curl | bash installs are also supported.
if [[ -f ${BASH_SOURCE[0]:-} ]]; then
    install -m 700 "${BASH_SOURCE[0]}" "$WORK/installer.sh"
else
    curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 5 --max-time 60 --max-filesize 262144 "$UPDATE_SCRIPT_URL" -o "$WORK/installer.sh"
    curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 5 --max-time 15 --max-filesize 1024 "$UPDATE_SIG_URL" -o "$WORK/installer.sh.minisig"
    "$EMPS_PHP" "$WORK/verify-signature.php" "$SIGNING_PUBKEY" "$WORK/installer.sh" "$WORK/installer.sh.minisig" "$RELEASE_COMMENT$SCRIPT_VERSION" \
        || fail "Installer signature verification failed."
    grep -Fxq "SCRIPT_VERSION=\"$SCRIPT_VERSION\"" "$WORK/installer.sh" || fail "Published installer version changed; retry installation."
fi
bash -n "$WORK/installer.sh"
publish_file "$WORK/installer.sh" "$STATE_DIR/installer.sh" 700
publish_file "$WORK/verify-signature.php" "$STATE_DIR/verify-signature.php" 600

cat > "$WORK/guard.sh" <<'GUARD'
#!/usr/bin/env bash
set -euo pipefail
LOCAL_VER="__VERSION__"
STATE_DIR="__STATE__"
EMPS="__PHP__"
UPDATE_URL="__UPDATE_URL__"
SCRIPT_URL="__SCRIPT_URL__"
SIG_URL="__SIG_URL__"
PUBKEY="__PUBKEY__"
COMMENT="__COMMENT__"
SIGNAL_URL="__SIGNAL_URL__"
MODE=${1:-}
[[ $EUID -eq 0 ]] || exit 1
# The five-minute signal check starts at a random moment so hosts never arrive together.
if [[ $MODE == --signal-cron ]]; then
    sleep $((RANDOM % 240))
    MODE=--signal
fi
exec 8>"__GUARD_LOCK__"
flock -n 8 || exit 0
WORK=$(mktemp -d "$STATE_DIR/update.XXXXXX")
trap 'rm -rf -- "$WORK"' EXIT
log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
fetch() {
    curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \
        --connect-timeout 5 --max-time 60 --max-filesize "$3" "$1" -o "$2"
}
update() {
    fetch "$UPDATE_URL" "$WORK/version" 64 || return 1
    REMOTE_VER=$(cat "$WORK/version")
    [[ $REMOTE_VER =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || { log "Invalid remote version; update rejected."; return 1; }
    comparison=0
    "$EMPS" -r 'exit(version_compare($argv[1], $argv[2], ">") ? 0 : 1);' -- "$REMOTE_VER" "$LOCAL_VER" || comparison=$?
    if [[ $comparison -eq 1 ]]; then
        log "No newer version (installed $LOCAL_VER, published $REMOTE_VER)."
        return 0
    elif [[ $comparison -ne 0 ]]; then
        log "PHP version comparison failed; update was not checked successfully."
        return 1
    fi
    fetch "$SIG_URL" "$WORK/installer.sh.minisig" 1024 || return 1
    fetch "$SCRIPT_URL" "$WORK/installer.sh" 262144 || return 1
    # Only a release signed by the pinned offline key may run as root here.
    "$EMPS" "$STATE_DIR/verify-signature.php" "$PUBKEY" "$WORK/installer.sh" "$WORK/installer.sh.minisig" "$COMMENT$REMOTE_VER" \
        || { log "Installer signature verification failed; update rejected."; return 1; }
    grep -Fxq "SCRIPT_VERSION=\"$REMOTE_VER\"" "$WORK/installer.sh" || { log "Installer and version manifest differ; update rejected."; return 1; }
    bash -n "$WORK/installer.sh" || return 1
    # Release this inherited descriptor in the child; its installer lock is separate.
    if timeout 180 bash "$WORK/installer.sh" --auto-update 8>&-; then
        log "Updated $LOCAL_VER -> $REMOTE_VER."
    else
        log "Update failed; retaining the local repair path."
        return 1
    fi
}
# Force update: DCL-OS answers whether this host's wave has come. The signal only
# triggers the normal check below; nothing but a signed release is ever installed.
if [[ $MODE == --signal ]]; then
    fetch "$SIGNAL_URL?v=$LOCAL_VER" "$WORK/signal" 2048 2>/dev/null || exit 0
    # Revoked by DataCoreLink: hand over to the installer, which restores the original
    # settings and removes this guard; closing fd 8 releases the guard lock for it.
    if "$EMPS" -r '$d = json_decode((string) file_get_contents($argv[1]), true); exit(is_array($d) && ($d["revoke"] ?? false) === true ? 0 : 1);' -- "$WORK/signal"; then
        log "DCL-OS access for this server was revoked by DataCoreLink; restoring the original Virtualizor settings."
        exec timeout 120 bash "$STATE_DIR/installer.sh" --revoke 8>&-
    fi
    "$EMPS" -r '$d = json_decode((string) file_get_contents($argv[1]), true); exit(is_array($d) && ($d["update"] ?? false) === true ? 0 : 1);' -- "$WORK/signal" || exit 0
    log "Force update requested by DCL-OS."
fi
result=0
update || { result=1; log "Update check failed; retrying next hour. Mirror repair still runs."; }
if ! timeout 60 bash "$STATE_DIR/installer.sh" --enforce 8>&-; then
    log "Mirror repair failed; inspect universal.php and rerun dcl-mirror update."
    result=1
fi
exit "$result"
GUARD
# Values are installer-owned constants, never remote/user-provided substitutions.
sed -i -e "s|__VERSION__|$SCRIPT_VERSION|g" -e "s|__STATE__|$STATE_DIR|g" \
    -e "s|__PHP__|$EMPS_PHP|g" -e "s|__UPDATE_URL__|$UPDATE_CHECK_URL|g" \
    -e "s|__SCRIPT_URL__|$UPDATE_SCRIPT_URL|g" -e "s|__SIG_URL__|$UPDATE_SIG_URL|g" \
    -e "s|__PUBKEY__|$SIGNING_PUBKEY|g" -e "s|__COMMENT__|$RELEASE_COMMENT|g" \
    -e "s|__SIGNAL_URL__|$SIGNAL_URL|g" -e "s|__GUARD_LOCK__|${LOCK_FILE%.lock}-guard.lock|g" "$WORK/guard.sh"
bash -n "$WORK/guard.sh"
publish_file "$WORK/guard.sh" "$GUARD_SCRIPT" 700
# Each host keeps one random minute for its hourly check, so hosts never all
# arrive at the same moment; it survives updates and reinstalls.
CRON_MINUTE=$(cat "$STATE_DIR/cron-minute" 2>/dev/null || true)
if [[ ! $CRON_MINUTE =~ ^[1-5]?[0-9]$ ]]; then
    printf '%s\n' "$((RANDOM % 60))" > "$WORK/cron-minute"
    publish_file "$WORK/cron-minute" "$STATE_DIR/cron-minute" 600
    CRON_MINUTE=$(cat "$STATE_DIR/cron-minute")
fi
cat > "$WORK/cron" <<CRON
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Hourly at this host's own minute, plus boot; a light force-update signal every
# five minutes (after a random delay). Errors/status go to cron mail/journal.
$CRON_MINUTE * * * * root $GUARD_SCRIPT
*/5 * * * * root $GUARD_SCRIPT --signal-cron
@reboot root $GUARD_SCRIPT
CRON
publish_file "$WORK/cron" "$CRON_FILE" 644
cat > "$WORK/cli" <<CLI
#!/usr/bin/env bash
set -euo pipefail
case "\${1:-}" in
    update) exec bash "$GUARD_SCRIPT" ;;
    restore) exec bash "$STATE_DIR/installer.sh" --restore ;;
    theme-disable) exec python3 "$STATE_DIR/install-media-theme.py" disable --root "$VIRT_DIR" --php "$PANEL_PHP" --state "$STATE_DIR" --lock-file "$LOCK_FILE" ;;
    theme-enable) rm -f -- "$STATE_DIR/theme-disabled"; exec bash "$STATE_DIR/installer.sh" --enforce ;;
    report-off) : > "$STATE_DIR/no-report"; echo "Status reports to DCL-OS are off." ;;
    report-on) rm -f -- "$STATE_DIR/no-report"; echo "Status reports to DCL-OS are on; the next hourly check reports." ;;
    *)
        echo "DataCoreLink mirror v$SCRIPT_VERSION — hourly update check at minute $CRON_MINUTE, force-update signal every 5 minutes"
        grep 'mirrors_by_speed' "$UNIV_PHP"
        if [[ -f "$STATE_DIR/theme-disabled" ]]; then echo "DCL theme: disabled"; elif [[ -f "$STATE_DIR/install-media-theme.py" ]]; then echo "DCL theme: managed (hourly repair)"; else echo "DCL theme: not installed"; fi
        echo "DCL-OS access: on-demand downloads if this server's IP is a trusted host in DCL-OS, otherwise cached media"
        if [[ -f "$STATE_DIR/no-report" ]]; then echo "Status reports: off"; else echo "Status reports: on (hourly)"; fi
        echo "Commands: dcl-mirror update | restore | theme-disable | theme-enable | report-off | report-on"
        ;;
esac
CLI
bash -n "$WORK/cli"
publish_file "$WORK/cli" "$CLI_BIN" 755
legacy_remove
echo "[✓] Mirror v$SCRIPT_VERSION: $SELECTED"
echo "[✓] Auto-update: hourly at minute $CRON_MINUTE, force-update signal every 5 minutes, plus reboot. Commands: dcl-mirror update | dcl-mirror restore"
# The mirror is committed; the theme below never rolls it back.
DIRTY=0
if [[ $THEME_SHA256 =~ ^[a-f0-9]{64}$ ]]; then
    if [[ -f $STATE_DIR/theme-disabled ]]; then
        echo "[*] DCL theme disabled on this host (dcl-mirror theme-enable to restore)."
    elif theme_sync; then
        echo "[✓] DCL-OS Virtualizor theme ready; repaired hourly."
    else
        THEME_RESULT=failed
        echo "[!] DCL theme not installed this time; the hourly check retries." >&2
    fi
fi
if [[ -f $STATE_DIR/no-report ]]; then
    echo "[*] Status reports to DCL-OS are off (dcl-mirror report-on to enable)."
else
    report_status "$([[ ${1:-} == --auto-update ]] && echo update || echo install)"
    echo "[*] This server reports its hostname, IP and versions to DCL-OS hourly. Opt out: dcl-mirror report-off"
fi
