#!/bin/sh
# Aion installer — installs the latest Aion CLI for macOS or Linux.
#
#   curl -fsSL https://aionagent.app/install.sh | sh
#
# It always fetches the LATEST GitHub release (via the /releases/latest/download
# redirect), so re-running it upgrades you in place.
#
# Environment overrides:
#   AION_VERSION=v1.2.3      install a specific tag instead of latest
#   AION_INSTALL_DIR=/path   install location (default: /usr/local/bin or ~/.local/bin)
#
# Release asset convention this expects (publish these on GitHub Releases):
#   aion-darwin-arm64.tar.gz   aion-darwin-x64.tar.gz
#   aion-linux-arm64.tar.gz    aion-linux-x64.tar.gz
#   checksums.txt              (optional; "<sha256>  <asset>" per line)
# Each archive must contain an executable named `aion`.

set -eu

REPO="trimdev/aion-cli"
BIN="aion"
RELEASES="https://github.com/${REPO}/releases"

# --- pretty output (only colorize a real terminal) -------------------------
if [ -t 1 ]; then C='\033[36m'; G='\033[32m'; Y='\033[33m'; R='\033[31m'; Z='\033[0m'; else C=''; G=''; Y=''; R=''; Z=''; fi
say() { printf "${C}▸${Z} %s\n" "$1"; }
ok()  { printf "${G}✓${Z} %s\n" "$1"; }
warn(){ printf "${Y}!${Z} %s\n" "$1"; }
die() { printf "${R}✗${Z} %s\n" "$1" >&2; exit 1; }

# --- detect platform -------------------------------------------------------
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$OS" in
  Darwin) OS="darwin" ;;
  Linux)  OS="linux" ;;
  *) die "Unsupported OS: $OS. Download a build from ${RELEASES}" ;;
esac
case "$ARCH" in
  arm64|aarch64)  ARCH="arm64"; ARCH_ALT="arm64|aarch64" ;;
  x86_64|amd64)   ARCH="x64";   ARCH_ALT="x64|amd64|x86_64" ;;
  *) die "Unsupported architecture: $ARCH. Download a build from ${RELEASES}" ;;
esac
ASSET="${BIN}-${OS}-${ARCH}.tar.gz"

# --- downloader (curl or wget) ---------------------------------------------
if command -v curl >/dev/null 2>&1; then
  dl() { curl -fsSL "$1" -o "$2"; }
  fetch() { curl -fsSL "$1"; }
elif command -v wget >/dev/null 2>&1; then
  dl() { wget -qO "$2" "$1"; }
  fetch() { wget -qO- "$1"; }
else
  die "Need curl or wget to download Aion."
fi

VERSION="${AION_VERSION:-latest}"
if [ "$VERSION" = "latest" ]; then
  BASE="${RELEASES}/latest/download"
else
  BASE="${RELEASES}/download/${VERSION}"
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

say "Installing aion · ${OS}/${ARCH} · ${VERSION}"

# --- download (with an API fallback for versioned asset names) -------------
say "Fetching the latest release"
if ! dl "${BASE}/${ASSET}" "${TMP}/${ASSET}" 2>/dev/null; then
  # Fall back to the GitHub API: find any matching .tar.gz on the latest release.
  api="https://api.github.com/repos/${REPO}/releases/latest"
  url="$(fetch "$api" 2>/dev/null \
    | grep -o '"browser_download_url": *"[^"]*"' \
    | sed 's/.*"\(https[^"]*\)"/\1/' \
    | grep -iE "(${OS})" \
    | grep -iE "(${ARCH_ALT})" \
    | grep -iE '\.tar\.gz$|\.tgz$' \
    | head -n1 || true)"
  [ -n "$url" ] || die "No build for ${OS}/${ARCH} in the latest release. See ${RELEASES}"
  dl "$url" "${TMP}/${ASSET}" || die "Download failed: $url"
fi

# --- verify checksum (best effort) -----------------------------------------
if dl "${BASE}/checksums.txt" "${TMP}/checksums.txt" 2>/dev/null; then
  sumtool=""
  if command -v sha256sum >/dev/null 2>&1; then sumtool="sha256sum"
  elif command -v shasum >/dev/null 2>&1; then sumtool="shasum -a 256"; fi
  expected="$(grep " ${ASSET}\$" "${TMP}/checksums.txt" 2>/dev/null | awk '{print $1}' || true)"
  if [ -n "$sumtool" ] && [ -n "$expected" ]; then
    actual="$(cd "$TMP" && $sumtool "$ASSET" | awk '{print $1}')"
    [ "$expected" = "$actual" ] || die "Checksum mismatch — refusing to install."
    ok "Checksum verified"
  else
    warn "Skipping checksum (no tool or entry found)"
  fi
fi

# --- extract ---------------------------------------------------------------
say "Extracting"
tar -xzf "${TMP}/${ASSET}" -C "$TMP" || die "Could not extract ${ASSET}"
binpath="${TMP}/${BIN}"
[ -f "$binpath" ] || binpath="$(find "$TMP" -type f -name "$BIN" 2>/dev/null | head -n1)"
[ -n "$binpath" ] && [ -f "$binpath" ] || die "'${BIN}' executable not found inside the archive."
chmod +x "$binpath"

# --- choose a writable install dir (no sudo prompts) -----------------------
if [ -n "${AION_INSTALL_DIR:-}" ]; then
  DIR="$AION_INSTALL_DIR"
elif [ -w /usr/local/bin ] 2>/dev/null; then
  DIR="/usr/local/bin"
else
  DIR="$HOME/.local/bin"
fi
mkdir -p "$DIR" || die "Cannot create $DIR"
mv "$binpath" "${DIR}/${BIN}" || die "Cannot write to ${DIR}. Re-run with AION_INSTALL_DIR=\$HOME/.local/bin"
ok "Installed → ${DIR}/${BIN}"

# --- PATH hint + version + next steps --------------------------------------
case ":$PATH:" in
  *":$DIR:"*) ;;
  *) warn "Add ${DIR} to your PATH:  export PATH=\"${DIR}:\$PATH\"" ;;
esac
if v="$("${DIR}/${BIN}" --version 2>/dev/null | head -n1)"; then ok "$v"; fi

printf "\n  Next:  ${C}aion login${Z}   then give it a mission.\n  Docs:  https://www.aionagent.app\n\n"
