#!/bin/bash
NTHREADS=1
[[ $# -eq 1 ]] && NTHREADS=$1
printf "%d" "$NTHREADS" >& /dev/null || { echo "error: given nr of threads must be an integer"; exit 255; }

export DIR_ORTHOLOGER=${DIR_ORTHOLOGER:="$(cd ../ && pwd)"}
source $DIR_ORTHOLOGER/bin/version.sh
logfile="run_test_all_${OP_VERSION_HASH}.log"

export TEST_NCMPFAIL=0
export TEST_NFAILED=0
export TEST_NPOOR=0
export TEST_NNEAR=0
export TEST_NOK=0
export TEST_T=0
echo
echo "Running all tests - this will take some time depending on hardware."
echo "Using 8 cores it takes roughly 15 minutes."
echo "Default settings is read from (if it exists):"
echo "  $DIR_ORTHOLOGER/etc/orthologer_conf.sh"
echo
echo "Logfile at $logfile"
echo

TTOT=0
NBAD=0
# set conservative nr of threads
nthreads=0
{
    #-------------------------------------------------
    cd proj_prot >& /dev/null
    ./setup.sh $nthreads >& setup.log
    ./run_test.sh || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    ./run_test_localmap.sh || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    cd - >& /dev/null

    #-------------------------------------------------

    cd proj_tree >& /dev/null
    ./setup.sh $nthreads >& setup.log
    ./run_test.sh || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    cd - >& /dev/null

    #-------------------------------------------------
    cd proj_map >& /dev/null
    ./setup.sh $nthreads >& setup.log
    ./run_test.sh              || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    ./run_test_busco_auto.sh   || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    ./run_test_busco.sh        || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    #./run_test_virus.sh        || NBAD=$((NBAD+1))
    ./run_test_with_busco.sh   || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))
    
    # Temp remove as it takes a long time
    #./run_test_with_subset.sh  || NBAD=$((NBAD+1))
    #TTOT=$(( TTOT+TEST_T ))

    cd - >& /dev/null

    #-------------------------------------------------
    cd proj_odbmap >& /dev/null
    ./setup.sh $nthreads >& setup.log
    ./run_test.sh              || NBAD=$((NBAD+1))
    TTOT=$(( TTOT+TEST_T ))

    cd - >& /dev/null

    #-------------------------------------------------

    ec=0
    NBAD=$(( TEST_NCMPFAIL + TEST_NFAILED ))
    if (( NBAD == 0 )); then
        echo "ALL test(s) OK"
        exit 0
    fi
    if (( TEST_NOK == 0 )); then
        echo "OK $TEST_NOK test(s)"
    fi
    if (( TEST_NCMPFAIL > 0 )); then
        echo "failed $TEST_NCMPFAIL comparision(s) with reference(s)"
        ec=255
    fi
    if (( TEST_NFAILED > 0 )); then
        echo "FAILED $TEST_NFAILED test(s)"
        ec=255
    fi
    echo "Total time elapsed is $TTOT secs"
    exit $ec
} >& $logfile


