#!/usr/bin/env bash
# Pylon node installer — served at https://pylond.run/install.sh
#
#   curl -fsSL https://pylond.run/install.sh | sh -s -- --token <ENROLL_TOKEN>
#
# Connects this machine to Pylon: installs Docker if missing, then runs the
# node-agent (dials out, holds the reverse tunnel, heartbeats) and the
# container-driver (runs game/VPS containers via the local Docker) from the
# official image. No inbound ports are opened — the node dials OUT.
set -eu

FLEET="${PYLON_FLEET:-https://fleet.pylon.host}"
MESH="${PYLON_MESH:-https://mesh.pylon.host}"
IMAGE="${PYLON_IMAGE:-registry.pylon.host/pylon:latest}"
TOKEN=""
while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --token=*) TOKEN="${1#*=}"; shift ;;
    --fleet) FLEET="$2"; shift 2 ;;
    --mesh) MESH="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 1 ;;
  esac
done
[ -n "$TOKEN" ] || { echo "error: --token <ENROLL_TOKEN> is required (get one in the Pylon host panel → Nodes)"; exit 1; }
[ "$(id -u)" = "0" ] || { echo "error: run as root (sudo)"; exit 1; }

echo "==> Pylon node install"
if ! command -v docker >/dev/null 2>&1; then
  echo "==> installing Docker"
  curl -fsSL https://get.docker.com | sh
fi

INSTALL_DIR=/opt/pylon
mkdir -p "$INSTALL_DIR"
cat > "$INSTALL_DIR/docker-compose.yml" <<YAML
name: pylon-node
services:
  node-agent:
    image: ${IMAGE}
    command: ["node-agent"]
    network_mode: host
    restart: unless-stopped
    environment:
      - NODE_FLEET_ENDPOINT=${FLEET}
      - NODE_MESH_ENDPOINT=${MESH}
      - NODE_ENROLL_TOKEN=${TOKEN}
      - NODE_HOSTNAME=$(hostname)
      - NODE_WORKLOAD_HOST=127.0.0.1
  container-driver:
    image: ${IMAGE}
    command: ["container-driver"]
    restart: unless-stopped
    environment:
      - CONTAINER_RUNTIME=bollard
      - CONTAINER_DRIVER_BIND=0.0.0.0:50058
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - "127.0.0.1:50058:50058"
YAML

echo "==> pulling ${IMAGE}"
docker pull "$IMAGE"
echo "==> starting node services"
docker compose -f "$INSTALL_DIR/docker-compose.yml" up -d

echo
echo "✅ Node connected to Pylon. It will appear in your host panel → Nodes within a few seconds."
echo "   Manage: docker compose -f $INSTALL_DIR/docker-compose.yml [logs|down|pull]"
