#!/bin/bash
############################################################
# Handle CTRL+C                                            #
############################################################
cleanup() {
    echo "Terminating script and its subscripts..."
    pkill -P $$
    exit 1
}

trap cleanup SIGINT
############################################################


############################################################
# Main program                                             #
############################################################
BDIR="../downloaded_benchmarks"
SUBDIRS="wcet drivers"
echo "Running the analysis on all the files in $BDIR "

WARNINGS='--crab-disable-warnings'
PRINT_INVS='--crab-print-invariants=false'

ANALYSIS_TYPES=("int" "pk-ap-pplite")

rm -rf TIMEINFO
mkdir TIMEINFO


for analysis in "${ANALYSIS_TYPES[@]}"; do
    if [ "$analysis" == "int" ]; then
        HAVOC_TYPES=("pos-nonrel" "def-nonrel")
    else
        HAVOC_TYPES=("pos-rel" "def-rel" "def-nonrel" "pos-nonrel")
    fi

    for SUBDIR in $SUBDIRS
    do
        for FILE in "$BDIR"/$SUBDIR/*.c "$BDIR"/$SUBDIR/*.i;
        do
            if [ ! -f "$FILE" ]; then
                continue
            fi
            BFILE=$(basename "$FILE")

            # Run no_havoc analysis once per analysis type and file
            OUTPUT_DIR="TIMEINFO/$analysis/nohavoc"
            mkdir -p "$OUTPUT_DIR"
            touch "$OUTPUT_DIR/TIMEINFO"
            echo "$BFILE" >> "$OUTPUT_DIR/TIMEINFO"
            echo "Running nohavoc the analysis on $FILE"
            clam.py --crab-dom=$analysis --inline \
            $WARNINGS $PRINT_INVS \
            "$FILE" > "$OUTPUT_DIR/$BFILE.out" 2>&1
            my_clamtime="$(grep '^BRUNCH_STAT Clam ' "$OUTPUT_DIR/$BFILE.out" | cut -d' ' -f3)"
            echo -e "\tClam time $my_clamtime" >> "$OUTPUT_DIR/TIMEINFO"

            for havoc in "${HAVOC_TYPES[@]}"; do
                OUTPUT_DIR="TIMEINFO/$analysis/$havoc"
                mkdir -p "$OUTPUT_DIR"
                touch "$OUTPUT_DIR/TIMEINFO"
                echo "$BFILE" >> "$OUTPUT_DIR/TIMEINFO"
                echo "Running havoc the analysis on $FILE"
                clam.py --crab-dom=$analysis --inline \
                --crab-havoc-analysis=$havoc \
                $WARNINGS $PRINT_INVS \
                "$FILE" > "$OUTPUT_DIR/$BFILE.out" 2>&1
                my_clamtime="$(grep '^BRUNCH_STAT Clam ' "$OUTPUT_DIR/$BFILE.out" | cut -d' ' -f3)"
                echo -e "\tClam time $my_clamtime" >> "$OUTPUT_DIR/TIMEINFO"
            done
        done
    done
done

echo "All of the analyses have been run"
echo "The time information is stored in the $OUTPUT_DIR directory"
############################################################
