#!/bin/bash
# ComputeHive Node — One-Line Installer (macOS / Linux)
# Usage:
#   curl -fsSL http://YOUR_BROKER/install.sh | bash
#   curl -fsSL http://YOUR_BROKER/install.sh | bash -s -- --broker http://host:8080 --token TOKEN

set -e

PURPLE='\033[0;35m' BOLD='\033[1m' GREEN='\033[0;32m'
YELLOW='\033[0;33m' RED='\033[0;31m' RESET='\033[0m'

echo ""
echo -e "${BOLD}${PURPLE}  ComputeHive Node Installer${RESET}"
echo -e "${PURPLE}  ──────────────────────────────${RESET}"
echo ""

# ── Install dir ─────────────────────────────────────────────────────────────
INSTALL_DIR="$HOME/.computehive"
mkdir -p "$INSTALL_DIR"

# ── Check / install Node.js ─────────────────────────────────────────────────
if ! command -v node &>/dev/null; then
  echo -e "${YELLOW}  ! Node.js not found. Installing...${RESET}"
  if [[ "$OSTYPE" == "darwin"* ]]; then
    if command -v brew &>/dev/null; then
      brew install node
    else
      echo -e "${RED}  ✗ Homebrew not found. Install Node.js from https://nodejs.org${RESET}"
      exit 1
    fi
  else
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt-get install -y nodejs
  fi
fi
echo -e "${GREEN}  ✓ Node.js $(node --version)${RESET}"

# ── Download setup.js and daemon.js ─────────────────────────────────────────
BROKER_URL="${BROKER:-https://computehive.net}"

echo -e "  → Downloading daemon files..."
curl -fsSL "${BROKER_URL}/daemon.js"  -o "$INSTALL_DIR/daemon.js"
curl -fsSL "${BROKER_URL}/setup.js"   -o "$INSTALL_DIR/setup.js"
chmod +x "$INSTALL_DIR/setup.js"

echo -e "${GREEN}  ✓ Files downloaded to $INSTALL_DIR${RESET}"
echo ""

# ── Run setup wizard ─────────────────────────────────────────────────────────
echo -e "  → Launching setup wizard..."
echo ""
node "$INSTALL_DIR/setup.js" "$@"
