#!/bin/bash

# Funzione per lanciare il comando di confronto
run_comparison() {
    file1=$1
    file2=$2
    output_dir=$3

    # Assicurati che la directory di output esista
    mkdir -p "$output_dir"
    
    # Nome del file di output
    output_file="$output_dir/$(basename "$file1").txt"

    # Esegui il comando di confronto e salva direttamente l'output
    ./compare-precision.sh "$file1" "$file2" "$output_file"
}

# Funzione per esplorare le directory e fare i confronti solo se il nome del test è uguale (rimuovendo .havoc)
explore_directories() {
    root_dir=$1
    compare_dirs=($root_dir/def-nonrel $root_dir/pos-nonrel $root_dir/def-rel $root_dir/pos-rel)
    no_havoc_dir=$root_dir/no-havoc

    for compare_dir in "${compare_dirs[@]}"; do
        for file1 in "$compare_dir"/linux*; do
            test_name1=$(basename "$file1")

            echo "File havoc $test_name1"

            for file2 in "$no_havoc_dir"/linux*; do
                test_name2=$(basename "$file2")
                
                # Controlla che il nome del test (senza .havoc) sia uguale
                if [[ "$test_name1" == "$test_name2" ]]; then

                    echo "File classic $test_name2"
                    output_dir="$compare_dir/clam-diff"
                    run_comparison "$file1" "$file2" "$output_dir"
                fi
            done
        done
    done
}

# Esplora la directory "output/int"
explore_directories "../output/int"

# Esplora la directory "output/pk-ap-pplite"
#explore_directories "../output/pk-ap-pplite"

# Esegue lo script Python su tutti i file generati nelle cartelle clam-diff
find ../output -type d -name "clam-diff" | while read clam_diff_dir; do
    output_file="$clam_diff_dir/clam-diff-percentage.json"
    python3 calculate-loss-clam-diff.py "$clam_diff_dir"/*.txt "$output_file"
    output_file="$clam_diff_dir/clam-diff-results.json"
    python3 clam-diff-stats-to-json.py "$clam_diff_dir"/*.txt "$output_file"
done

echo "Comparisons completed and loss calculations executed."