#!/bin/bash
# Test LMDZ compilation in various situations

set -eu

mkdir -p test_logs

function do_one_test {
    # Perform one test, if the log file doesn't already exist

    # Create test args
    args="-arch_dir arch_local -arch local-gfortran"
    if [[ ! $parallel = "none" ]]; then
        args="$args-parallel"
    fi
    args="$args -rad $rad -parallel $parallel -netcdf 0 -veget $veget $xios $lmdzrev"
    # trim
    args=$(echo "$args" | xargs)

    logfile="test_logs/$args.out"
    if [[ -f $logfile ]]; then return; fi
    echo "Testing $args"
    rm -rf LMDZ


    # shellcheck disable=SC2086
    if ! ./install_lmdz.sh -name LMDZ $args > "$logfile" 2>&1; then
        # Check bench success if bench
        if (grep -q "EXECUTION DU BENCH" < "$logfile") && (! grep -q "Everything is cool" < "$logfile"); then
            echo "/!\\ Bench FAILED /!\\"
        else
            echo "/!\\ Install FAILED /!\\"
        fi
    fi
}

function run_all_tests {
    for parallel in "none" "mpi_omp"; do
    for rad in "oldrad" "rrtm"; do
    for veget in "none" "orch2.0" "orch2.2"; do
    for xios in "" "-xios"; do
    if [[ $xios = "-xios" && $parallel = "none" ]]; then continue; fi
    for lmdzrev in "" "-r 4894"; do
        do_one_test
    done
    done
    done
    done
    done
}

function display_results {
    cd "test_logs"
    echo "Success=o, Failure=XXX"
    echo "INSTALL  BENCH  NAME"
    for fname in *; do
        if [[ $(tail -n 1 -- "$fname") = " Everything is cool" ]]; then
            echo "   o       o    $fname"
        else
            if grep -q "EXECUTION DU BENCH" < "$fname"; then
                echo "   o      XXX   $fname"
            else
                echo "  XXX           $fname"
            fi
        fi
    done
}

skip_tests=""
while (($# > 0)); do
    case $1 in
        "-s") skip_tests="y"; shift;;
    esac
done

if [[ -z $skip_tests ]]; then run_all_tests; fi
display_results
