#!/usr/bin/env bash
###############################################################################
# ApexQuant — public one-command installer  (served at https://get.apexquant.tech)
#
#   curl -fsSL https://get.apexquant.tech | sudo bash
#
# Downloads the canonical dist from /files/, verifies its minisign signature
# (authenticity + integrity) with a PINNED key, extracts to /root/ApexQuant,
# and runs install.sh --unattended. All logic lives in main(), invoked only on
# the LAST line — so a truncated curl|bash executes nothing.
###############################################################################
set -euo pipefail

DIST_URL="${AQ_DIST_URL:-https://apexquant.tech/files/ApexQuant-Setup.zip}"
SIG_URL="${AQ_SIG_URL:-${DIST_URL}.minisig}"
# 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.apexquant.tech | 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
    TMP_ZIP="$(mktemp /root/aq-dist.XXXXXX.zip)"; TMP_SIG="${TMP_ZIP}.minisig"
    trap 'rm -f "$TMP_ZIP" "$TMP_SIG"' EXIT
    say "Downloading dist: $DIST_URL"
    curl -fSL --retry 3 "$DIST_URL" -o "$TMP_ZIP"
    say "Fetching signature: $SIG_URL"
    curl -fsSL "$SIG_URL" -o "$TMP_SIG" || die "Cannot fetch signature ($SIG_URL). Aborting rather than install unverified."
    minisign -V -P "$AQ_MINISIGN_PUBKEY" -m "$TMP_ZIP" -x "$TMP_SIG" >/dev/null 2>&1 \
        || die "SIGNATURE VERIFICATION FAILED — the download is not authentically signed by ApexQuant. Aborting."
    say "Signature verified (minisign, pinned key)"
    rm -f "$TMP_SIG"

    # count this install (curl|bash bypasses the website /dl/ping beacon) — fire-and-forget
    curl -fsS -m 5 "${AQ_BEACON_URL:-https://apexquant.tech/dl/ping?src=cli}" -o /dev/null 2>&1 || true

    # 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 "$@"
