#!/bin/sh
# Ninoo installer — https://ninoo.ai
#
# What this does, in full:
#   1. Checks for Node.js 20+ (ninoo runs on Node's built-in fetch).
#   2. Downloads the CLI (one self-contained file) to ~/.ninoo/lib/ninoo.mjs
#   3. Writes a launcher at ~/.local/bin/ninoo
# Nothing outside your home directory is touched. Re-run anytime to update.

set -eu

DL_URL="${NINOO_DL_URL:-https://ninoo.ai/ninoo.mjs}"
LIB_DIR="$HOME/.ninoo/lib"
BIN_DIR="$HOME/.local/bin"

fail() {
  echo "ninoo: $1" >&2
  exit 1
}

command -v node >/dev/null 2>&1 || fail "Node.js 20+ is required but 'node' was not found.
       Install it from https://nodejs.org and re-run this script."

NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
[ "$NODE_MAJOR" -ge 20 ] 2>/dev/null || fail "Node.js 20+ is required (found $(node -v))."

mkdir -p "$LIB_DIR" "$BIN_DIR"

echo "Downloading ninoo…"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$DL_URL" -o "$LIB_DIR/ninoo.mjs.tmp"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$LIB_DIR/ninoo.mjs.tmp" "$DL_URL"
else
  fail "neither curl nor wget is available."
fi
mv "$LIB_DIR/ninoo.mjs.tmp" "$LIB_DIR/ninoo.mjs"

cat > "$BIN_DIR/ninoo" <<'LAUNCHER'
#!/bin/sh
exec node "$HOME/.ninoo/lib/ninoo.mjs" "$@"
LAUNCHER
chmod +x "$BIN_DIR/ninoo"

echo "ninoo installed to $BIN_DIR/ninoo"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    echo ""
    echo "Note: $BIN_DIR is not on your PATH. Add this to your shell profile:"
    echo "  export PATH=\"\$HOME/.local/bin:\$PATH\""
    ;;
esac

echo ""
echo "Next: ninoo login"
