#!/bin/bash
#
# Hello FABRIC - Weave Orchestrator
#
# This script is the entry point when you click "Run" in the WebUI.
# It creates and provisions the slice, then waits for you to click Stop.
# When you click Stop, it deletes the slice and exits cleanly.
#

# Get the slice name from the SLICE_NAME env var (set by weave.json args),
# or from the first command-line argument, or use "hello-fabric" as default.
SLICE_NAME="${SLICE_NAME:-${1:-hello-fabric}}"

# Clean the name: only letters, numbers, and hyphens allowed
SLICE_NAME=$(echo "$SLICE_NAME" | sed 's/[^a-zA-Z0-9-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
if [ -z "$SLICE_NAME" ]; then
  echo "ERROR: SLICE_NAME not set" >&2
  exit 1
fi

# The Python script that manages the slice lifecycle
SCRIPT="hello_fabric.py"

# --- Graceful shutdown handler ---
# When you click "Stop" in the WebUI, this function runs.
# It tells the Python script to delete the slice, then exits cleanly.
cleanup() {
  echo ""
  echo "### PROGRESS: Stop requested — cleaning up..."
  python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  echo "### PROGRESS: Done."
  exit 0
}

# Install the shutdown handler (catches the Stop button signal)
trap cleanup SIGTERM SIGINT

# --- Start the slice ---
if ! python3 "$SCRIPT" start "$SLICE_NAME"; then
  echo "ERROR: Failed to start slice"
  exit 1
fi

# --- Wait for Stop ---
# The slice is ready. Wait indefinitely until the user clicks Stop.
# "sleep infinity & wait $!" allows SIGTERM to be handled immediately.
echo "### PROGRESS: Slice '$SLICE_NAME' is ready (click Stop to tear down)..."
sleep infinity &
wait $! 2>/dev/null || true
