#!/usr/bin/env bash
# investibook CLI installer
#
# Usage (standalone):
#   curl -fsSL https://investibook-build.s3.amazonaws.com/install.sh | bash
#
# Usage (with automatic init):
#   curl -fsSL https://investibook-build.s3.amazonaws.com/install.sh | \
#     bash -s -- --api-host https://your-host --api-key ib_xxxx
#
# Supports: Linux x86_64, Linux ARM64, macOS ARM64 (Apple Silicon), macOS x86_64 (Intel)

set -euo pipefail

# ── Helpers ──────────────────────────────────────────────────────────────────

S3_BASE="https://investibook-build.s3.amazonaws.com"
INSTALL_DIR="/usr/local/bin"
BINARY="investibook"

err()  { echo "[investibook-install] ERROR: $*" >&2; exit 1; }
info() { echo "[investibook-install] $*"; }

# ── Parse optional flags ──────────────────────────────────────────────────────

API_HOST=""
API_KEY=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --api-host)  API_HOST="${2:-}"; shift 2 ;;
    --api-key)   API_KEY="${2:-}";  shift 2 ;;
    *) err "Unknown argument: $1" ;;
  esac
done

# ── Detect platform ───────────────────────────────────────────────────────────

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

case "$ARCH" in
  x86_64)         ARCH="amd64" ;;
  aarch64|arm64)  ARCH="arm64" ;;
  *) err "Unsupported architecture: $ARCH (supported: x86_64, aarch64/arm64)" ;;
esac

# ── Rosetta 2 detection ───────────────────────────────────────────────────────
# On Apple Silicon running x86_64 under Rosetta, uname -m returns x86_64.
# Detect this and prefer the native arm64 binary for better performance.
if [[ "$OS" == "darwin" && "$ARCH" == "amd64" ]]; then
  if [[ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" == "1" ]]; then
    info "Rosetta 2 detected — switching to native arm64 binary"
    ARCH="arm64"
  fi
fi

PLATFORM="${OS}-${ARCH}"

case "$PLATFORM" in
  linux-amd64|linux-arm64|darwin-amd64|darwin-arm64) ;;
  *) err "Unsupported platform: $PLATFORM (supported: linux-amd64, linux-arm64, darwin-amd64, darwin-arm64)" ;;
esac

# ── musl libc detection ───────────────────────────────────────────────────────
# All binaries are compiled with CGO_ENABLED=0 (fully static), so they run on
# both glibc and musl systems without a separate build variant.
if [[ "$OS" == "linux" ]]; then
  if [[ -f /lib/libc.musl-x86_64.so.1 ]] || [[ -f /lib/libc.musl-aarch64.so.1 ]] || \
     ldd /bin/ls 2>&1 | grep -q musl 2>/dev/null; then
    info "musl libc detected — statically-linked binary is fully compatible"
  fi
fi

info "Detected platform: $PLATFORM"

# ── Skip download if already installed ───────────────────────────────────────

if [[ -x "${INSTALL_DIR}/${BINARY}" ]]; then
  info "${BINARY} already installed at ${INSTALL_DIR}/${BINARY} — skipping download"
else

# ── Download ──────────────────────────────────────────────────────────────────

ARCHIVE_URL="${S3_BASE}/latest/${BINARY}-${PLATFORM}.tar.gz"
CHECKSUM_URL="${S3_BASE}/latest/${BINARY}-${PLATFORM}.sha256"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

info "Downloading $ARCHIVE_URL ..."
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$ARCHIVE_URL" -o "${TMP_DIR}/${BINARY}.tar.gz"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "${TMP_DIR}/${BINARY}.tar.gz" "$ARCHIVE_URL"
else
  err "Neither curl nor wget found. Please install one and retry."
fi

# ── Verify checksum ───────────────────────────────────────────────────────────

info "Verifying checksum..."
EXPECTED=""
if command -v curl >/dev/null 2>&1; then
  EXPECTED=$(curl -fsSL "$CHECKSUM_URL" 2>/dev/null | tr -d '[:space:]') || true
elif command -v wget >/dev/null 2>&1; then
  EXPECTED=$(wget -qO- "$CHECKSUM_URL" 2>/dev/null | tr -d '[:space:]') || true
fi

if [[ -n "$EXPECTED" ]]; then
  ACTUAL=""
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL=$(sha256sum "${TMP_DIR}/${BINARY}.tar.gz" | awk '{print $1}')
  elif command -v shasum >/dev/null 2>&1; then
    ACTUAL=$(shasum -a 256 "${TMP_DIR}/${BINARY}.tar.gz" | awk '{print $1}')
  else
    info "Warning: sha256sum/shasum not found — skipping checksum verification"
  fi
  if [[ -n "$ACTUAL" && "$ACTUAL" != "$EXPECTED" ]]; then
    err "Checksum mismatch! Expected: $EXPECTED  Got: $ACTUAL"
  fi
  [[ -n "$ACTUAL" ]] && info "Checksum OK ($ACTUAL)"
else
  info "Warning: Could not fetch checksum — skipping verification"
fi

# ── Extract ───────────────────────────────────────────────────────────────────

tar -xzf "${TMP_DIR}/${BINARY}.tar.gz" -C "$TMP_DIR"
chmod +x "${TMP_DIR}/${BINARY}"

# ── Install ───────────────────────────────────────────────────────────────────

if [[ -w "$INSTALL_DIR" ]]; then
  mv "${TMP_DIR}/${BINARY}" "${INSTALL_DIR}/${BINARY}"
else
  info "Installing to $INSTALL_DIR (may prompt for sudo password)..."
  sudo install -m 755 "${TMP_DIR}/${BINARY}" "${INSTALL_DIR}/${BINARY}"
fi

info "Installed $(${INSTALL_DIR}/${BINARY} version 2>/dev/null || echo 'investibook') → ${INSTALL_DIR}/${BINARY}"

fi  # end skip-if-already-installed

# ── Optional: auto init ───────────────────────────────────────────────────────

if [[ -n "$API_HOST" && -n "$API_KEY" ]]; then
  info "Running: investibook init --api-host $API_HOST --api-key $API_KEY"
  "${INSTALL_DIR}/${BINARY}" init --api-host "$API_HOST" --api-key "$API_KEY"
  info "Done! Run 'investibook --help' to get started."
else
  echo ""
  echo "  Next step — authenticate:"
  echo "  investibook init --api-host <URL> --api-key <KEY>"
  echo ""
  echo "  Get an API key: Settings → API Keys in the Investibook web UI."
fi
