#!/bin/bash

# Compile
(cd ./sources/amip-forcing/src/fortran && make clean)
(cd ./sources/amip-forcing/src/fortran && make oasis)
(cd ./sources/amip-forcing/src/fortran && make)

if [ $# -ne 1 ]; then
    echo 'Running tests WITHOUT the large test. Use ./run_tests.sh 1 to run all tests including the large test.'
else
    echo 'Running tests WITH the large test.'
fi

cd ./tests

echo '*****************************************************************'
echo "Running tests..."
# Clean old tests
rm -rf ./work_*

# Standard test
./run_example.sh fortran 4 1990-01-01 1991-01-01 0 > /dev/null
./run_example.sh python 4 1990-01-01 1991-01-01 0 > /dev/null
# Secuential years
./run_example.sh fortran 4 1990-01-01 1994-01-01 0 > /dev/null
./run_example.sh python 4 1990-01-01 1994-01-01 0 > /dev/null
# Fixed year
./run_example.sh fortran 4 1995-01-01 1998-01-01 1 > /dev/null
./run_example.sh python 4 1995-01-01 1998-01-01 1 > /dev/null
# Years before 1900 (leap-year)
./run_example.sh fortran 4 1892-01-01 1894-01-01 0 > /dev/null
./run_example.sh python 4 1892-01-01 1894-01-01 0 > /dev/null
# All years between 1979 and 2014
if [ $1 ]; then
    ./run_example.sh fortran 4 1979-01-01 2014-01-01 0 > /dev/null
    ./run_example.sh python 4 1979-01-01 2014-01-01 0 > /dev/null
fi

echo '*****************************************************************'
echo "Checking results..."

fortran_wildcard=./work_fortran*
i=0
for dir in $fortran_wildcard; do
    fortran_dirs[$i]="$dir"
    ((i++))
done

python_wildcard=./work_python*
i=0
for dir in $python_wildcard; do
    python_dirs[$i]="$dir"
    ((i++))
done

len=$i
for ((i = 0; i < len; i++)); do
    echo 'Checking '${python_dirs[$i]}' vs '${fortran_dirs[$i]}
    cdo diff ${python_dirs[$i]}/AMIP_sic_AMIPFORC_01.nc ${fortran_dirs[$i]}/AMIP_sic_AMIPFORC_01.nc && : || exit 1
    cdo diff ${python_dirs[$i]}/AMIP_sst_AMIPFORC_01.nc ${fortran_dirs[$i]}/AMIP_sst_AMIPFORC_01.nc && : || exit 1
    cdo diff ${python_dirs[$i]}/A_Ice_frac_IFS_MOCK_01.nc ${fortran_dirs[$i]}/A_Ice_frac_IFS_MOCK_01.nc && : || exit 1
    cdo diff ${python_dirs[$i]}/A_SST_IFS_MOCK_01.nc ${fortran_dirs[$i]}/A_SST_IFS_MOCK_01.nc && : || exit 1
    cat ${python_dirs[$i]}/IFS_mock.out_* > ${python_dirs[$i]}/IFS_mock__all.out
    cat ${fortran_dirs[$i]}/IFS_mock.out_* > ${fortran_dirs[$i]}/IFS_mock__all.out
    diff ${fortran_dirs[$i]}/IFS_mock__all.out ${python_dirs[$i]}/IFS_mock__all.out && : || exit 1
done

echo "Tests PASSED"
