#!/bin/sh
# install.sh — wild-workspace bootstrap installer (macOS + Linux)
# ============================================================================
# ONE-LINE USAGE (what the landing page shows):
#   curl -fsSL https://workspace.venturewild.llc/install.sh | sh -s -- <LOGIN_BLOB>
#
# WHY THIS EXISTS: `npm i -g @venturewild/workspace` SUCCEEDS, but the bare
# `wild-workspace` command then dies with "command not found" because npm's
# global-bin directory isn't on PATH — the #1 install failure for real users.
# This installer NEVER depends on PATH: it resolves an ABSOLUTE `node`, installs
# the package, then drives the CLI by its ABSOLUTE path inside the package.
# No admin password. Idempotent — safe to re-run.
# ============================================================================
set -u

PACKAGE="@venturewild/workspace"
WW_DIR="$HOME/.wild-workspace"
LOCAL_NODE_DIR="$WW_DIR/node"        # a private Node lives here when the system one is absent/old
USER_PREFIX="$WW_DIR/npm-global"     # fallback install spot if the default needs a password
MIN_NODE_MAJOR=18
BLOB="${1:-${WW_BLOB:-}}"  # login blob: 1st arg or $WW_BLOB env (landing bakes it in)

bold() { printf '\033[1m%s\033[0m\n' "$*"; }
say()  { printf '  %s\n' "$*"; }
fail() { printf '\n\033[31mX %s\033[0m\n' "$*"; exit 1; }

bold "wild-workspace installer"
say  "Setting up your personal workspace. No admin password needed, and it's"
say  "safe to run this again if anything ever goes wrong."
say  ""

# ---- 0. Pin a writable workspace home (never inherit the shell's cwd) -------
# Without this the CLI uses this shell's cwd as the workspace root; a piped
# invocation can land in an unwritable cwd. Exporting it makes login + service
# agree on one writable home. Honour a value the caller/landing already set.
[ -n "${WILD_WORKSPACE_DIR:-}" ] || WILD_WORKSPACE_DIR="$HOME"
export WILD_WORKSPACE_DIR
say "Your workspace will live in: $WILD_WORKSPACE_DIR"
say ""

# ---- 1. Find a Node >= 18 (use the system one if it's new enough) ----------
NODE=""
if command -v node >/dev/null 2>&1; then
  NODE=$(command -v node)
  NODE_MAJOR=$("$NODE" -v 2>/dev/null | sed 's/^v//;s/\..*//')
  case "$NODE_MAJOR" in '' | *[!0-9]*) NODE_MAJOR=0 ;; esac
  if [ "$NODE_MAJOR" -ge "$MIN_NODE_MAJOR" ]; then
    say "OK  Found Node $("$NODE" -v) — good."
  else
    say "Found Node $("$NODE" -v 2>/dev/null), but wild-workspace needs Node $MIN_NODE_MAJOR+."
    say "I'll install a private copy of Node (just for you, no password) instead."
    NODE=""
  fi
fi

# ---- 2. If no usable Node, install one under ~/.wild-workspace/node ---------
if [ -z "$NODE" ]; then
  os=$(uname -s); arch=$(uname -m)
  case "$os-$arch" in
    Darwin-arm64)            NOS=darwin; NARCH=arm64 ;;
    Darwin-x86_64)           NOS=darwin; NARCH=x64 ;;
    Linux-x86_64)            NOS=linux;  NARCH=x64 ;;
    Linux-aarch64 | Linux-arm64) NOS=linux;  NARCH=arm64 ;;
    *) fail "This computer ($os $arch) isn't one the installer handles yet. Please install Node $MIN_NODE_MAJOR+ yourself from nodejs.org, then re-run this command." ;;
  esac
  command -v curl >/dev/null 2>&1 || fail "This installer needs 'curl'. (You launched it with curl, so it should be here — please tell the VentureWild team.)"
  command -v tar  >/dev/null 2>&1 || fail "This installer needs 'tar', which is missing on this machine."

  say "Finding the latest Node version..."
  ver=$(curl -fsSL https://nodejs.org/dist/index.json | grep -o '"version":"v[0-9.]*"' | head -n 1 | sed 's/.*"\(v[0-9.]*\)"/\1/')
  [ -n "$ver" ] || fail "Couldn't read the Node download list. Are you online?"

  tarball="node-$ver-$NOS-$NARCH.tar.gz"
  url="https://nodejs.org/dist/$ver/$tarball"
  say "Downloading Node $ver for $NOS/$NARCH..."
  mkdir -p "$LOCAL_NODE_DIR" || fail "Couldn't create $LOCAL_NODE_DIR."
  tmp=$(mktemp -d) || fail "Couldn't make a temporary folder."
  if ! curl -fsSL "$url" -o "$tmp/$tarball"; then
    rm -rf "$tmp"; fail "Couldn't download Node from $url."
  fi
  say "Unpacking into $LOCAL_NODE_DIR (no password)..."
  if ! tar -xzf "$tmp/$tarball" -C "$LOCAL_NODE_DIR" --strip-components=1; then
    rm -rf "$tmp"; fail "Couldn't unpack Node."
  fi
  rm -rf "$tmp"
  NODE="$LOCAL_NODE_DIR/bin/node"
  [ -x "$NODE" ] || fail "Node was downloaded but the node program wasn't found at $NODE."
  say "OK  Installed Node $("$NODE" -v)."
fi

# ---- 3. Locate npm and run it via absolute node (so no PATH is needed) ------
# npm's own shebang is `#!/usr/bin/env node` — running `npm` directly would need
# node on PATH. We bypass that by invoking npm-cli.js through our absolute node.
NPM_CLI=$("$NODE" -e 'try{var p=require("path");console.log(p.join(p.dirname(require.resolve("npm/package.json")),"bin","npm-cli.js"))}catch(e){}' 2>/dev/null || true)
if [ ! -f "$NPM_CLI" ]; then
  _prefix=$(dirname "$(dirname "$NODE")")
  NPM_CLI="$_prefix/lib/node_modules/npm/bin/npm-cli.js"
fi
[ -f "$NPM_CLI" ] || fail "Found Node but couldn't find npm alongside it. Please report this to the VentureWild team."
NPM() { "$NODE" "$NPM_CLI" "$@"; }

# ---- 4. Install wild-workspace globally (fall back to a user dir if needed) -
say "Installing wild-workspace..."
LOG="$WW_DIR/install.log"; mkdir -p "$WW_DIR"
if NPM i -g --no-audit --no-fund "$PACKAGE" >"$LOG" 2>&1; then
  ROOT_G=$(NPM root -g)
else
  say "The usual install spot needs a password, so I'll use a private spot instead (still no password)..."
  mkdir -p "$USER_PREFIX" || fail "Couldn't create $USER_PREFIX."
  if NPM i -g --no-audit --no-fund --prefix "$USER_PREFIX" "$PACKAGE" >>"$LOG" 2>&1; then
    ROOT_G="$USER_PREFIX/lib/node_modules"
  else
    tail -n 6 "$LOG" 2>/dev/null
    fail "Couldn't install wild-workspace. (The few lines above may say why.)"
  fi
fi
CLI="$ROOT_G/@venturewild/workspace/server/bin/wild-workspace.mjs"
[ -f "$CLI" ] || fail "Install finished, but the program wasn't found at $CLI. Please report this."
say "OK  Installed to $ROOT_G/@venturewild/workspace."

# ---- 5. Link this computer to your account (login) — by ABSOLUTE path -------
if [ -z "$BLOB" ]; then
  say ""
  say "Almost there! wild-workspace is installed, but I still need your personal"
  say "login code (the blob copied from workspace.venturewild.llc). Re-run the"
  say "command from the website with your code, or run:"
  say "    \"$NODE\" \"$CLI\" login \"YOUR-CODE-HERE\""
else
  say "Linking this computer to your account..."
  login_out=$("$NODE" "$CLI" login "$BLOB" 2>&1)
  rc=$?
  printf '%s\n' "$login_out"
  if [ "$rc" -ne 0 ]; then
    fail "Linking didn't complete. Check the code you pasted and try again."
  fi
  slug=$(printf '%s' "$login_out" | sed -n 's/^  slug *: *//p' | head -n 1)
fi

# ---- 6. Enable always-on AND start it NOW — by ABSOLUTE path ----------------
# (login already does this when a code was supplied; this is belt-and-suspenders so
#  the workspace is live immediately, not just at the next login.)
say "Turning on always-on + starting your workspace now..."
"$NODE" "$CLI" service install >>"$LOG" 2>&1 || true
if "$NODE" "$CLI" service start >>"$LOG" 2>&1; then
  say "OK  always-on is on and your workspace is starting."
else
  say "(always-on is set up; it'll come up at your next login. Logs are in $WW_DIR.)"
fi

# ---- 7. Done ----------------------------------------------------------------
say ""
bold "Done!"
if [ -n "${slug:-}" ]; then
  say "Your workspace is starting now — it'll be live at:"
  say "    https://$slug.venturewild.llc"
  say "  (give it a few seconds; it relaunches automatically every time you log in)"
else
  say "wild-workspace is installed and will start automatically at your next login."
fi
say ""
say "Nothing else to do — no extra commands, no terminal to keep open."
say ""
say "Welcome to wild-workspace."
