#!/bin/sh
# envcli installer: https://envcli.dev
#
# Usage:
#   curl -fsSL https://envcli.dev/install.sh | sh
#
# This script installs the `envcli` CLI using whichever Node package manager
# you already have (bun > pnpm > npm). It does NOT touch your shell config.
# Inspect before running:
#   curl -fsSL https://envcli.dev/install.sh | less

set -eu

ENVCLI_VERSION="${ENVCLI_VERSION:-latest}"

# ANSI colours, but only if we're on a tty
if [ -t 1 ]; then
  BOLD='\033[1m'
  DIM='\033[2m'
  GREEN='\033[32m'
  RED='\033[31m'
  YELLOW='\033[33m'
  RESET='\033[0m'
else
  BOLD=''; DIM=''; GREEN=''; RED=''; YELLOW=''; RESET=''
fi

say() { printf '%b\n' "$*"; }
err() { printf '%bENVCLI: error: %s%b\n' "$RED" "$1" "$RESET" >&2; exit 1; }

say "${BOLD}Installing @envcli.dev/cli@${ENVCLI_VERSION}${RESET}"
say ""

have() { command -v "$1" >/dev/null 2>&1; }

if ! have node; then
  err "Node.js is required (>= 20). Install it from https://nodejs.org and re-run this."
fi

NODE_MAJOR="$(node -e 'process.stdout.write(String(process.versions.node.split(".")[0]))' 2>/dev/null || echo 0)"
if [ "${NODE_MAJOR}" -lt 20 ]; then
  err "envcli needs Node 20 or newer (you have $(node -v)). Upgrade and re-run."
fi

if have bun; then
  PM="bun"
  CMD="bun add -g @envcli.dev/cli@${ENVCLI_VERSION}"
elif have pnpm; then
  PM="pnpm"
  CMD="pnpm add -g @envcli.dev/cli@${ENVCLI_VERSION}"
elif have npm; then
  PM="npm"
  CMD="npm install -g @envcli.dev/cli@${ENVCLI_VERSION}"
else
  err "no package manager found (looked for bun, pnpm, npm)."
fi

say "${DIM}Using ${PM}: ${CMD}${RESET}"
say ""

if ! eval "$CMD"; then
  say ""
  say "${YELLOW}Install failed.${RESET} You may need to run with sudo, or fix npm permissions:"
  say "  https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally"
  exit 1
fi

say ""
if have envcli; then
  say "${GREEN}envcli installed:${RESET} $(envcli --version)"
  say ""
  say "Next:"
  say "  ${BOLD}envcli login${RESET}                # sign in with GitHub"
  say "  ${BOLD}envcli init${RESET}                 # create a project here"
  say "  ${BOLD}envcli push -m \"first push\"${RESET}  # encrypt and upload .env"
else
  say "${YELLOW}Installed, but \`envcli\` isn't on your PATH.${RESET}"
  say "Make sure your package manager's global bin directory is in PATH:"
  case "$PM" in
    npm)  say "  npm config get prefix";;
    pnpm) say "  pnpm bin -g";;
    bun)  say "  echo \$BUN_INSTALL/bin";;
  esac
fi
