#!/bin/sh
# Install the `nex` CLI by downloading the appropriate prebuilt binary.
#
# Usage:
#   curl -fsSL https://nextoken.biz/install.sh | sh
#
# Env vars you can set:
#   NEX_VERSION   pin to a specific release (default: latest)
#   NEX_INSTALL_DIR  where to put the binary (default: /usr/local/bin)

set -eu

VERSION="${NEX_VERSION:-v0.1.0}"
INSTALL_DIR="${NEX_INSTALL_DIR:-/usr/local/bin}"
# Override with NEX_DOWNLOAD_BASE for self-hosted mirrors. Defaults to the
# Nex CDN; once the GitHub release flow is wired this will become the
# release URL pattern.
DOWNLOAD_BASE="${NEX_DOWNLOAD_BASE:-https://nextoken.biz/dl}"

detect_os() {
  case "$(uname -s)" in
    Darwin)  echo "darwin"  ;;
    Linux)   echo "linux"   ;;
    *)       echo "unsupported"; exit 1 ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)  echo "amd64" ;;
    aarch64|arm64) echo "arm64" ;;
    *)             echo "unsupported"; exit 1 ;;
  esac
}

OS=$(detect_os)
ARCH=$(detect_arch)
BIN="nex-${OS}-${ARCH}"
URL="${DOWNLOAD_BASE}/${VERSION}/${BIN}"

echo "Installing nex ${VERSION} (${OS}/${ARCH}) to ${INSTALL_DIR}/nex ..."

# Use sudo if the install dir isn't writable as the current user.
SUDO=""
if [ ! -w "$INSTALL_DIR" ]; then
  if command -v sudo >/dev/null 2>&1; then
    SUDO=sudo
  else
    echo "Error: ${INSTALL_DIR} not writable and sudo not available." >&2
    exit 1
  fi
fi

TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT

if ! curl -fsSL -o "$TMP" "$URL"; then
  echo "Error: download failed for $URL" >&2
  exit 1
fi

$SUDO install -m 0755 "$TMP" "$INSTALL_DIR/nex"
echo
echo "Installed: $(${INSTALL_DIR}/nex version)"
echo
echo "Next: run 'nex login' to authenticate."
