#!/bin/sh
set -e

# SKIP_K3S=1 — bypass k3s/soul-demo startup and go straight to neuron-web.
# Used by the dev CI smoke test where the container runtime doesn't support
# the kernel capabilities k3s requires (overlayfs / privileged mode).
if [ "${SKIP_K3S:-0}" = "1" ]; then
  echo "[entrypoint] SKIP_K3S=1: starting neuron-web directly (no k3s/soul-demo)."
  exec /usr/local/bin/neuron-web
fi

echo "[entrypoint] Starting k3s server (embedded soul-demo orchestrator)..."

# k3s server — single-node mode, disable unused components
# --disable traefik,servicelb: we don't need an ingress or LB
# --disable metrics-server: saves ~50MB RAM
# --write-kubeconfig-mode=644: allow non-root reads
# --data-dir: use the pre-chowned dir
k3s server \
  --disable traefik \
  --disable servicelb \
  --disable metrics-server \
  --write-kubeconfig-mode=644 \
  --data-dir /var/lib/rancher/k3s \
  --node-name soul-node &

K3S_PID=$!

echo "[entrypoint] Waiting for k3s to become ready..."
until k3s kubectl get nodes --no-headers 2>/dev/null | grep -q "Ready"; do
  sleep 2
done
echo "[entrypoint] k3s ready. soul-demo Deployment will be applied automatically from manifests."

# Wait for soul-demo pod to be Running before starting neuron-web
echo "[entrypoint] Waiting for soul-demo pod..."
until k3s kubectl get pods -l app=soul-demo --no-headers 2>/dev/null | grep -q "Running"; do
  sleep 3
done
echo "[entrypoint] soul-demo is running."

echo "[entrypoint] Starting neuron-web on port ${PORT:-8080}..."
exec /usr/local/bin/neuron-web
