#!/usr/bin/env bash
###############################################################################
# ApexQuant — public one-command installer  (served at https://get.vardynnode.com and https://get.apexquant.tech)
#
#   curl -fsSL https://get.vardynnode.com | sudo bash        (or: curl -fsSL https://get.apexquant.tech | sudo bash)
#
# Downloads the canonical dist from /files/ (the SITE origins below, in order; the next one is tried when one
# is unreachable, answers an error or does not verify), verifies its minisign signature (authenticity +
# integrity) with a PINNED key, extracts to /root/ApexQuant, and runs install.sh --unattended. The zip and its
# signature always come from the SAME origin. All logic lives in main(), invoked only on the LAST line — so a
# truncated curl|bash executes nothing.
###############################################################################
set -euo pipefail

# ORIGINS (the one place the download domains are named, here and in aq-update.sh). Public face: vardynnode.com; backend: apexquant.tech (permanent, kept as the fallback). AQ_DIST_URL / AQ_SIG_URL still override: when set they are the only URLs used.
SITE_ORIGINS="${AQ_SITE_ORIGINS:-https://vardynnode.com https://apexquant.tech}"
DIST_URL="${AQ_DIST_URL:-}"
SIG_URL="${AQ_SIG_URL:-}"
# PINNED minisign public key — NOT env-overridable. To rotate, edit this line.
readonly AQ_MINISIGN_PUBKEY="RWRHtMOGHSz0oywqtMdW5cQkw2UE1llujBPPnUFkW1RGaz9qRFZHZKSj"
APP_DIR="/root/ApexQuant"
DATA_DIR="/root/apexquant-data"
LOG="/root/apexquant-bootstrap.log"

RED=$'\033[31m'; GRN=$'\033[32m'; YEL=$'\033[33m'; NC=$'\033[0m'
say(){ echo "${GRN}[AQ]${NC} $*"; }
warn(){ echo "${YEL}[AQ]${NC} $*"; }
die(){ echo "${RED}[AQ] ERROR:${NC} $*" >&2; exit 1; }

main(){
    # bootstrap log holds credentials later — root-only BEFORE teeing.
    umask 077
    touch "$LOG"; chmod 600 "$LOG"
    exec > >(tee -a "$LOG") 2>&1
    say "ApexQuant installer starting $(date -u)"

    # 1) preflight
    [[ $EUID -eq 0 ]] || die "Run as root:  curl -fsSL https://get.vardynnode.com | sudo bash"
    command -v apt-get >/dev/null 2>&1 || die "Debian/Ubuntu (apt) only."
    . /etc/os-release 2>/dev/null || true
    if [[ "${ID:-}" != "ubuntu" || "${VERSION_ID:-}" != "24.04" ]]; then
        if [[ "${AQ_ALLOW_UNSUPPORTED_OS:-0}" == "1" ]]; then
            warn "Unsupported OS ${PRETTY_NAME:-unknown} — proceeding (AQ_ALLOW_UNSUPPORTED_OS=1). Dist is Python 3.12 ABI-locked; likely to fail."
        else
            die "ApexQuant requires Ubuntu 24.04 LTS (Python 3.12). Found ${PRETTY_NAME:-unknown}. Deploy a 24.04 image and retry.  (Advanced override: AQ_ALLOW_UNSUPPORTED_OS=1)"
        fi
    fi
    [[ -f "$APP_DIR/main.py" ]] && die "ApexQuant already at $APP_DIR. Use '$APP_DIR/install.sh --update' instead."
    [[ -d "$DATA_DIR" ]] && die "$DATA_DIR already exists (previous install). Remove it or use --update before reinstalling."

    # 2) deps (minisign mandatory — pinned-key verification is required)
    export DEBIAN_FRONTEND=noninteractive
    say "Installing prerequisites"
    apt-get update -y -qq
    apt-get install -y -qq --no-install-recommends curl ca-certificates unzip coreutils minisign
    command -v minisign >/dev/null 2>&1 || die "minisign is required for signature verification but could not be installed."

    # 3) download + MANDATORY signature verification (no sha256 fallback)
    local TMP_ZIP TMP_SIG o d g got=0 first=""
    TMP_ZIP="$(mktemp /root/aq-dist.XXXXXX.zip)"; TMP_SIG="${TMP_ZIP}.minisig"
    trap 'rm -f "$TMP_ZIP" "$TMP_SIG"' EXIT
    # one origin at a time: its zip and its signature together; an origin that fails, or whose signature is not valid, is passed over (never accepted)
    local -a CANDS=()
    if [[ -n "$DIST_URL$SIG_URL" ]]; then
        d="${DIST_URL:-${SITE_ORIGINS%% *}/files/ApexQuant-Setup.zip}"; CANDS+=("$d ${SIG_URL:-$d.minisig}")
    else
        for o in $SITE_ORIGINS; do CANDS+=("$o/files/ApexQuant-Setup.zip $o/files/ApexQuant-Setup.zip.minisig"); done
    fi
    for c in "${CANDS[@]}"; do
        read -r d g <<< "$c"
        say "Downloading dist: $d"
        rm -f "$TMP_ZIP" "$TMP_SIG"
        curl -fSL --retry 3 "$d" -o "$TMP_ZIP" 2>/dev/null && [[ -s "$TMP_ZIP" ]] || { warn "Download from ${d#*://} failed — trying the next origin"; continue; }
        say "Fetching signature: $g"
        curl -fsSL "$g" -o "$TMP_SIG" 2>/dev/null && [[ -s "$TMP_SIG" ]] || { warn "Cannot fetch the signature from this origin — trying the next origin"; continue; }
        minisign -V -P "$AQ_MINISIGN_PUBKEY" -m "$TMP_ZIP" -x "$TMP_SIG" >/dev/null 2>&1 \
            || { warn "SIGNATURE VERIFICATION FAILED for the download from ${d#*://} — not used, trying the next origin"; continue; }
        got=1; first="$d"; break
    done
    [[ "$got" == 1 ]] || die "No origin gave a download that is authentically signed by ApexQuant. Aborting rather than install unverified."
    say "Signature verified (minisign, pinned key); package served by ${first#*://}"
    rm -f "$TMP_SIG"

    # count this install (curl|bash bypasses the website /dl/ping beacon) — fire-and-forget
    if [[ -n "${AQ_BEACON_URL:-}" ]]; then curl -fsS -m 5 "$AQ_BEACON_URL" -o /dev/null 2>&1 || true
    else for o in $SITE_ORIGINS; do curl -fsS -m 5 "$o/dl/ping?src=cli" -o /dev/null 2>&1 && break; done; fi

    # 4) extract -> /root/ApexQuant, run installer from there
    say "Extracting to $APP_DIR"
    unzip -oq "$TMP_ZIP" -d /root
    [[ -f "$APP_DIR/install.sh" ]] || die "install.sh not found at $APP_DIR after extract (bad dist?)."
    cd "$APP_DIR"; chmod +x install.sh
    say "Running ApexQuant installer (systemd, nginx, firewall, credentials)"
    AQ_UNATTENDED=1 ./install.sh --unattended

    # 5) surface credentials + config commands
    local IP INSTALL_LOG HANDOVER
    IP="$(curl -fsSL https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')"
    INSTALL_LOG="$(ls -t /root/apexquant-install-*.log 2>/dev/null | head -1)"
    HANDOVER="$(ls -t "$APP_DIR"/handover-*.html 2>/dev/null | head -1)"
    say "Install complete."
    echo
    echo "  DASHBOARD:  https://${IP}/    (accept the self-signed cert the first time)"
    echo
    echo "  LOGIN (auto-generated password + PIN):"
    if [[ -n "$INSTALL_LOG" ]]; then
        grep -iE "dashboard password|password:|(^|[^A-Za-z])PIN([^A-Za-z]|:)|setup token" "$INSTALL_LOG" | sed 's/^/     /' || true
        echo "     Full details in:  $INSTALL_LOG"
    fi
    echo "     Handover report:  ${HANDOVER:-$APP_DIR/handover-*.html}"
    echo "                       (holds password + PIN; delete after saving: rm '${HANDOVER:-<file>}')"
    echo
    echo "  ADD LICENSE + BINANCE KEYS — run the guided setup ON THE SERVER:"
    echo "     apexquant --setup-gui         # token-gated wizard; prints a URL; self-closes when done"
    echo "     apexquant --show-setup-token  # re-print the setup token if needed"
    echo "     apexquant --config-gui        # edit settings later"
    echo
    echo "  Until a license is added, the bot runs in SAFE/paper mode (no exchange keys needed)."
    echo
    warn "This bootstrap log ($LOG) contains your password + PIN — delete it after saving:  rm '$LOG'"
    say "Docs & license: https://apexquant.tech"
}

main "$@"
