#!/usr/bin/env bash
# Salus CLI installer.
#
# Detects your OS and CPU architecture, downloads the matching salus binary,
# and installs it to /usr/local/bin. Run it with:
#
#   curl -fsSL https://download.salus.cloud/install.sh | bash
#
# Override the install directory with SALUS_INSTALL_DIR.
set -euo pipefail

BASE_URL="${SALUS_DOWNLOAD_BASE:-https://download.salus.cloud}"
BIN_NAME="salus"
INSTALL_DIR="${SALUS_INSTALL_DIR:-/usr/local/bin}"

# Sentinel is split so the publish-time substitution leaves it intact, letting
# an unconfigured installer fail clearly instead of fetching a bad URL.
UNCONFIGURED='__SALUS_DOWNLOAD_BASE'"__"
if [[ "$BASE_URL" == "$UNCONFIGURED" ]]; then
  echo "✗ No download URL configured. Set SALUS_DOWNLOAD_BASE or use an uploaded installer." >&2
  exit 1
fi

detect_platform() {
  local os arch
  os="$(uname -s)"
  arch="$(uname -m)"
  case "$os" in
    Darwin) os="darwin" ;;
    Linux)  os="linux" ;;
    *) echo "✗ Unsupported OS: $os" >&2; exit 1 ;;
  esac
  case "$arch" in
    arm64|aarch64) arch="arm64" ;;
    x86_64|amd64)  arch="x64" ;;
    *) echo "✗ Unsupported architecture: $arch" >&2; exit 1 ;;
  esac
  printf '%s-%s\n' "$os" "$arch"
}

PLATFORM="$(detect_platform)"
ASSET="salus-cli-${PLATFORM}"
URL="${BASE_URL}/${ASSET}"

echo "→ Downloading salus ($PLATFORM) from ${URL}"
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
if ! curl -fSL "$URL" -o "$TMP"; then
  echo "✗ Download failed: $URL" >&2
  exit 1
fi
chmod +x "$TMP"

TARGET="${INSTALL_DIR%/}/${BIN_NAME}"
if [[ -w "$INSTALL_DIR" ]] || { [[ ! -e "$INSTALL_DIR" ]] && mkdir -p "$INSTALL_DIR" 2>/dev/null; }; then
  mv -f "$TMP" "$TARGET"
else
  echo "→ ${INSTALL_DIR} is not writable; elevating with sudo"
  sudo mkdir -p "$INSTALL_DIR"
  sudo mv -f "$TMP" "$TARGET"
fi
trap - EXIT

echo "✓ Installed salus to ${TARGET}"
if ! command -v salus >/dev/null 2>&1; then
  echo "  Note: ${INSTALL_DIR} is not on your PATH. Add it, or run ${TARGET} directly."
fi
