#!/usr/bin/env bash
#
# Install the haunt CLI.
#
# Usage: curl -fsSL haunts.sh | sh
#
set -euo pipefail

REPO="trebl-labs/haunts"
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/bin}"

log() { echo "==> $*"; }

# Detect OS and arch
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

case "$ARCH" in
  x86_64)  ARCH="x86_64" ;;
  aarch64|arm64) ARCH="aarch64" ;;
  *) echo "error: unsupported architecture: $ARCH"; exit 1 ;;
esac

case "$OS" in
  linux)  TARGET="${ARCH}-unknown-linux-gnu" ;;
  darwin) TARGET="${ARCH}-apple-darwin" ;;
  *) echo "error: unsupported OS: $OS"; exit 1 ;;
esac

# Get latest release tag
log "fetching latest release"
LATEST=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null | grep '"tag_name"' | head -1 | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/' || echo "")

if [ -z "$LATEST" ]; then
  # No releases yet — build from source
  log "no releases found, installing from source"

  if ! command -v cargo &>/dev/null; then
    log "installing Rust"
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source "$HOME/.cargo/env"
  fi

  TMP=$(mktemp -d)
  log "cloning and building"
  git clone --depth 1 "https://github.com/${REPO}.git" "$TMP/haunts"
  cd "$TMP/haunts"
  cargo build --release --bin haunt

  mkdir -p "$INSTALL_DIR"
  cp target/release/haunt "$INSTALL_DIR/haunt"
  chmod +x "$INSTALL_DIR/haunt"
  rm -rf "$TMP"
else
  # Download pre-built binary from release
  DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${LATEST}/haunt-${TARGET}"
  log "downloading haunt ${LATEST} for ${TARGET}"

  mkdir -p "$INSTALL_DIR"
  curl -fsSL "$DOWNLOAD_URL" -o "$INSTALL_DIR/haunt"
  chmod +x "$INSTALL_DIR/haunt"
fi

# Check PATH
if ! echo "$PATH" | grep -q "$INSTALL_DIR"; then
  log "add to your PATH:"
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
  echo ""
fi

log "installed: $("$INSTALL_DIR/haunt" --help | head -1)"
echo ""
echo "  haunt auth --url https://haunts.dev --api-key YOUR_API_KEY"
echo "  haunt create my-vm"
echo "  haunt exec 'echo hello'"
echo ""
