#!/bin/bash
# NRP FABRIC SENSE — thin orchestrator
# Creates a FABRIC slice with a facility port, provisions a SENSE L2 path to
# NRP Nautilus, deploys a K8s pod, and tests end-to-end connectivity.
# All infrastructure logic lives in nrp_sense.py.

SLICE_NAME="${SLICE_NAME:-${1:-nrp-fabric-sense}}"
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

export NRP_FABRIC_SITE="${NRP_FABRIC_SITE:-STAR}"
export NRP_FACILITY_PORT="${NRP_FACILITY_PORT:-NRP-UCSD}"
export NRP_VLAN="${NRP_VLAN:-any}"
export FABRIC_NODE_IP="${FABRIC_NODE_IP:-192.168.1.3}"
export NRP_POD_IP="${NRP_POD_IP:-192.168.1.2}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="$SCRIPT_DIR/nrp_sense.py"

cleanup() {
  echo ""
  echo "### PROGRESS: Stop requested — tearing down SENSE path and FABRIC slice..."
  python3 -u "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  echo "### PROGRESS: Done."
  exit 0
}
trap cleanup SIGTERM SIGINT

echo "### PROGRESS: Starting NRP FABRIC SENSE experiment"
echo "  Slice:         $SLICE_NAME"
echo "  FABRIC site:   $NRP_FABRIC_SITE"
echo "  Facility port: $NRP_FACILITY_PORT"
echo "  VLAN:          $NRP_VLAN"
echo "  FABRIC node IP: $FABRIC_NODE_IP"
echo "  NRP pod IP:     $NRP_POD_IP"
echo ""

if ! python3 -u "$SCRIPT" start "$SLICE_NAME"; then
  echo "ERROR: Experiment setup failed"
  python3 -u "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  exit 1
fi

echo "### PROGRESS: Experiment running — click Stop to tear down."
while true; do
  if ! python3 -u "$SCRIPT" monitor "$SLICE_NAME"; then
    echo "ERROR: Monitor detected failure — cleaning up..."
    python3 -u "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
    exit 1
  fi
  sleep 60 &
  wait $! 2>/dev/null || true
done
