#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Slippage — installer
#
# Installs the sniper bot into a folder in your current directory. The bot itself
# is downloaded from the license server gated behind your license key.
#
# Usage:
#   curl -fsSL https://install.slippa.ge | bash -s -- SNIP-xxxxx
#   SNIPER_LICENSE=SNIP-xxxxx  curl -fsSL https://install.slippa.ge | bash
#   ./install.sh SNIP-xxxxx                          # if you downloaded this file
#
# Options (env):
#   SNIPER_LICENSE       license key (alternative to passing it as an argument)
#   SNIPER_DIR           install folder name (default: sniper)
#   SNIPER_LICENSE_URL   license server base URL (default below)
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail

LICENSE_URL="${SNIPER_LICENSE_URL:-https://install.slippa.ge}"
DIR_NAME="${SNIPER_DIR:-sniper}"
LICENSE_KEY="${1:-${SNIPER_LICENSE:-}}"

# ── Colors ───────────────────────────────────────────────────────────────────
CYAN='\033[0;96m'; GREEN='\033[0;92m'; YELLOW='\033[0;93m'; RED='\033[0;91m'
BOLD='\033[1m'; DIM='\033[2m'; RESET='\033[0m'
info()    { echo -e "${CYAN}  →${RESET} $*"; }
success() { echo -e "${GREEN}  ✓${RESET} $*"; }
warn()    { echo -e "${YELLOW}  ⚠${RESET} $*"; }
error()   { echo -e "${RED}  ✗${RESET} $*"; exit 1; }

echo -e ""
echo -e "${BOLD}${CYAN}  ╔══════════════════════════════════════════╗${RESET}"
echo -e "${BOLD}${CYAN}  ║           Slippage — installer           ║${RESET}"
echo -e "${BOLD}${CYAN}  ╚══════════════════════════════════════════╝${RESET}"
echo -e ""

# ── Dependencies ─────────────────────────────────────────────────────────────
for t in curl tar sha256sum; do
  command -v "$t" >/dev/null 2>&1 || error "'$t' is required but not found. Install it and retry."
done

# ── License key (arg > env > prompt) ─────────────────────────────────────────
if [ -z "${LICENSE_KEY}" ]; then
  if [ -t 0 ]; then
    read -r -p "  Enter your license key (SNIP-…): " LICENSE_KEY
  else
    error "No license key. Pass it: curl … | bash -s -- SNIP-xxxxx   (or set SNIPER_LICENSE)"
  fi
fi
[ -z "${LICENSE_KEY}" ] && error "License key is empty."

# ── Target folder (in the current directory) ─────────────────────────────────
TARGET="$(pwd)/${DIR_NAME}"
if [ -e "${TARGET}" ] && [ -n "$(ls -A "${TARGET}" 2>/dev/null || true)" ]; then
  error "Folder '${TARGET}' already exists and is not empty. Set SNIPER_DIR=other or remove it."
fi
mkdir -p "${TARGET}"
info "Install dir: ${TARGET}"

# ── Ask the license server for the release (token + manifest) ────────────────
info "Contacting license server…"
RESP="$(curl -fsS -X POST "${LICENSE_URL}/v1/install/init" \
  -H 'Content-Type: application/json' \
  -d "{\"license_key\":\"${LICENSE_KEY}\"}" || true)"
[ -z "${RESP}" ] && error "Could not reach license server at ${LICENSE_URL}"

TOKEN="$(printf '%s' "${RESP}"  | grep -oE '"download_token":"[^"]+"' | head -1 | cut -d'"' -f4)"
VERSION="$(printf '%s' "${RESP}" | grep -oE '"version":"[^"]+"'       | head -1 | cut -d'"' -f4)"
WANT_SHA="$(printf '%s' "${RESP}" | grep -oE '"sha256":"[^"]+"'        | head -1 | cut -d'"' -f4)"

if [ -z "${TOKEN}" ] || [ -z "${VERSION}" ]; then
  echo -e "${RED}  server response:${RESET}"; printf '%s\n' "${RESP}" | head -3
  error "License rejected or unexpected server response (check your key)."
fi
success "License OK — version ${VERSION}"

# ── Download + verify ────────────────────────────────────────────────────────
info "Downloading…"
curl -fsSL "${LICENSE_URL}/v1/install/download?token=${TOKEN}" -o "${TARGET}/release.tar.gz"
GOT_SHA="$(sha256sum "${TARGET}/release.tar.gz" | cut -d' ' -f1)"
if [ -n "${WANT_SHA}" ] && [ "${GOT_SHA}" != "${WANT_SHA}" ]; then
  rm -f "${TARGET}/release.tar.gz"
  error "SHA256 mismatch — refusing to install (expected ${WANT_SHA}, got ${GOT_SHA})"
fi
success "Verified (sha256 ${GOT_SHA:0:12}…)"

# ── Extract ──────────────────────────────────────────────────────────────────
tar -xzf "${TARGET}/release.tar.gz" -C "${TARGET}"
rm -f "${TARGET}/release.tar.gz"
chmod +x "${TARGET}/start" "${TARGET}/update" 2>/dev/null || true

# ── Seed .env (license filled; user adds wallet + RPC) ────────────────────────
if [ ! -f "${TARGET}/.env" ]; then
  cp "${TARGET}/.env.template" "${TARGET}/.env" 2>/dev/null || true
  # write the license key in so ./update works and /start can activate
  if grep -qE '^LICENSE_KEY=' "${TARGET}/.env" 2>/dev/null; then
    sed -i.bak "s|^LICENSE_KEY=.*|LICENSE_KEY=${LICENSE_KEY}|" "${TARGET}/.env" && rm -f "${TARGET}/.env.bak"
  else
    echo "LICENSE_KEY=${LICENSE_KEY}" >> "${TARGET}/.env"
  fi
fi
success "Installed v${VERSION}"

# ── Next steps ───────────────────────────────────────────────────────────────
echo -e ""
echo -e "${BOLD}${GREEN}  ✓ Done.${RESET}  Next:"
echo -e ""
echo -e "    ${BOLD}cd ${DIR_NAME}${RESET}"
echo -e "    ${DIM}# edit .env — set PRIVATE_KEY (your wallet) and RPC endpoints${RESET}"
echo -e "    ${BOLD}nano .env${RESET}"
echo -e "    ${BOLD}./start${RESET}        ${DIM}# first run pins the right Node, then opens the menu${RESET}"
echo -e ""
echo -e "  ${DIM}In the bot:${RESET}  ${BOLD}/start ${LICENSE_KEY}${RESET}  ${DIM}→ activate · then /deploy in Wallet Manager${RESET}"
echo -e "  ${DIM}Update later:${RESET}  ${BOLD}./update${RESET}"
echo -e ""
