#!/bin/sh
# ============================================================
# mybitduit installer — https://mybitduit.com
#   curl -fsSL https://mybitduit.com/install.sh | sh
# Installs the CLI globally via npm, then makes sure the
# `mybitduit` command is actually on your PATH.
# Non-custodial, always: this only installs a price/wallet
# *viewer* — it never touches keys or funds.
# ============================================================
set -e

GREEN='\033[38;2;0;255;156m'; DIM='\033[38;2;95;122;110m'
RED='\033[38;2;255;79;163m'; BOLD='\033[1m'; RESET='\033[0m'

say()  { printf "%b\n" "$1"; }
fail() { say "${RED}✗ $1${RESET}"; exit 1; }

say "${BOLD}${GREEN}mybitduit${RESET}${DIM} // installer${RESET}"

# --- 1. need node >= 18 + npm ---------------------------------
command -v node >/dev/null 2>&1 || fail "node not found — install Node 18+ first: https://nodejs.org"
command -v npm  >/dev/null 2>&1 || fail "npm not found — it ships with Node: https://nodejs.org"

NODE_MAJOR=$(node -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')
[ "$NODE_MAJOR" -ge 18 ] 2>/dev/null || fail "Node 18+ required (you have $(node -v))"

# --- 2. install globally from npm ------------------------------
say "${DIM}installing mybitduit globally via npm…${RESET}"
npm install -g mybitduit >/dev/null 2>&1 || npm install -g mybitduit \
  || fail "npm install -g failed — try: sudo npm install -g mybitduit"

# --- 3. make sure the command resolves -------------------------
NPM_BIN="$(npm prefix -g)/bin"

if command -v mybitduit >/dev/null 2>&1; then
  say "${GREEN}✓ installed${RESET} ${DIM}($(command -v mybitduit))${RESET}"
else
  # npm's global bin dir isn't on PATH — add it to the user's shell rc
  case "${SHELL:-}" in
    */zsh)  RC="$HOME/.zshrc" ;;
    */bash) RC="$HOME/.bashrc" ;;
    *)      RC="$HOME/.profile" ;;
  esac
  if ! grep -qs "$NPM_BIN" "$RC" 2>/dev/null; then
    printf '\n# npm global bin (added by mybitduit installer)\nexport PATH="%s:$PATH"\n' "$NPM_BIN" >> "$RC"
    say "${GREEN}✓ installed${RESET} ${DIM}— added $NPM_BIN to PATH in $RC${RESET}"
  else
    say "${GREEN}✓ installed${RESET} ${DIM}— $NPM_BIN already in $RC${RESET}"
  fi
  say "${DIM}open a new terminal (or: source $RC) before the first run${RESET}"
fi

say ""
say "  ${BOLD}mybitduit${RESET}               ${DIM}full-screen live terminal${RESET}"
say "  ${BOLD}mybitduit price sol${RESET}     ${DIM}one-shot price, scriptable${RESET}"
say "  ${BOLD}mybitduit watch <addr>${RESET}  ${DIM}read-only Solana wallet${RESET}"
say "  ${BOLD}mybitduit help${RESET}          ${DIM}everything else${RESET}"
say ""
say "${DIM}non-custodial, always — we never hold your money.${RESET}"
