#!/bin/bash

source logging.sh
source config.sh


# begin initialization
initialization() {
    log "Create Pods."
    ./pod_manager.sh create

    log "Load probe orchestrator."
    ./probe_manager.sh create
}
# end initialization

# begin experiment
experiment() {
    log "Phase 1. Generate traffic ($PHASE_1_NUM_TRAFFIC_ITERATIONS iterations)."
    ./generate_traffic.sh  $PHASE_1_NUM_TRAFFIC_ITERATIONS

    log "Inject failures."
    ./inject_failures.sh start

    log "Phase 2. Generate traffic ($PHASE_2_NUM_TRAFFIC_ITERATIONS iterations)."
    ./generate_traffic.sh  $PHASE_2_NUM_TRAFFIC_ITERATIONS
    
    ./inject_failures.sh stop
    log "Stop failures."

    log "Phase 3. Generate traffic ($PHASE_3_NUM_TRAFFIC_ITERATIONS iterations)."
    ./generate_traffic.sh  $PHASE_3_NUM_TRAFFIC_ITERATIONS
}
# end experiment

# begin cleanup
cleanup() {
    ./probe_manager.sh delete
    ./pod_manager.sh delete
}
# end cleanup

usage() {
    echo "Usage: $0 [-i] [-e] [-c] [-a]"
    echo "  -i  Run Initialization"
    echo "  -e  Run Experiment"
    echo "  -c  Run Cleanup"
    echo "  -a  Run All (default if no flags provided)"
    exit 1
}

RUN_INIT=false
RUN_EXP=false
RUN_CLEAN=false

if [ $# -eq 0 ]; then
    RUN_INIT=true
    RUN_EXP=true
    RUN_CLEAN=true
fi

while getopts "ieca" opt; do
  case $opt in
    i) RUN_INIT=true ;;
    e) RUN_EXP=true ;;
    c) RUN_CLEAN=true ;;
    a) 
       RUN_INIT=true
       RUN_EXP=true
       RUN_CLEAN=true 
       ;;
    *) usage ;;
  esac
done


trap cleanup SIGINT

log "Starting script execution."

if [ "$RUN_INIT" = true ]; then
    initialization
fi

if [ "$RUN_EXP" = true ]; then
    experiment
fi

if [ "$RUN_CLEAN" = true ]; then
    cleanup
fi

log "Script execution finished."