#!/bin/bash

SLICE_NAME="${SLICE_NAME:-${1:-sequence-experiment-lab}}"
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

SCRIPT="sequence_experiment_lab.py"

cleanup() {
  echo ""
  echo "### PROGRESS: Stop requested - cleaning up..."
  python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  echo "### PROGRESS: Done."
  exit 0
}

trap cleanup SIGTERM SIGINT

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

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