#!/usr/bin/env bash
# Nova Code installer
#
# Usage:
#   curl -fsSL https://nova.dekipi.com/cli/install.sh | bash
#
# Environment variables:
#   NOVA_INSTALL_DIR   Install location (default: $HOME/.local/bin)
#   NOVA_VERSION       Pin to a specific version instead of "latest"

set -euo pipefail

BASE_URL="https://dl.dekipi.com/dekipi-nova-releases"
INSTALL_DIR="${NOVA_INSTALL_DIR:-$HOME/.local/bin}"
REQUESTED_VERSION="${NOVA_VERSION:-}"

info()  { printf '\033[1;34m==>\033[0m %s\n' "$1"; }
error() { printf '\033[1;31merror:\033[0m %s\n' "$1" >&2; exit 1; }

detect_platform() {
  local os arch
  os="$(uname -s)"
  arch="$(uname -m)"

  case "$os" in
    Darwin) os="darwin" ;;
    Linux)  os="linux" ;;
    *) error "unsupported operating system: $os" ;;
  esac

  case "$arch" in
    x86_64 | amd64)  arch="amd64" ;;
    arm64 | aarch64) arch="arm64" ;;
    *) error "unsupported architecture: $arch" ;;
  esac

  echo "nova-${os}_${arch}"
}

path_has_dir() {
  case ":$PATH:" in
    *":$1:"*) return 0 ;;
    *) return 1 ;;
  esac
}

main() {
  command -v curl >/dev/null 2>&1 || error "curl is required to install Nova Code"

  local binary ver url tmp
  binary="$(detect_platform)"

  if [ -n "$REQUESTED_VERSION" ]; then
    ver="$REQUESTED_VERSION"
  else
    info "Resolving latest version..."
    ver="$(curl -fsSL "${BASE_URL}/latest")"
    [ -n "$ver" ] || error "could not resolve the latest version"
  fi

  info "Installing Nova Code ${ver} (${binary})..."

  url="${BASE_URL}/${ver}/${binary}"
  tmp="$(mktemp)"
  trap 'rm -f "$tmp"' EXIT

  curl -fsSL "$url" -o "$tmp" || error "download failed: $url"
  chmod +x "$tmp"

  mkdir -p "$INSTALL_DIR"
  mv "$tmp" "$INSTALL_DIR/nova"
  trap - EXIT

  info "Installed to ${INSTALL_DIR}/nova"

  if path_has_dir "$INSTALL_DIR"; then
    info "${INSTALL_DIR} is already on your PATH — you're all set."
  else
    info "${INSTALL_DIR} isn't on your PATH in this shell yet."
    echo
    echo "  Most distros add ~/.local/bin to PATH automatically once it"
    echo "  exists, so a new terminal session will likely pick it up on its own."
    echo
    echo "  To use it right now, run:"
    echo
    echo "    export PATH=\"${INSTALL_DIR}:\$PATH\""
    echo
    echo "  Add that line to your shell profile (~/.bashrc, ~/.zshrc, etc.) to make it permanent."
  fi

  info "Run 'nova --version' to verify the installation."
}

main "$@"
