#!/bin/bash
#
# SPHERE experiment weave — Run/Stop orchestrator (auto-generated by LoomAI).
#
EXPERIMENT_NAME="${EXPERIMENT_NAME:-${1:-edgeids}}"
EXPERIMENT_NAME=$(echo "$EXPERIMENT_NAME" | tr 'A-Z' 'a-z' | sed 's/[^a-z0-9]//g')
if [ -z "$EXPERIMENT_NAME" ]; then
  echo "ERROR: EXPERIMENT_NAME not set" >&2
  exit 1
fi
SCRIPT="$(dirname "$0")/experiment.py"

cleanup() {
  echo ""
  echo "### PROGRESS: Stop requested — tearing down..."
  python3 "$SCRIPT" stop "$EXPERIMENT_NAME" 2>&1 || true
  echo "### PROGRESS: Done."
  exit 0
}
trap cleanup SIGTERM SIGINT

if ! python3 "$SCRIPT" start "$EXPERIMENT_NAME"; then
  echo "ERROR: Failed to bring up experiment"
  exit 1
fi

echo "### PROGRESS: Up. Monitoring (click Stop to tear down)..."
while true; do
  if ! python3 "$SCRIPT" monitor "$EXPERIMENT_NAME"; then
    echo "ERROR: Monitor detected a problem"
    exit 1
  fi
  sleep 60 &
  wait $! 2>/dev/null || true
done
