#!/usr/bin/env bash
# Standalone bootstrap, including curl URL | bash.
install_ds1_native_package() (
    set +x
    set -euo pipefail
    umask 077
    [[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || { printf 'Linux x64 required.\n' >&2; exit 1; }
    for dependency in curl tar sha256sum mktemp; do command -v "$dependency" >/dev/null || { printf 'Missing dependency: %s\n' "$dependency" >&2; exit 1; }; done
    zip=${DS1CLI_7ZIP:-}
    if [[ -z $zip ]]; then zip=$(command -v 7zz || command -v 7z || true); fi
    [[ -n $zip && -x $zip ]] || { printf '7-Zip required; install 7zip or set DS1CLI_7ZIP.\n' >&2; exit 1; }
    version=${DS1CLI_VERSION:-0.3.0-rc.3}
    [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { printf 'Invalid DS1CLI_VERSION.\n' >&2; exit 1; }
    install_root=${DS1_INSTALL_ROOT:-$HOME/.local/share/ds1cli-rust}
    [[ $install_root == /* ]] || { printf 'DS1_INSTALL_ROOT must be absolute.\n' >&2; exit 1; }
    mode=${DS1_INSTALL_MODE:-auto}
    case "$mode" in auto|install|update) ;; *) printf 'DS1_INSTALL_MODE: auto, install or update.\n' >&2; exit 1;; esac
    registered=false
    [[ ! -f $install_root/install-receipt.json ]] || registered=true
    if [[ $mode == auto ]]; then if $registered; then mode=update; else mode=install; fi; fi
    [[ $mode != update ]] || $registered || { printf 'No Rust installation registered at target.\n' >&2; exit 1; }
    name="ds1cli-$version-linux-x64.7z"
    case "${DS1CLI_DISTRIBUTION:-registry}" in
        registry) base="https://forgejo.ds1david.space/api/packages/ds1david/generic/ds1cli-linux-x64/$version";;
        release) base="https://forgejo.ds1david.space/ds1david/ds1-cli/releases/download/v$version";;
        *) printf 'DS1CLI_DISTRIBUTION: registry or release; no automatic fallback.\n' >&2; exit 1;;
    esac
    stage=$(mktemp -d "${TMPDIR:-/tmp}/ds1cli-native-XXXXXXXX")
    trap 'rm -rf -- "$stage"' EXIT
    printf 'ds1cli %s: %s -> %s\n' "$version" "$mode" "$install_root"
    download() {
        local url=$1 output=$2 status
        printf 'Download: %s\n' "$url"
        status=$(curl --silent --show-error --proto '=https' --write-out '%{http_code}' "$url" -o "$output") || { printf 'Download transport failed: %s\n' "$url" >&2; exit 1; }
        [[ $status == 200 ]] || { printf 'Download failed. HTTP=%s; URL=%s. Check server/proxy and approved network access.\n' "$status" "$url" >&2; exit 1; }
    }
    if [[ -n ${DS1CLI_PACKAGE_PATH:-} ]]; then
        [[ $DS1CLI_PACKAGE_PATH == *.7z ]] || { printf 'A password-protected .7z package is required.\n' >&2; exit 1; }
        cp -- "$DS1CLI_PACKAGE_PATH" "$stage/$name"
        cp -- "$DS1CLI_PACKAGE_PATH.sha256" "$stage/$name.sha256"
        name_on_disk=$(basename -- "$DS1CLI_PACKAGE_PATH")
    else
        download "$base/$name.sha256" "$stage/$name.sha256"
        download "$base/$name" "$stage/$name"
        name_on_disk=$name
    fi
    read -r expected expected_name extra < "$stage/$name.sha256"
    [[ $expected =~ ^[0-9a-fA-F]{64}$ && ${expected_name#\*} == "$name_on_disk" && -z ${extra:-} ]] || { printf 'Invalid package SHA256 sidecar.\n' >&2; exit 1; }
    actual=$(sha256sum -- "$stage/$name")
    [[ ${actual%% *} == "${expected,,}" ]] || { printf 'Package SHA256 mismatch. Expected=%s; received=%s; extraction refused: incomplete or altered download.\n' "$expected" "${actual%% *}" >&2; exit 1; }
    password=${DS1CLI_PACKAGE_PASSWORD:-}
    unset DS1CLI_PACKAGE_PASSWORD DS1CLI_PACKAGE_PASSWORD_FILE
    if [[ -z $password ]]; then
        if [[ -t 0 ]]; then
            printf 'Senha do pacote de distribuicao: ' >&2
            IFS= read -r -s password
            printf '\n' >&2
        elif ( : </dev/tty ) 2>/dev/null; then
            printf 'Senha do pacote de distribuicao: ' >/dev/tty
            IFS= read -r -s password </dev/tty
            printf '\n' >/dev/tty
        else
            printf 'Password requires an interactive terminal or DS1CLI_PACKAGE_PASSWORD.\n' >&2
            exit 1
        fi
    fi
    [[ -n $password && $password != *$'\n'* && $password != *$'\r'* ]] || { printf 'A nonempty single-line password is required.\n' >&2; exit 1; }
    if ! printf '%s\n' "$password" | "$zip" x -sccUTF-8 -so "$stage/$name" payload.tar.gz >"$stage/decrypted.tar.gz" 2>"$stage/7zip.log"; then
        unset password
        printf 'Package decryption/integrity failed (wrong password or damaged package). Nothing extracted or installed.\n' >&2
        exit 1
    fi
    unset password
    mkdir "$stage/package"
    tar -tzf "$stage/decrypted.tar.gz" > "$stage/entries"
    while IFS= read -r entry; do
        case "$entry" in /*|..|../*|*/../*|*/..) printf 'Unsafe archive entry.\n' >&2; exit 1;; esac
    done < "$stage/entries"
    tar -tvzf "$stage/decrypted.tar.gz" > "$stage/details"
    while IFS= read -r entry; do
        [[ $entry == -* || $entry == d* ]] || { printf 'Archive links or special entries are not supported.\n' >&2; exit 1; }
    done < "$stage/details"
    tar --no-same-owner --no-same-permissions -xzf "$stage/decrypted.tar.gz" -C "$stage/package" || { printf 'Package extraction/integrity failed; nothing installed.\n' >&2; exit 1; }
    [[ -f $stage/package/package-files.sha256 && -f $stage/package/build-manifest.json ]] || { printf 'Native manifest missing; use a complete RC.2 or newer package.\n' >&2; exit 1; }
    while read -r hash entry; do
        [[ $hash =~ ^[0-9a-f]{64}$ && $entry != /* && $entry != *..* ]] || { printf 'Invalid manifest path/hash.\n' >&2; exit 1; }
    done < "$stage/package/package-files.sha256"
    (cd "$stage/package" && sha256sum --strict -c package-files.sha256) || { printf 'Package content integrity failed.\n' >&2; exit 1; }
    binary="$stage/package/bin/ds1cli"
    [[ -f $binary && -x $binary ]] || { printf 'Native binary missing from package.\n' >&2; exit 1; }
    actual_version=$("$binary" --version)
    [[ $actual_version == "ds1cli/$version "* ]] || { printf 'Executable version differs from requested version.\n' >&2; exit 1; }
    arguments=(package "$mode" --target "$install_root")
    case "${DS1CLI_INSTALL_PLAN:-}" in 1|true) arguments+=(--plan);; esac
    if [[ ${DS1CLI_INSTALL_PLAN:-} == 1 || ${DS1CLI_INSTALL_PLAN:-} == true ]]; then
        "$binary" "${arguments[@]}"
    else
        if [[ -t 0 ]]; then
            "$binary" "${arguments[@]}"
        elif ( : </dev/tty ) 2>/dev/null; then
            "$binary" "${arguments[@]}" </dev/tty
        else
            printf 'Interactive terminal required; use DS1CLI_INSTALL_PLAN=1 to inspect.\n' >&2
            exit 1
        fi
    fi
    printf 'Target: %s\nPATH directory (after confirmation): %s/bin\n' "$install_root" "$install_root"
)
install_ds1_native_package
ds1_bootstrap_status=$?
unset -f install_ds1_native_package
exit "$ds1_bootstrap_status"
