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

set -eu

## Params

#submit_cmd="sbatch -A $(/usr/sbin/my_project.py -l 2>&1 | head -1 | cut -d " " -f 3- | cut -c 5-) --constraint=GENOA --time=00:15:00 -N 1 -n 1 -c 8"  # to launch on Adastra /!\ Not working rn, since jobs don't have internet access
submit_cmd=""  # to launch directly
#base_args="-arch_dir arch_local -arch local-gfortran"  # to use local arch
base_args="-arch local-gfortran-parallel"


## End params

local=$(pwd)
mkdir -p test_logs

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

    # Create test args
    local args="$base_args -rad $rad -parallel $parallel -netcdf 0 -veget $veget $xios $lmdzrev $cosp"
    # trim
    args=$(echo "$args" | xargs)

    local logfile="$local/test_logs/$args.out"
    if [[ -f $logfile ]]; then return; fi  # ALready exists = test already ran
    echo "Testing $args"

    # Create temp folder
    mkdir -p "test_logs/${args// /_}_$$" && cd "test_logs/${args// /_}_$$"
    cp ../../install_lmdz.sh .

    # shellcheck disable=SC2086
    local test_cmd="$submit_cmd ./install_lmdz.sh -name LMDZ $args"
    if ! $test_cmd > "$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 {
    cd "$local"
    for parallel in "none" "mpi_omp"; do
    for rad in "oldrad" "rrtm" "ecrad"; 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 ""; do
    for cosp in "" "-cosp v1" "-cosp v2"; do
        do_one_test
    done
    done
    done
    done
    done
    done
}

function display_results {
    cd "$local/test_logs"
    echo "Success=o, Failure=XXX, non-breaking error=/!\\"
    echo "INSTALL  BENCH  NAME"
    for fname in *.out; do
        if [[ $(tail -n 1 -- "$fname") = " Everything is cool" ]]; then
            if grep -q "Error" < "$fname"; then
                    echo "   o      /!\\   $fname"
                else
                    echo "   o       o    $fname"
                fi
        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
