#!/bin/sh
# eigenify CLI installer  -  curl -fsSL https://cli.eigenify.com/install.sh | sh
#
# Detects your OS/arch, downloads the matching standalone binary from the release CDN, VERIFIES its
# SHA-256 against the release manifest, installs it to ~/.eigenify/bin, and adds it to your PATH.
# No Bun or Node required. POSIX sh (sh/dash/bash/zsh). Publish side: deployment/runbooks/EIGENIFY-CLI-PUBLISH.md.
#
#   EIGENIFY_VERSION=0.1.2-alpha.0    pin a version (default: latest)
#   EIGENIFY_INSTALL_DIR=/usr/local/bin   install location (default: ~/.eigenify/bin)
#   EIGENIFY_INSTALL_BASE=https://...     override the release CDN
#   --dry-run                         print the plan, download/install nothing

set -eu

INSTALL_BASE="${EIGENIFY_INSTALL_BASE:-${EIGENIFY_BASE_URL:-https://cli.eigenify.com}}"
BIN_DIR="${EIGENIFY_INSTALL_DIR:-$HOME/.eigenify/bin}"
REQUESTED="${EIGENIFY_VERSION:-latest}"
DRY_RUN=0
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
TMP_DIR=""

cleanup() { [ -n "$TMP_DIR" ] && rm -rf "$TMP_DIR" 2>/dev/null || true; }
trap cleanup EXIT INT TERM
die() { printf 'eigenify-install: %s\n' "$1" >&2; exit 1; }

if command -v curl >/dev/null 2>&1; then
  DL() { curl -fsSL "$1"; }; DL_OUT() { curl -fsSL -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
  DL() { wget -qO - "$1"; }; DL_OUT() { wget -qO "$2" "$1"; }
else
  die "curl or wget is required but neither is installed"
fi

# ----- detect platform (matches the release layout) -------------------------
case "$(uname -s)" in
  Darwin) os="darwin" ;;
  Linux)  os="linux" ;;
  MINGW*|MSYS*|CYGWIN*) die "Windows is not supported by this installer; use 'bun add @eigenify/harness' or WSL" ;;
  *) die "unsupported OS: $(uname -s)" ;;
esac
case "$(uname -m)" in
  x86_64|amd64) arch="x64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) die "unsupported architecture: $(uname -m)" ;;
esac
# Rosetta 2: an x64 shell on Apple Silicon takes the native arm64 binary.
if [ "$os" = "darwin" ] && [ "$arch" = "x64" ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
  arch="arm64"
fi
# musl (Alpine etc.) gets a musl-linked build.
if [ "$os" = "linux" ] && { [ -f /lib/libc.musl-x86_64.so.1 ] || [ -f /lib/libc.musl-aarch64.so.1 ] || (ldd /bin/ls 2>&1 | grep -qi musl); }; then
  platform="linux-${arch}-musl"
else
  platform="${os}-${arch}"
fi

# ----- resolve version ------------------------------------------------------
if [ "$REQUESTED" = "latest" ]; then
  version="$(DL "$INSTALL_BASE/latest" | tr -d '[:space:]')"
else
  version="$REQUESTED"
fi
case "$version" in
  [0-9]*.[0-9]*.[0-9]*) : ;;
  *) die "could not resolve a valid version from $INSTALL_BASE/latest (got '$version'); the CDN may be unreachable" ;;
esac

printf 'eigenify installer\n  version : %s\n  platform: %s\n  source  : %s\n  install : %s/eigenify\n' \
  "$version" "$platform" "$INSTALL_BASE" "$BIN_DIR"
if [ "$DRY_RUN" = "1" ]; then
  printf '(dry-run) would download %s/%s/%s/eigenify, verify its sha256, and install it.\n' "$INSTALL_BASE" "$version" "$platform"
  exit 0
fi

# ----- fetch manifest + expected checksum -----------------------------------
TMP_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t eigenify)"
manifest="$TMP_DIR/manifest.json"
DL_OUT "$INSTALL_BASE/$version/manifest.json" "$manifest" || die "failed to fetch the $version manifest"
if command -v jq >/dev/null 2>&1; then
  expected="$(jq -r --arg p "$platform" '.platforms[$p].checksum // empty' "$manifest")"
else
  expected="$(tr -d '\n\r\t' < "$manifest" | sed 's/  */ /g' \
    | grep -oE "\"$platform\"[^}]*\"checksum\"[[:space:]]*:[[:space:]]*\"[a-f0-9]{64}\"" \
    | grep -oE '[a-f0-9]{64}' | head -1)"
fi
case "$expected" in
  ????????????????????????????????????????????????????????????????) : ;;
  *) die "no build for platform '$platform' in the $version manifest" ;;
esac

# ----- download + verify ----------------------------------------------------
bin="$TMP_DIR/eigenify"
DL_OUT "$INSTALL_BASE/$version/$platform/eigenify" "$bin" || die "binary download failed"
if command -v sha256sum >/dev/null 2>&1; then
  actual="$(sha256sum "$bin" | cut -d' ' -f1)"
elif command -v shasum >/dev/null 2>&1; then
  actual="$(shasum -a 256 "$bin" | cut -d' ' -f1)"
else
  die "no sha256 tool (sha256sum/shasum) to verify the download"
fi
[ "$actual" = "$expected" ] || die "checksum mismatch (expected $expected, got $actual) - refusing to install"

# ----- install + PATH -------------------------------------------------------
mkdir -p "$BIN_DIR"
install -m 0755 "$bin" "$BIN_DIR/eigenify" 2>/dev/null || { cp "$bin" "$BIN_DIR/eigenify"; chmod 0755 "$BIN_DIR/eigenify"; }

added_path=""
case ":$PATH:" in
  *":$BIN_DIR:"*) : ;;
  *)
    line="export PATH=\"$BIN_DIR:\$PATH\""
    for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.profile"; do
      [ -e "$rc" ] || continue
      grep -qsF "$BIN_DIR" "$rc" 2>/dev/null && continue
      printf '\n# eigenify CLI\n%s\n' "$line" >> "$rc" && added_path="$rc"
    done
    [ -z "$added_path" ] && { printf '\n# eigenify CLI\n%s\n' "$line" >> "$HOME/.profile"; added_path="$HOME/.profile"; }
    ;;
esac

printf '\neigenify %s installed to %s/eigenify\n' "$version" "$BIN_DIR"
[ -n "$added_path" ] && printf 'Added %s to PATH in %s - restart your shell or run:  export PATH="%s:$PATH"\n' "$BIN_DIR" "$added_path" "$BIN_DIR"
printf 'Get started:\n  eigenify --help\n  eigenify chat\nUpgrade later:  eigenify upgrade\n\n'
