#!/usr/bin/env bash
# AsentumChain CLI installer — macOS / Linux.
#
# Usage:
#   curl -fsSL https://testnet.asentum.com/install | bash
#   curl -fsSL https://testnet.asentum.com/install/install.sh | bash
#
# Installs the `asentum` CLI (a single self-contained binary) to
# ~/.asentum/bin/asentum and adds that directory to your shell's PATH.
# No sudo needed. No Node.js, pnpm, or other dependencies required.
#
# Override the install root by setting ASENTUM_INSTALL_DIR.
# Skip the auto-quickstart by setting ASENTUM_SKIP_QUICKSTART=1.

# bash check — set -eu is POSIX but the rest of this script uses
# bashisms (printf %b colours, [[ ]] tests). /bin/sh on Debian/Ubuntu
# is dash; piping into it produces cryptic failures. Refuse upfront
# with an actionable error pointing at the bash one-liner.
if [ -z "${BASH_VERSION:-}" ]; then
  printf '\033[31merror:\033[0m this installer requires bash, not sh.\n' >&2
  printf '\n' >&2
  printf '       Re-run with bash:\n' >&2
  printf '\n' >&2
  printf '         \033[1mcurl -fsSL https://testnet.asentum.com/install | bash\033[0m\n' >&2
  printf '\n' >&2
  exit 1
fi

set -eu

INSTALL_BASE="${ASENTUM_INSTALL_BASE:-https://testnet.asentum.com/install}"
BIN_NAME="asentum"
MIN_BINARY_SIZE_BYTES=$((50 * 1024 * 1024))   # sanity check: 50 MB

# --- colors (respect NO_COLOR) ----------------------------------------------
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  G='\033[0;32m'; Y='\033[0;33m'; R='\033[0;31m'
  C='\033[0;36m'; B='\033[1m'; RST='\033[0m'
else
  G=''; Y=''; R=''; C=''; B=''; RST=''
fi

printf '\n'
printf '%b' "${B}${C}"
cat <<'BANNER'
  ┌──────────────────────────────────────────┐
  │  AsentumChain — one-command installer    │
  │  post-quantum L1 · JS-native · testnet   │
  └──────────────────────────────────────────┘
BANNER
printf '%b\n\n' "${RST}"

# --- detect platform + arch --------------------------------------------------
OS_RAW="$(uname -s 2>/dev/null || echo unknown)"
case "$OS_RAW" in
  Darwin) PLATFORM=darwin ;;
  Linux)  PLATFORM=linux  ;;
  *)
    printf '%berror:%b unsupported OS %s. See INSTALL.md for build-from-source.\n' "$R" "$RST" "$OS_RAW"
    exit 1 ;;
esac

ARCH_RAW="$(uname -m 2>/dev/null || echo unknown)"
case "$ARCH_RAW" in
  arm64|aarch64) ARCH=arm64 ;;
  x86_64|amd64)  ARCH=x64   ;;
  *)
    printf '%berror:%b unsupported arch %s.\n' "$R" "$RST" "$ARCH_RAW"
    exit 1 ;;
esac

TARGET="${BIN_NAME}-${PLATFORM}-${ARCH}"
URL="${INSTALL_BASE}/${TARGET}"

printf '  platform:  %b%s-%s%b\n'  "$B" "$PLATFORM" "$ARCH" "$RST"
printf '  source:    %s\n\n'  "$URL"

# --- install dir -------------------------------------------------------------
INSTALL_DIR="${ASENTUM_INSTALL_DIR:-$HOME/.asentum/bin}"
INSTALL_PATH="$INSTALL_DIR/$BIN_NAME"
mkdir -p "$INSTALL_DIR"

# --- download ----------------------------------------------------------------
printf '%b[1/4]%b downloading %s...\n' "$C" "$RST" "$TARGET"

TMP="$(mktemp "${TMPDIR:-/tmp}/asentum-install.XXXXXXXX")"
trap 'rm -f "$TMP"' EXIT INT TERM

if command -v curl >/dev/null 2>&1; then
  if ! curl -fsSL --progress-bar -o "$TMP" "$URL"; then
    printf '%berror:%b download failed (curl). Is the URL reachable?\n' "$R" "$RST"
    printf '       %s\n' "$URL"
    exit 1
  fi
elif command -v wget >/dev/null 2>&1; then
  if ! wget -q --show-progress -O "$TMP" "$URL"; then
    printf '%berror:%b download failed (wget).\n' "$R" "$RST"
    exit 1
  fi
else
  printf '%berror:%b neither curl nor wget is available. Install one and retry.\n' "$R" "$RST"
  exit 1
fi

SIZE="$(wc -c < "$TMP" | tr -d ' ')"
if [ "$SIZE" -lt "$MIN_BINARY_SIZE_BYTES" ]; then
  printf '%berror:%b downloaded file is only %s bytes — probably an HTTP error page.\n' "$R" "$RST" "$SIZE"
  printf '       first 300 bytes:\n       '
  head -c 300 "$TMP" 2>/dev/null || true
  printf '\n'
  exit 1
fi

HUMAN_SIZE="$(du -h "$TMP" 2>/dev/null | cut -f1 || echo "$SIZE bytes")"
printf '        %b✓%b downloaded (%s)\n' "$G" "$RST" "$HUMAN_SIZE"

# --- macOS: strip quarantine -------------------------------------------------
printf '%b[2/4]%b preparing binary...\n' "$C" "$RST"
chmod +x "$TMP"
if [ "$PLATFORM" = "darwin" ] && command -v xattr >/dev/null 2>&1; then
  xattr -d com.apple.quarantine "$TMP" 2>/dev/null || true
fi
printf '        %b✓%b executable, quarantine stripped\n' "$G" "$RST"

# --- install -----------------------------------------------------------------
printf '%b[3/5]%b installing to %s...\n' "$C" "$RST" "$INSTALL_PATH"
mv "$TMP" "$INSTALL_PATH"
trap - EXIT INT TERM
printf '        %b✓%b installed\n' "$G" "$RST"

# --- pre-configure the testnet RPC ------------------------------------------
# The installer lives at testnet.asentum.com/install, so point the freshly
# installed CLI at that same testnet's JSON-RPC by default. Users can change
# it any time with `asentum config set rpc <url>`.
printf '%b[4/5]%b configuring RPC endpoint...\n' "$C" "$RST"
RPC_URL="${INSTALL_BASE%/install*}"
if "$INSTALL_PATH" config set rpc "$RPC_URL" >/dev/null 2>&1; then
  printf '        %b✓%b rpcUrl → %s\n' "$G" "$RST" "$RPC_URL"
else
  printf '        %bwarning:%b could not pre-configure RPC. Run `asentum config set rpc %s` manually.\n' "$Y" "$RST" "$RPC_URL"
fi

# --- PATH setup --------------------------------------------------------------
printf '%b[5/5]%b configuring PATH...\n' "$C" "$RST"

# Pick a shell rc to patch. Prefer the shell in $SHELL; fall back to both
# zsh (macOS default) and bash so most users get covered in one pass.
RC_FILES=""
case "${SHELL:-}" in
  */zsh)  RC_FILES="$HOME/.zshrc" ;;
  */bash) RC_FILES="$HOME/.bashrc $HOME/.bash_profile" ;;
  *)      RC_FILES="$HOME/.zshrc $HOME/.bashrc $HOME/.bash_profile" ;;
esac

LINE="export PATH=\"$INSTALL_DIR:\$PATH\""
PATH_STATE="manual"
for RC in $RC_FILES; do
  # Only patch rc files that already exist OR are the primary for the
  # active shell. Avoid sprinkling new dotfiles into the user's home.
  if [ -f "$RC" ] || [ "$RC" = "$HOME/.zshrc" ] && [ "${SHELL:-}" = "/bin/zsh" ]; then
    if [ -f "$RC" ] && grep -qxF "$LINE" "$RC" 2>/dev/null; then
      printf '        %b✓%b PATH already configured in %s\n' "$G" "$RST" "$RC"
      PATH_STATE="exists"
      continue
    fi
    [ -f "$RC" ] || touch "$RC"
    {
      printf '\n# Added by the AsentumChain installer\n'
      printf '%s\n' "$LINE"
    } >> "$RC"
    printf '        %b✓%b added to %s\n' "$G" "$RST" "$RC"
    PATH_STATE="added"
  fi
done

# Also try to make this current shell useful, in case the user sources the script.
export PATH="$INSTALL_DIR:$PATH"

printf '\n'
printf '%b  ✓ AsentumChain CLI installed!%b\n\n' "${G}${B}" "$RST"

case "$PATH_STATE" in
  added)
    printf '  %bNext step:%b open a new terminal (or run `%bsource %s%b`)\n' \
           "$Y" "$RST" "$B" "${RC_FILES%% *}" "$RST"
    printf '             so the updated PATH takes effect, then run:\n\n'
    ;;
  manual)
    printf '  %bNote:%b add this line to your shell profile to use `asentum` directly:\n' "$Y" "$RST"
    printf '        %s\n\n' "$LINE"
    ;;
  *)
    printf '  Now try:\n\n'
    ;;
esac

printf '    %basentum quickstart%b       (create a wallet, fund it, show balance)\n' "$C" "$RST"
printf '    %basentum balance%b          (check any time)\n' "$C" "$RST"
printf '    %basentum chain%b            (look at the chain state)\n\n' "$C" "$RST"

printf '  Testnet explorer:  %b%s%b\n\n' "$C" "${INSTALL_BASE%/install*}" "$RST"

# --- auto-quickstart ---------------------------------------------------------
if [ -z "${ASENTUM_SKIP_QUICKSTART:-}" ] && [ -t 0 ] && [ -t 1 ]; then
  printf '  Run %basentum quickstart%b now? [Y/n] ' "$B" "$RST"
  read -r ANSWER
  case "$ANSWER" in
    ''|y|Y|yes|Yes)
      printf '\n'
      "$INSTALL_PATH" quickstart
      ;;
    *)
      printf '  Skipped. Run it yourself whenever: %basentum quickstart%b\n\n' "$B" "$RST"
      ;;
  esac
fi
