#!/bin/sh
# nanpos CLI installer.
#
#   curl -fsSL https://cli.nanpos.com/install.sh | sh
#
# Env overrides:
#   NANPOS_VERSION=v1.2.3    pin a version (default: latest release)
#   NANPOS_INSTALL=~/.nanpos  install prefix (binary goes in $NANPOS_INSTALL/bin)
#   NANPOS_DL_BASE=…          download host (default: https://cli.nanpos.com, o Worker
#                             que redireciona pro mirror público GCS)
set -eu

BIN="nanpos"
: "${NANPOS_INSTALL:=${HOME}/.nanpos}"
: "${NANPOS_DL_BASE:=https://cli.nanpos.com}"
INSTALL_DIR="${NANPOS_INSTALL}/bin"

fail() { echo "nanpos: $*" >&2; exit 1; }

# --- detect platform ---------------------------------------------------------
os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$os" in
  linux|darwin) ;;
  *) fail "SO não suportado: $os (suportados: linux, darwin)" ;;
esac
case "$arch" in
  x86_64|amd64)  arch="amd64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) fail "arquitetura não suportada: $arch" ;;
esac
asset="${BIN}_${os}_${arch}"

# --- resolve download URLs ---------------------------------------------------
# cli.nanpos.com is a Cloudflare Worker (see docs/distribution.md) that proxies
# the private GitHub release, so the download is anonymous. Pass ?version= to pin.
ver="${NANPOS_VERSION:-latest}"
# cache-bust: query única por run → sempre a geração atual do objeto no GCS
# (o GCS edge-cacheia objetos públicos; sem isto um checksums.txt velho fura o install).
_cb="cb=$(date +%s 2>/dev/null || echo 0)$$"
if [ "$ver" = "latest" ]; then q="?${_cb}"; else q="?version=${ver}&${_cb}"; fi
base="${NANPOS_DL_BASE}/download"

# --- download ----------------------------------------------------------------
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

dl() { # silencioso (arquivos pequenos: checksums)
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else fail "preciso de curl ou wget no PATH"; fi
}
dl_progress() { # com barra de progresso (o binário, ~13MB)
  if command -v curl >/dev/null 2>&1; then curl -fL --progress-bar "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -q --show-progress -O "$2" "$1"
  else fail "preciso de curl ou wget no PATH"; fi
}

echo "nanpos: baixando ${asset} (${ver})…"
dl_progress "${base}/${asset}${q}" "$tmp/$BIN" || fail "download falhou (${base}/${asset}) — release/host existe?"
dl "${NANPOS_DL_BASE}/checksums.txt${q}" "$tmp/checksums.txt" || echo "nanpos: (sem checksums.txt — pulando verificação)" >&2

# --- verify checksum (best-effort) ------------------------------------------
if [ -s "$tmp/checksums.txt" ]; then
  sha=""
  if command -v sha256sum >/dev/null 2>&1; then sha="sha256sum"
  elif command -v shasum   >/dev/null 2>&1; then sha="shasum -a 256"; fi
  if [ -n "$sha" ]; then
    want="$(grep " ${asset}\$" "$tmp/checksums.txt" 2>/dev/null | awk '{print $1}')"
    if [ -n "$want" ]; then
      got="$($sha "$tmp/$BIN" | awk '{print $1}')"
      [ "$want" = "$got" ] || fail "checksum não confere (esperado $want, obtido $got)"
      echo "nanpos: checksum ok"
    fi
  fi
fi

# --- install -----------------------------------------------------------------
mkdir -p "$INSTALL_DIR"
chmod +x "$tmp/$BIN"
mv "$tmp/$BIN" "$INSTALL_DIR/$BIN"
# alias curto `np` — symlink relativo (sobrevive a upgrade, que só troca `nanpos`)
ln -sf "$BIN" "$INSTALL_DIR/np"
echo "nanpos: instalado em $INSTALL_DIR/$BIN (+ alias np)"

# --- add to PATH -------------------------------------------------------------
# Auto-adiciona ao PATH (idempotente), como bun/deno fazem. Opt-out: NANPOS_NO_MODIFY_PATH=1.
add_to_path() { # imprime o(s) arquivo(s) que editou (vazio se nenhum)
  _line="export PATH=\"${INSTALL_DIR}:\$PATH\""
  case "$(basename "${SHELL:-sh}")" in
    zsh)  _files="${ZDOTDIR:-$HOME}/.zshrc" ;;
    bash) _files="$HOME/.bashrc" ; [ -f "$HOME/.bash_profile" ] && _files="$_files $HOME/.bash_profile" ;;
    fish)
      _d="$HOME/.config/fish/conf.d"; mkdir -p "$_d"
      printf 'set -gx PATH %s $PATH\n' "$INSTALL_DIR" > "$_d/nanpos.fish"
      printf '%s' " $_d/nanpos.fish"; return ;;
    *)    _files="$HOME/.profile" ;;
  esac
  _touched=""
  for _f in $_files; do
    [ -e "$_f" ] || touch "$_f"
    if ! grep -qF "$INSTALL_DIR" "$_f" 2>/dev/null; then
      printf '\n# nanpos CLI\n%s\n' "$_line" >> "$_f"
      _touched="$_touched $_f"
    fi
  done
  printf '%s' "$_touched"
}

echo ""
case ":${PATH}:" in
  *":${INSTALL_DIR}:"*)
    : ;;  # já está no PATH
  *)
    if [ "${NANPOS_NO_MODIFY_PATH:-0}" = "1" ]; then
      echo "Adicione ao PATH:  export PATH=\"${INSTALL_DIR}:\$PATH\""
    else
      _edited="$(add_to_path)"
      if [ -n "$_edited" ]; then
        echo "nanpos: PATH atualizado em$_edited"
        echo "        abra um novo terminal (ou:  export PATH=\"${INSTALL_DIR}:\$PATH\")"
      else
        echo "Adicione ao PATH:  export PATH=\"${INSTALL_DIR}:\$PATH\""
      fi
    fi ;;
esac

echo ""
echo "Feito. Próximo passo:  nanpos auth login"
