#!/bin/sh
# install.sh — the compiled Aleria CLI, from the CDN to your shell:
#
#   curl -fsSL https://download.aleria.ai/cli/install.sh | sh
#
# It downloads the prebuilt binary for this machine's OS and architecture,
# verifies it against the SHA-256 checksum published next to it, and puts it
# at ~/.local/bin/aleria.
#
# It writes nowhere but the home directory of whoever ran it — no /usr/local,
# no sudo — and it says exactly what it changed. Run it again and the current
# build replaces the previous one atomically; nothing stale is left behind.
#
# Unlike scripts/install.ts, which a developer runs from a checkout, it does
# edit one shell file: for a zsh user whose PATH lacks ~/.local/bin, it
# appends the PATH line to ~/.zshrc (once). ALERIA_NO_MODIFY_PATH=1 turns
# that off:
#
#   curl -fsSL https://download.aleria.ai/cli/install.sh | ALERIA_NO_MODIFY_PATH=1 sh

set -eu

BASE_URL="https://download.aleria.ai/cli"
BIN_DIR="$HOME/.local/bin"
NAME="aleria"

fail() {
  echo "aleria: $*" >&2
  exit 1
}

# --- which build this machine needs ----------------------------------------

os=$(uname -s)
arch=$(uname -m)

case "$os" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *)
    fail "no prebuilt binary for $os — this installer covers macOS and Linux;
  build from source instead (apps/cli in the Aleria repository)."
    ;;
esac

case "$arch" in
  x86_64 | amd64) arch=x64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *)
    fail "no prebuilt binary for $os/$arch —
  build from source instead (apps/cli in the Aleria repository)."
    ;;
esac

asset="$NAME-$os-$arch"

# --- download, into a scratch dir that always goes away ---------------------

tmp=$(mktemp -d)
stage=""
cleanup() {
  rm -rf "$tmp"
  if [ -n "$stage" ]; then rm -f "$stage"; fi
}
trap cleanup EXIT HUP INT TERM

echo "aleria: downloading $BASE_URL/$asset ($os/$arch)"
curl -fsSL "$BASE_URL/$asset" -o "$tmp/$asset" ||
  fail "download failed for $BASE_URL/$asset"
curl -fsSL "$BASE_URL/SHA256SUMS" -o "$tmp/SHA256SUMS" ||
  fail "download failed for $BASE_URL/SHA256SUMS"

# --- verify before anything lands -------------------------------------------

if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/$asset" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
  actual=$(shasum -a 256 "$tmp/$asset" | awk '{print $1}')
else
  fail "nothing to verify the download with: neither sha256sum nor shasum is
  installed. Install one (coreutils provides both) and run this again."
fi

expected=$(awk -v f="$asset" '$2 == f {print $1}' "$tmp/SHA256SUMS")
if [ -z "$expected" ]; then
  fail "SHA256SUMS does not list $asset — refusing to install."
fi
if [ "$actual" != "$expected" ]; then
  fail "checksum mismatch for $asset:
  expected $expected
  got      $actual
  Refusing to install. If this repeats, the published build is suspect."
fi
echo "aleria: checksum verified (sha256)"

# --- install, atomically, inside $HOME only ----------------------------------

if [ ! -d "$BIN_DIR" ]; then
  mkdir -p "$BIN_DIR"
  echo "aleria: created $BIN_DIR"
fi

# stage → chmod → mv: a reader either sees the old binary or the finished new
# one, never a half-written file, and a second run simply replaces the first.
stage="$BIN_DIR/.$NAME.tmp.$$"
cp "$tmp/$asset" "$stage"
chmod +x "$stage"
mv -f "$stage" "$BIN_DIR/$NAME"
stage=""

megabytes=$(( $(wc -c < "$BIN_DIR/$NAME") / 1000000 ))
echo "aleria: installed $BIN_DIR/$NAME (${megabytes} MB, $os/$arch)"
"$BIN_DIR/$NAME" --version ||
  echo "aleria: warning — $BIN_DIR/$NAME --version did not run on this machine" >&2

# --- put the directory on the shell's PATH ----------------------------------
#
# A fresh Mac has no ~/.local/bin on PATH, and a hint printed under a 75 MB
# download is one nobody reads: the next thing they type is `aleria` and the
# answer is `command not found`. So for zsh — the macOS default — the line
# goes into the file zsh reads for every interactive shell. The marker is how
# a second run knows the line is already there; the literal line counts too,
# because the hint this replaced told people to paste exactly that. Any other
# shell, or an opt-out, still gets the line to add by hand.

PATH_LINE='export PATH="$HOME/.local/bin:$PATH"'
PATH_MARKER="# Added by the Aleria CLI installer"

path_hint() {
  echo "aleria: $BIN_DIR is not on your PATH — add this to your shell's startup file:"
  echo "    $PATH_LINE"
}

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    zshrc="${ZDOTDIR:-$HOME}/.zshrc"
    login_shell="${SHELL:-}"
    if [ "${ALERIA_NO_MODIFY_PATH:-}" = "1" ] || [ "${login_shell##*/}" != "zsh" ]; then
      path_hint
    elif grep -qxF -e "$PATH_MARKER" -e "$PATH_LINE" "$zshrc" 2>/dev/null; then
      echo "aleria: $zshrc already adds it to PATH."
      echo "  Open a new terminal, or run: source $zshrc"
    # The redirection lives inside the subshell: POSIX lets a failed
    # redirection on a compound command end the whole script, and a
    # read-only ~/.zshrc must cost a hint, not the install that just worked.
    elif (
      exec >>"$zshrc" || exit 1
      if [ -s "$zshrc" ]; then
        # A file whose last line has no newline would glue the marker onto it.
        if [ -n "$(tail -c 1 "$zshrc")" ]; then printf '\n'; fi
        printf '\n'
      fi
      printf '%s\n%s\n' "$PATH_MARKER" "$PATH_LINE"
    ) 2>/dev/null; then
      echo "aleria: added $BIN_DIR to PATH in $zshrc"
      echo "  Open a new terminal, or run: source $zshrc"
    else
      echo "aleria: could not write $zshrc" >&2
      path_hint
    fi
    ;;
esac
