#!/bin/bash

# Script to run experiments with logging and timing
# Override parameters using environment variables, e.g.:
#   NUM_RUNS=10 NUM_BINS=3 ./run_experiments.sh

# ============================================
# Configuration Parameters (override with env vars)
# ============================================

# Common parameters
CFLAGS_BASELINE="${CFLAGS_BASELINE:--O3 -march=native}"
CFLAGS_GCOMP="${CFLAGS_GCOMP:--O3 -march=native}"
CFLAGS_GRIFT="${CFLAGS_GRIFT:--O3 -march=native}"

BENCHMARKS="${BENCHMARKS:-matmult blackscholes}"
BACKENDS="${BACKENDS:-gradual_mono_closures gradual_mono_values gradual_guarded}"

# Baseline parameters
NUM_RUNS_BASELINE="${NUM_RUNS_BASELINE:-50}"

# Gradual typing parameters
NUM_BINS="${NUM_BINS:-5}"
NUM_SAMPLES="${NUM_SAMPLES:-5}"
NUM_RUNS="${NUM_RUNS:-3}"
ULIMIT="${ULIMIT:-6553600}"

# Logging
DEFAULT_LOG_FILE="experiments_mtoro_$(date +%Y%m%d_%H%M%S).log"
LOG_FILE="${LOG_FILE:-$DEFAULT_LOG_FILE}"

# ============================================
# Print configuration
# ============================================

echo "Configuration:"
echo "  CFLAGS_BASELINE:     $CFLAGS_BASELINE"
echo "  CFLAGS_GCOMP:        $CFLAGS_GCOMP"
echo "  CFLAGS_GRIFT:        $CFLAGS_GRIFT"
echo "  BENCHMARKS:          $BENCHMARKS"
echo "  BACKENDS:            $BACKENDS"
echo "  NUM_RUNS_BASELINE:   $NUM_RUNS_BASELINE"
echo "  NUM_BINS:            $NUM_BINS"
echo "  NUM_SAMPLES:         $NUM_SAMPLES"
echo "  NUM_RUNS:            $NUM_RUNS"
echo "  LOG_FILE:            $LOG_FILE"
echo "  Stack size (ulimit)  $ULIMIT"
echo ""

# ============================================
# Script execution
# ============================================

START_TIME=$(date +%s)

echo "Starting experiments at $(date)" | tee -a "$LOG_FILE"
echo "============================================" | tee -a "$LOG_FILE"

# Set stack size limit
ulimit -s $ULIMIT
echo "Setting stack size limit (ulimit) to $ULIMIT" | tee -a "$LOG_FILE"
echo "Current stack size limit:" | tee -a "$LOG_FILE"
ulimit -s | tee -a "$LOG_FILE"

# Function to log and execute commands
run_experiment() {
    local description="$1"
    shift
    echo "" | tee -a "$LOG_FILE"
    echo "Running: $description" | tee -a "$LOG_FILE"
    echo "----------------------------------------" | tee -a "$LOG_FILE"
    
    local cmd_start=$(date +%s)
    "$@" 2>&1 | tee -a "$LOG_FILE"
    local exit_code=${PIPESTATUS[0]}
    local cmd_end=$(date +%s)
    local cmd_duration=$((cmd_end - cmd_start))
    
    if [ $exit_code -eq 0 ]; then
        echo "✓ Completed in ${cmd_duration}s" | tee -a "$LOG_FILE"
    else
        echo "✗ Failed with exit code $exit_code after ${cmd_duration}s" | tee -a "$LOG_FILE"
        return $exit_code
    fi
}


# Run gcomp experiments
run_experiment "gcomp gradual typing" \
    python3 run_experiments.py \
    --compilers gcomp \
    --benchmarks $BENCHMARKS \
    --typechecking $BACKENDS \
    --cflags "$CFLAGS_GCOMP" \
    --num-bins "$NUM_BINS" \
    --num-samples "$NUM_SAMPLES" \
    --num-runs "$NUM_RUNS" \
&& echo "Done running gcomp" | tee -a "$LOG_FILE"

if [ $? -ne 0 ]; then
    echo "gcomp failed, exiting..." | tee -a "$LOG_FILE"
    exit 1
fi


# Calculate and display total time
END_TIME=$(date +%s)
TOTAL_DURATION=$((END_TIME - START_TIME))
HOURS=$((TOTAL_DURATION / 3600))
MINUTES=$(((TOTAL_DURATION % 3600) / 60))
SECONDS=$((TOTAL_DURATION % 60))

echo "" | tee -a "$LOG_FILE"
echo "============================================" | tee -a "$LOG_FILE"
echo "All experiments completed successfully!" | tee -a "$LOG_FILE"
echo "Total time: ${HOURS}h ${MINUTES}m ${SECONDS}s (${TOTAL_DURATION}s)" | tee -a "$LOG_FILE"
echo "Finished at $(date)" | tee -a "$LOG_FILE"
echo "Log saved to: $LOG_FILE" | tee -a "$LOG_FILE"
