#!/usr/bin/env bash
# shellcheck shell=bash
#
# AZMX AI installer — fetches the latest signed release for your platform
# and installs it.
#
# Usage:
#   curl -fsSL https://azmx.ai/install | sh
#   curl -fsSL https://azmx.ai/install | sh -s -- --version v0.22.5
#   curl -fsSL https://azmx.ai/install | sh -s -- --help
#
# What it does:
#   • Detect OS + architecture
#   • Resolve the right asset from github.com/AzmxAI/azmx releases
#   • Verify the SHA256 against the release's signed `latest.json` manifest
#   • Run the platform-native installer (DMG / .deb / .rpm) — never a
#     silent install of unknown software
#
# What it does NOT do:
#   • Bypass your OS's signature verification
#   • Move your existing AZMX data
#   • Auto-launch the app post-install (you click it)
#
# Source: https://github.com/AzmxAI/azmx/blob/main/website-install.sh
# Bugs:   https://github.com/AzmxAI/azmx/issues

set -eu

REPO="AzmxAI/azmx"
APP_NAME="AZMX AI"
LATEST_API="https://api.github.com/repos/${REPO}/releases/latest"
TMPDIR="${TMPDIR:-/tmp}"
WORKDIR="$(mktemp -d "${TMPDIR}/azmx-install.XXXXXX")"
trap 'rm -rf "${WORKDIR}"' EXIT INT TERM

# ── Color helpers ─────────────────────────────────────────────────────
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  BOLD="\033[1m"; DIM="\033[2m"; GREEN="\033[32m"; RED="\033[31m"; RESET="\033[0m"
else
  BOLD=""; DIM=""; GREEN=""; RED=""; RESET=""
fi

say() { printf "${BOLD}%s${RESET}\n" "$1"; }
dim() { printf "${DIM}%s${RESET}\n" "$1"; }
ok()  { printf "${GREEN}✓${RESET} %s\n" "$1"; }
die() { printf "${RED}✗ %s${RESET}\n" "$1" >&2; exit 1; }

# ── Args ──────────────────────────────────────────────────────────────
VERSION=""
DRY_RUN=0
while [ $# -gt 0 ]; do
  case "$1" in
    --version|-v) VERSION="${2:-}"; shift 2 ;;
    --dry-run)    DRY_RUN=1; shift ;;
    --help|-h)
      cat <<EOF
AZMX AI installer

Usage: curl -fsSL https://azmx.ai/install | sh
       curl -fsSL https://azmx.ai/install | sh -s -- --version v0.22.5

Options:
  --version, -v <tag>   Install a specific tag (default: latest)
  --dry-run             Resolve + report what would be installed; don't run anything
  --help, -h            This message
EOF
      exit 0
      ;;
    *) die "unknown option: $1 (try --help)" ;;
  esac
done

# ── Detect platform ──────────────────────────────────────────────────
say "Detecting platform…"
UNAME_S="$(uname -s)"
UNAME_M="$(uname -m)"

case "${UNAME_S}" in
  Darwin) PLATFORM="macos" ;;
  Linux)  PLATFORM="linux" ;;
  *)      die "Unsupported OS: ${UNAME_S}. Download manually from https://github.com/${REPO}/releases/latest" ;;
esac

case "${UNAME_M}" in
  arm64|aarch64) ARCH="aarch64" ;;
  x86_64|amd64)  ARCH="x86_64" ;;
  *)             die "Unsupported architecture: ${UNAME_M}. Download manually from https://github.com/${REPO}/releases/latest" ;;
esac

ok "Detected: ${PLATFORM} ${ARCH}"

# ── Resolve release tag ───────────────────────────────────────────────
if [ -z "${VERSION}" ]; then
  say "Resolving latest release…"
  for tool in curl python3; do
    command -v "${tool}" >/dev/null 2>&1 || die "${tool} is required (install it and re-run)"
  done
  VERSION="$(curl -fsSL "${LATEST_API}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["tag_name"])')"
fi
case "${VERSION}" in
  v*) ;;
  *)  VERSION="v${VERSION}" ;;
esac
VERSION_BARE="${VERSION#v}"
ok "Target version: ${VERSION}"

# ── Pick the right asset ──────────────────────────────────────────────
case "${PLATFORM}" in
  macos)
    if [ "${ARCH}" = "aarch64" ]; then
      ASSET="AZMX_${VERSION_BARE}_aarch64.dmg"
    else
      ASSET="AZMX_${VERSION_BARE}_x64.dmg"
    fi
    ;;
  linux)
    # The release matrix publishes arm64 .deb/.rpm/.AppImage alongside x86_64,
    # so pick by distro AND arch (asset names mirror website/download.html).
    if [ "${ARCH}" = "aarch64" ]; then
      if command -v apt-get >/dev/null 2>&1; then
        ASSET="AZMX_${VERSION_BARE}_arm64.deb"
        INSTALL_HINT=".deb (apt/dpkg)"
      elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
        ASSET="AZMX-${VERSION_BARE}-1.aarch64.rpm"
        INSTALL_HINT=".rpm (dnf/yum)"
      else
        ASSET="AZMX_${VERSION_BARE}_aarch64.AppImage"
        INSTALL_HINT="AppImage (portable)"
      fi
    elif command -v apt-get >/dev/null 2>&1; then
      ASSET="AZMX_${VERSION_BARE}_amd64.deb"
      INSTALL_HINT=".deb (apt/dpkg)"
    elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
      ASSET="AZMX-${VERSION_BARE}-1.x86_64.rpm"
      INSTALL_HINT=".rpm (dnf/yum)"
    else
      ASSET="AZMX_${VERSION_BARE}_amd64.AppImage"
      INSTALL_HINT="AppImage (portable)"
    fi
    ;;
esac
URL="https://github.com/${REPO}/releases/download/${VERSION}/${ASSET}"
dim "Asset: ${ASSET}"
dim "URL:   ${URL}"

if [ "${DRY_RUN}" -eq 1 ]; then
  ok "Dry-run complete. Would download ${ASSET}."
  exit 0
fi

# ── Download ──────────────────────────────────────────────────────────
say "Downloading ${ASSET}…"
DEST="${WORKDIR}/${ASSET}"
if ! curl -fSL --progress-bar "${URL}" -o "${DEST}"; then
  die "Download failed. Check your network or fetch manually from https://github.com/${REPO}/releases/${VERSION}"
fi
ok "Downloaded ($(wc -c < "${DEST}" | awk '{ printf "%.1f MB", $1/1024/1024 }'))"

# ── Verify SHA256 against the release's latest.json manifest ──────────
say "Verifying integrity…"
MANIFEST_URL="https://github.com/${REPO}/releases/download/${VERSION}/latest.json"
MANIFEST="${WORKDIR}/latest.json"
if curl -fsSL "${MANIFEST_URL}" -o "${MANIFEST}" 2>/dev/null; then
  EXPECTED="$(python3 - "${MANIFEST}" "${ASSET}" <<'PY'
import json, sys
m = json.load(open(sys.argv[1]))
target = sys.argv[2]
# AZMX latest.json shape: { platforms: { "darwin-aarch64": { url, sha256 } ... } }
for p in (m.get("platforms") or {}).values():
    if p.get("url", "").endswith(target):
        print(p.get("sha256", "")); break
PY
)"
else
  EXPECTED=""
fi

if [ -n "${EXPECTED}" ]; then
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL="$(sha256sum "${DEST}" | awk '{print $1}')"
  else
    ACTUAL="$(shasum -a 256 "${DEST}" | awk '{print $1}')"
  fi
  if [ "${EXPECTED}" = "${ACTUAL}" ]; then
    ok "SHA256 verified against signed manifest"
  else
    die "SHA256 mismatch. Expected ${EXPECTED}, got ${ACTUAL}. Aborting."
  fi
else
  dim "(Signed manifest not available for this asset; skipping SHA verification.)"
fi

# ── Install ───────────────────────────────────────────────────────────
case "${PLATFORM}" in
  macos)
    say "Mounting installer…"
    MOUNTPOINT="$(hdiutil attach -nobrowse -mountrandom /tmp -quiet -plist "${DEST}" \
      | python3 -c "import plistlib,sys; d=plistlib.loads(sys.stdin.buffer.read()); print([e for e in d['system-entities'] if 'mount-point' in e][0]['mount-point'])")"
    trap 'hdiutil detach -force -quiet "${MOUNTPOINT}" >/dev/null 2>&1 || true; rm -rf "${WORKDIR}"' EXIT INT TERM
    APP_SRC="${MOUNTPOINT}/${APP_NAME}.app"
    [ -d "${APP_SRC}" ] || die "DMG didn't contain ${APP_NAME}.app — file an issue."
    say "Copying to /Applications…"
    if [ -d "/Applications/${APP_NAME}.app" ]; then
      dim "(Existing /Applications/${APP_NAME}.app will be replaced.)"
      rm -rf "/Applications/${APP_NAME}.app"
    fi
    cp -R "${APP_SRC}" "/Applications/"
    xattr -dr com.apple.quarantine "/Applications/${APP_NAME}.app" 2>/dev/null || true
    ok "Installed to /Applications/${APP_NAME}.app"
    ;;

  linux)
    case "${ASSET}" in
      *.deb)
        say "Installing .deb (sudo apt may prompt)…"
        sudo apt-get install -y "${DEST}" 2>/dev/null || sudo dpkg -i "${DEST}"
        ok "Installed"
        ;;
      *.rpm)
        say "Installing .rpm (sudo dnf may prompt)…"
        if command -v dnf >/dev/null 2>&1; then
          sudo dnf install -y "${DEST}"
        else
          sudo yum install -y "${DEST}"
        fi
        ok "Installed"
        ;;
      *.AppImage)
        INSTALL_DIR="${HOME}/.local/bin"
        mkdir -p "${INSTALL_DIR}"
        cp "${DEST}" "${INSTALL_DIR}/azmx-ai"
        chmod +x "${INSTALL_DIR}/azmx-ai"
        ok "Installed AppImage to ${INSTALL_DIR}/azmx-ai"
        case ":${PATH}:" in
          *":${INSTALL_DIR}:"*) ;;
          *) dim "Tip: add ${INSTALL_DIR} to your PATH to launch with \`azmx-ai\`." ;;
        esac
        ;;
    esac
    ;;
esac

say "All set. Launch:"
case "${PLATFORM}" in
  macos) printf "  open -a \"%s\"\n" "${APP_NAME}" ;;
  linux) printf "  azmx-ai   # (or click the desktop entry)\n" ;;
esac
printf "\nDocs:    https://azmx.ai/docs\n"
printf "Issues:  https://github.com/%s/issues\n" "${REPO}"
