#!/usr/bin/env bash
# Curl-able installer for caspian.
#
# Usage:
#   curl -fsSL https://nox-website.s3.amazonaws.com/install.sh | bash
#
# Downloads the universal macOS binary, chmods it, and hands off to
# `caspian setup`, which copies itself into ~/.caspian/bin/ and installs
# the LaunchAgent + <user>.local mapping + prereqs.

set -euo pipefail

BINARY_BASE_URL="${CASPIAN_BINARY_BASE_URL:-https://nox-website.s3.amazonaws.com}"

W='\033[1m'
D='\033[0;90m'
R='\033[0m'

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "caspian is macOS-only." >&2
  exit 1
fi

# Pick the right thin binary. Rosetta-translated shells on Apple Silicon
# report x86_64, so also check sysctl for the native CPU arch.
ARCH="$(uname -m)"
if [[ "$ARCH" = "x86_64" ]] && sysctl -n sysctl.proc_translated 2>/dev/null | grep -q '^1$'; then
  ARCH="arm64"
fi
case "$ARCH" in
  arm64)  BINARY_NAME="caspian-darwin-arm64" ;;
  x86_64) BINARY_NAME="caspian-darwin-x64" ;;
  *) echo "unsupported arch: $ARCH" >&2; exit 1 ;;
esac
BINARY_URL="$BINARY_BASE_URL/$BINARY_NAME"

printf "\n${W}installing caspian${R}\n\n"

TMP_DIR="$(mktemp -d -t caspian.XXXXXX)"
trap 'rm -rf "$TMP_DIR"' EXIT
TMP_BIN="$TMP_DIR/caspian"

printf "${D}  downloading binary${R}\n"
curl -fSL --progress-bar "$BINARY_URL" -o "$TMP_BIN"
chmod +x "$TMP_BIN"

# Sanity check — bun-compiled binaries run --version without side effects.
if ! "$TMP_BIN" --version >/dev/null 2>&1; then
  echo "downloaded binary failed to run. check $BINARY_URL" >&2
  exit 1
fi

# Ensure ~/.caspian/bin is on PATH so `caspian <verb>` works after setup.
add_to_path() {
  local rc="$1"
  [[ -f "$rc" ]] || return 0
  if ! grep -qs 'caspian/bin' "$rc"; then
    printf '\n# caspian\nexport PATH="$HOME/.caspian/bin:$PATH"\n' >> "$rc"
    printf "${D}  added ~/.caspian/bin to PATH in %s${R}\n" "$rc"
  fi
}

case "$(basename "${SHELL:-}")" in
  zsh)  add_to_path "$HOME/.zshrc" ;;
  bash) add_to_path "$HOME/.bashrc"; add_to_path "$HOME/.bash_profile" ;;
esac

printf "\n"
exec "$TMP_BIN" setup
