#!/bin/bash
# Weave Template (Claude) — Thin orchestrator
# Runs a single-VM experiment: measures CPU/memory/network utilization, collects results.
# All logic lives in experiment.py.

SLICE_NAME="${SLICE_NAME:-${1:-claude-exp}}"
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

DURATION="${DURATION:-60}"
DATA_DIR="${DATA_DIR:-data}"

export SLICE_NAME DURATION DATA_DIR

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

# Graceful shutdown: save data, delete slice, exit cleanly
# Triggered by WebUI Stop button (sends SIGTERM)
cleanup() {
  echo ""
  echo "### PROGRESS: Stop requested — saving data and cleaning up..."
  # Try to collect whatever data is available before tearing down
  python3 "$SCRIPT" collect "$SLICE_NAME" 2>&1 || true
  python3 "$SCRIPT" analyze "$SLICE_NAME" 2>&1 || true
  python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  echo "### PROGRESS: Stopped. Data saved to $DATA_DIR/."
  exit 0
}
trap cleanup SIGTERM SIGINT

# Print run summary
echo "### PROGRESS: Starting experiment"
echo "  Slice: $SLICE_NAME"
echo "  Duration: ${DURATION}s"
echo "  Data dir: $DATA_DIR"
echo ""

# Step 1: Create slice and run the experiment
echo "### PROGRESS: Running — creating slice and starting experiment..."
if ! python3 "$SCRIPT" start "$SLICE_NAME"; then
  echo "ERROR: Experiment failed"
  python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  exit 1
fi

# Step 2: Collect data from the VM
echo "### PROGRESS: Running — collecting data..."
if ! python3 "$SCRIPT" collect "$SLICE_NAME"; then
  echo "ERROR: Failed to collect data"
  python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true
  exit 1
fi

# Step 3: Analyze results
echo "### PROGRESS: Running — analyzing results..."
if ! python3 "$SCRIPT" analyze "$SLICE_NAME"; then
  echo "WARNING: Analysis failed (data may still be in $DATA_DIR)"
fi

# Step 4: Delete the slice and finish
echo "### PROGRESS: Cleaning up slice..."
python3 "$SCRIPT" stop "$SLICE_NAME" 2>&1 || true

echo "### PROGRESS: Done — experiment complete. Data saved to $DATA_DIR/."
exit 0
