#!/usr/bin/env sh
set -eu

# Installer for codelogician-lite-shell
# Usage: curl -fsSL https://codelogician.dev/cl-lite-shell/install.sh | sh

INSTALL_DIR="${CODELOGICIAN_INSTALL_DIR:-/usr/local/bin}"
BIN_NAME="cl-lite"
BASE_URL="${CODELOGICIAN_DOWNLOAD_URL:-https://storage.googleapis.com/imandra-dev-codelogician-releases/codelogician-lite-shell}"

main() {
  check_deps
  download
  echo "codelogician installed to ${INSTALL_DIR}/${BIN_NAME}"
  echo "Run '${INSTALL_DIR}/${BIN_NAME} --version' to verify."
  echo "To uninstall, run: rm ${INSTALL_DIR}/${BIN_NAME}"
}

check_deps() {
  for cmd in curl jq; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      echo "Error: '$cmd' is required but not installed." >&2
      exit 1
    fi
  done
}

download() {
  tmp=$(mktemp)
  trap 'rm -f "$tmp"' EXIT

  echo "Downloading cl-lite..."
  curl -fsSL "${BASE_URL}/codelogician.sh" -o "$tmp"

  # Install — use sudo if the target dir isn't writable
  if [ -w "$INSTALL_DIR" ]; then
    mv "$tmp" "${INSTALL_DIR}/${BIN_NAME}"
    chmod +x "${INSTALL_DIR}/${BIN_NAME}"
  else
    echo "Installing to ${INSTALL_DIR} (requires sudo)..."
    sudo mv "$tmp" "${INSTALL_DIR}/${BIN_NAME}"
    sudo chmod +x "${INSTALL_DIR}/${BIN_NAME}"
  fi
}

main
