#!/bin/sh
# Hopbits CLI Installer — https://hopbits.io/cli.sh
#
# Quick start (zero sudo prompts; installs to /usr/local/bin or ~/.local/bin):
#   curl -fsSL https://hopbits.io/cli.sh | sh
#
# Pin a specific release or custom install directory:
#   curl -fsSL https://hopbits.io/cli.sh | HOPBITS_CLI_VERSION=0.1.0 sh
#   curl -fsSL https://hopbits.io/cli.sh | HOPBITS_INSTALL_DIR="$HOME/bin" sh
#
# Optional overrides:
#   HOPBITS_CLI_VERSION=<semver>                     (default: latest)
#   HOPBITS_INSTALL_DIR=<dir>                        (default: /usr/local/bin if writable, else ~/.local/bin)
#   HOPBITS_RELEASE_BASE=https://hopbits.io/releases (override release base URL)

set -eu

RELEASE_BASE="${HOPBITS_RELEASE_BASE:-https://hopbits.io/releases}"
RELEASE_BASE="${RELEASE_BASE%/}"
RAW_VERSION="${HOPBITS_CLI_VERSION:-}"

say() {
  printf '==> %s\n' "$*"
}

err() {
  printf 'error: %s\n' "$*" >&2
  exit 1
}

fetch_file() {
  url="$1"
  dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$dest"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$dest" "$url"
  else
    err "Neither curl nor wget is installed."
  fi
}

verify_sha256() {
  dir="$1"
  bin_name="$2"
  expected="$(awk -v f="$bin_name" '$2 == f || $2 == "*"f { print $1; exit }' "${dir}/SHA256SUMS")"
  if [ -z "$expected" ]; then
    err "Could not find SHA-256 entry for ${bin_name} in SHA256SUMS."
  fi
  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "${dir}/${bin_name}" | awk '{ print $1 }')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "${dir}/${bin_name}" | awk '{ print $1 }')"
  else
    err "Neither sha256sum nor shasum is installed to verify ${bin_name}."
  fi
  if [ "$actual" != "$expected" ]; then
    err "SHA-256 mismatch for ${bin_name} (expected ${expected}, got ${actual})."
  fi
}

raw_os="$(uname -s 2>/dev/null || printf 'unknown')"
case "${raw_os}" in
  Linux)
    OS="linux"
    ;;
  Darwin)
    OS="darwin"
    ;;
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    printf 'Windows detected (%s). Download the native Windows CLI binary directly:\n\n' "${raw_os}" >&2
    printf '  PowerShell:\n' >&2
    printf '    Invoke-WebRequest -Uri "%s/hopbits-windows-amd64.exe" -OutFile "hopbits.exe"\n' "${RELEASE_BASE}" >&2
    printf '    Invoke-WebRequest -Uri "%s/SHA256SUMS" -OutFile "SHA256SUMS"\n' "${RELEASE_BASE}" >&2
    printf '    Get-FileHash .\\hopbits.exe -Algorithm SHA256\n\n' >&2
    printf '  Direct URL: %s/hopbits-windows-amd64.exe\n' "${RELEASE_BASE}" >&2
    exit 1
    ;;
  *)
    err "Unsupported operating system '${raw_os}' (supported: Linux, Darwin; Windows: ${RELEASE_BASE}/hopbits-windows-amd64.exe)."
    ;;
esac

raw_arch="$(uname -m 2>/dev/null || printf 'unknown')"
case "${raw_arch}" in
  x86_64|amd64)
    ARCH="amd64"
    ;;
  aarch64|arm64)
    ARCH="arm64"
    ;;
  *)
    err "Unsupported CPU architecture '${raw_arch}' (supported: x86_64/amd64, aarch64/arm64)."
    ;;
esac

VERSION=""
if [ -n "${RAW_VERSION}" ]; then
  VERSION="${RAW_VERSION#v}"
  case "${VERSION}" in
    ""|*[!0-9A-Za-z._-]*)
      err "Invalid HOPBITS_CLI_VERSION '${RAW_VERSION}'."
      ;;
  esac
  BIN_NAME="hopbits-${VERSION}-${OS}-${ARCH}"
else
  BIN_NAME="hopbits-${OS}-${ARCH}"
fi

if [ -n "${HOPBITS_INSTALL_DIR:-}" ]; then
  INSTALL_DIR="${HOPBITS_INSTALL_DIR%/}"
  [ -n "${INSTALL_DIR}" ] || INSTALL_DIR="/"
elif [ "$(id -u 2>/dev/null || printf '1')" = "0" ]; then
  INSTALL_DIR="/usr/local/bin"
elif [ -d "/usr/local/bin" ] && [ -w "/usr/local/bin" ]; then
  INSTALL_DIR="/usr/local/bin"
else
  if [ -z "${HOME:-}" ]; then
    err "HOME is not set. Pass HOPBITS_INSTALL_DIR=/path/to/bin to choose an install location."
  fi
  INSTALL_DIR="${HOME%/}/.local/bin"
fi

if ! mkdir -p "${INSTALL_DIR}" 2>/dev/null || [ ! -w "${INSTALL_DIR}" ]; then
  err "Install directory '${INSTALL_DIR}' is not writable. Set HOPBITS_INSTALL_DIR to a writable directory."
fi

DEST="${INSTALL_DIR}/hopbits"
TMP_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "${TMP_DIR}"
}
trap cleanup EXIT INT TERM

say "Downloading verified ${BIN_NAME} from ${RELEASE_BASE}..."
if ! fetch_file "${RELEASE_BASE}/SHA256SUMS" "${TMP_DIR}/SHA256SUMS" || \
   ! fetch_file "${RELEASE_BASE}/${BIN_NAME}" "${TMP_DIR}/${BIN_NAME}"; then
  err "Could not download ${BIN_NAME} from ${RELEASE_BASE}. Check outbound HTTPS connectivity and version."
fi

verify_sha256 "${TMP_DIR}" "${BIN_NAME}"
chmod 0755 "${TMP_DIR}/${BIN_NAME}"

TMP_DEST="${DEST}.tmp.$$"
cp "${TMP_DIR}/${BIN_NAME}" "${TMP_DEST}"
chmod 0755 "${TMP_DEST}"
mv -f "${TMP_DEST}" "${DEST}"

say "Installed hopbits to ${DEST}"
"${DEST}" version

case ":${PATH:-}:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    printf '\nNote: %s is not in your PATH. Add it with:\n' "${INSTALL_DIR}"
    printf '  export PATH="%s:$PATH"\n' "${INSTALL_DIR}"
    ;;
esac

printf '\nQuick start:\n'
printf '  export HOPBITS_API_KEY=hb_live_...\n'
printf '  hopbits whoami\n'
printf '  hopbits export -o hopbits.yaml\n'
printf '  hopbits apply -f hopbits.yaml\n'
