#!/usr/bin/env bash
# raccha.ai CLI installer — https://raccha.ai/install.sh
#
# This script is a plain static file, meant to be read before it is run:
#     curl -fsSL https://raccha.ai/install.sh -o install.sh && less install.sh
#     bash install.sh
# or piped directly if you already trust it:
#     curl -fsSL https://raccha.ai/install.sh | bash
#
# Usage:
#   install.sh [--dry-run]
#   install.sh uninstall
#   install.sh -h | --help

set -euo pipefail

BASE_URL="${RACCHA_INSTALL_BASE_URL:-https://raccha.ai}"
VERSION="0.1.0"
CLI_NAME="raccha-${VERSION}"
DRY_RUN=0
ASSUME_YES=0

usage() {
  cat <<'EOF'
raccha.ai CLI installer

Usage:
  install.sh [--dry-run]
  install.sh uninstall
  install.sh -h | --help

Options:
  --dry-run     Print what would happen (platform detected, URLs used,
                install path) without downloading, installing, or
                recording consent.
  uninstall     Remove the installed raccha binary and config directory.
  -h, --help    Show this help, including automation flags and platform support.
EOF
}

usage_full() {
  usage
  cat <<'EOF'

Automation:
  -y            Skip the interactive consent prompt for CI/scripted
                installs. Consent is still recorded server-side as
                non-interactive.

Platform support:
  linux-x86_64  supported
  macOS         planned
  Windows       planned (use WSL in the meantime)
EOF
}

uninstall() {
  local installed_path
  installed_path="$(command -v raccha || true)"
  if [ -n "$installed_path" ] && [ -f "$installed_path" ]; then
    rm -f "$installed_path"
    echo "Removed ${installed_path}"
  else
    echo "raccha binary not found on PATH."
  fi

  local config_dir="${HOME}/.config/raccha"
  if [ -d "$config_dir" ]; then
    rm -rf "$config_dir"
    echo "Removed config directory ${config_dir}"
  fi
}

for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    -y) ASSUME_YES=1 ;;
    uninstall) uninstall; exit 0 ;;
    -h|--help) usage_full; exit 0 ;;
    *)
      echo "raccha.ai installer: unknown option: $arg" >&2
      usage
      exit 1
      ;;
  esac
done

# ---- platform detection ----

detect_os() {
  case "$(uname -s)" in
    Linux) echo "linux" ;;
    Darwin) echo "darwin" ;;
    *) echo "unknown" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64) echo "x86_64" ;;
    aarch64|arm64) echo "aarch64" ;;
    *) echo "unknown" ;;
  esac
}

OS="$(detect_os)"
ARCH="$(detect_arch)"
PLATFORM="${OS}-${ARCH}"

case "$PLATFORM" in
  linux-x86_64)
    ASSET="${CLI_NAME}-x86_64-unknown-linux-gnu"
    ;;
  *)
    echo "raccha.ai installer: no pre-built binary for platform '${PLATFORM}' yet." >&2
    echo "Supported platforms: Linux x86_64 (now); macOS and Windows are planned." >&2
    echo "In the meantime: SDKs for Python/TypeScript/Java are available at" >&2
    echo "https://raccha.ai/connect.html regardless of platform." >&2
    exit 1
    ;;
esac

DOWNLOAD_URL="${BASE_URL}/downloads/${ASSET}"
INSTALL_DIR="${HOME}/.local/bin"
if [ -w "/usr/local/bin" ] 2>/dev/null; then
  INSTALL_DIR="/usr/local/bin"
fi
INSTALL_PATH="${INSTALL_DIR}/raccha"
CONSENT_URL="${BASE_URL}/install/consent"

# ---- dry run: print and stop, nothing else runs ----

if [ "$DRY_RUN" -eq 1 ]; then
  cat <<EOF
[dry-run] raccha.ai installer — nothing below actually happens.

  Detected platform : ${PLATFORM}
  Would download     : ${DOWNLOAD_URL}
  Would install to   : ${INSTALL_PATH}
  Would verify       : ${DOWNLOAD_URL}.sha256 (if published)
  Would record consent at: ${CONSENT_URL}
    (mode=$([ "$ASSUME_YES" -eq 1 ] && echo non-interactive || echo interactive))

No network calls were made, no files were written, no consent was recorded.
EOF
  exit 0
fi

# ---- consent: shown and server-recorded before anything installs ----

echo "raccha.ai installer"
echo "  Platform detected : ${PLATFORM}"
echo "  Will download     : ${DOWNLOAD_URL}"
echo "  Will install to   : ${INSTALL_PATH}"
echo

if [ "$ASSUME_YES" -ne 1 ]; then
  printf 'Proceed with installing the raccha CLI as shown above? [y/N] '
  read -r REPLY
  case "$REPLY" in
    y|Y|yes|YES) : ;;
    *) echo "Aborted — nothing was installed." >&2; exit 1 ;;
  esac
fi

CONSENT_MODE="interactive"
if [ "$ASSUME_YES" -eq 1 ]; then
  CONSENT_MODE="non-interactive"
fi

if ! curl -fsSL -X POST "$CONSENT_URL" \
  -H "Content-Type: application/json" \
  -d "{\"mode\":\"${CONSENT_MODE}\",\"platform\":\"${PLATFORM}\",\"version\":\"${VERSION}\"}" \
  -o /dev/null; then
  echo "raccha.ai installer: failed to record consent at ${CONSENT_URL} — aborting." >&2
  echo "(Install does not proceed without a recorded consent event.)" >&2
  exit 1
fi

# ---- download ----

TMP_FILE="$(mktemp)"
trap 'rm -f "$TMP_FILE" "$TMP_FILE.sha256" "$TMP_FILE.asc"' EXIT

echo "Downloading ${DOWNLOAD_URL} ..."
curl -fsSL "$DOWNLOAD_URL" -o "$TMP_FILE"

SIZE="$(wc -c < "$TMP_FILE" | tr -d ' ')"
if [ "${SIZE:-0}" -eq 0 ]; then
  echo "raccha.ai installer: downloaded file is empty — aborting install." >&2
  exit 1
fi

# ---- checksum / signature verification (best-effort) ----

verify_checksum() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum --check --status - <<<"$1  $TMP_FILE" 2>/dev/null
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 --check --status - <<<"$1  $TMP_FILE" 2>/dev/null
  else
    echo "Checksum file found but sha256sum/shasum unavailable; skipping verification." >&2
    return 0
  fi
}

if curl -fsSL "${DOWNLOAD_URL}.sha256" -o "$TMP_FILE.sha256" 2>/dev/null; then
  EXPECTED="$(awk '{print $1}' "$TMP_FILE.sha256")"
  if [ -n "$EXPECTED" ] && verify_checksum "$EXPECTED"; then
    echo "Checksum verified."
  else
    echo "raccha.ai installer: checksum verification failed — aborting." >&2
    exit 1
  fi
else
  echo "No .sha256 file published; skipping checksum verification."
fi

if curl -fsSL "${DOWNLOAD_URL}.asc" -o "$TMP_FILE.asc" 2>/dev/null; then
  if command -v gpg >/dev/null 2>&1; then
    if gpg --verify "$TMP_FILE.asc" "$TMP_FILE" >/dev/null 2>&1; then
      echo "Signature verified."
    else
      echo "raccha.ai installer: signature verification failed — aborting." >&2
      exit 1
    fi
  else
    echo "Signature file found but gpg unavailable; skipping signature verification."
  fi
else
  echo "No .asc file published; skipping signature verification."
fi

chmod +x "$TMP_FILE"

# ---- install onto PATH ----

mkdir -p "$INSTALL_DIR"
mv "$TMP_FILE" "$INSTALL_PATH"
trap - EXIT
chmod +x "$INSTALL_PATH"

echo "Installed raccha to ${INSTALL_PATH}"

case ":$PATH:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    echo
    echo "NOTE: ${INSTALL_DIR} is not on your PATH."
    echo "Add it, e.g.: export PATH=\"${INSTALL_DIR}:\$PATH\""
    ;;
esac

echo
echo "Run 'raccha --help' to get started."
echo ""
echo "To authenticate:"
echo "  - From a laptop with a browser: raccha auth login"
echo "  - From a server/container (headless): raccha auth device-login, then approve the code at https://raccha.ai/device.html"
