#!/bin/bash


cd $( dirname $0 )

## Set defaults
##---------------------------------------------------
TRUST_MAIN_DIR=$PWD
TRUST_FLAG_DEBUG=0; TRUST_FLAG_PROD=0; TRUST_FLAG_HELP=0
## No update on SVN directories & 'FAILED' result for 'Unknown error' )
TRUST_SVN_ACTION='svn status'
TRUST_FLAG_RESULT='FAILED'; TRUST_FLAG_ERROR=0

xios_mode='--full'; stdout_redir='>&'
rev=$( svn info | awk '(NR == 9) {print $NF}' )


## Get options (replacing initials settings)
##---------------------------------------------------
while [ $# -ne 0 ]; do

    case $1 in
	'-a'|'--archive') TRUST_CFG_FORC=$2; shift 2;; '-b'|'--branch' ) TRUST_SVN_BRANCH=$2; shift 2;;
	'-d'|'--debug'  ) TRUST_FLAG_DEBUG=1 ; shift  ;; '-e'|'--email'  ) TRUST_TEST_MAILING=$2; shift 2;;
	'-f'|'--forcdir') TRUST_DIR_FORC=$2; shift 2;; '-j'|'--job'    ) TRUST_COMPILE_NPROC=$2; shift 2;;
	'-h'|'--help'   ) TRUST_FLAG_HELP=1 ; shift  ;; '-m'|'--machine') TRUST_MAIN_HPCC=$2; shift 2;;
	'-n'|'--newconf') TRUST_CFG_NEW=$2; shift 2;; '-r'|'--refconf') TRUST_CFG_REF=$2; shift 2;;
	'-t'|'--time'   ) TRUST_JOB_TIMEOUT=$2; shift 2;; '-p'|'--prod'   ) TRUST_FLAG_PROD=1 ; shift  ;;
	'-u'|'--user'   ) TRUST_MAIN_USER=$2; shift 2;; '-v'|'--version') TRUST_SVN_REV=$2; shift 2;;
	'-w'|'--workdir') TRUST_DIR_WORK=$2; shift 2;; "*"             ) TRUST_FLAG_HELP=1 ; shift  ;;
    esac

done


## Initialization (HPC & user environment)
##---------------------------------------------------
if [[ ! -e cfg/${TRUST_MAIN_USER}.cfg || ! -e cfg/${TRUST_MAIN_HPCC}.cfg || ${TRUST_FLAG_HELP} -eq 1 ]]; then
    cat ./inc/trusting_help.txt

    if [ ${TRUST_FLAG_HELP} -eq 0 ]; then
	printf "\n\n\033[0;33m"
	printf "At least one configuration (arch or user) file is missing or misspelled:"
	printf "\t'%s'.cfg\t'%s'.cfg" ${TRUST_MAIN_USER} ${TRUST_MAIN_HPCC}
	printf "\033[0m"
    fi

    printf "\n\nContent of 'config' folder:"
    find config -name *.cfg | cut -d/ -f2 \
	| xargs -n 4 printf "%-25s\t%-25s\t%-25s\n"
    exit 1
else
    . ./inc/trusting.env && . ./inc/trusting_func.sh

    ## DEBUG option to speed up & expand verbosity of compilation
    [ ${TRUST_FLAG_DEBUG} -eq 1 ] && { set -vx; xios_mode=''; stdout_redir='>'; }

    ## If -v|--version option has been set, modify default SVN action on directories
    if   [ $( echo ${TRUST_SVN_REV} | grep  "HEAD\|up\|update"                     ) ]; then
	TRUST_SVN_ACTION='svn update -r HEAD'
    elif [ $( echo ${TRUST_SVN_REV} | grep -o '{[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}}' ) ]; then
	TRUST_SVN_ACTION='svn update -r     '$( echo ${TRUST_SVN_REV} | grep -o '{[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}}' )
    elif [ $( echo ${TRUST_SVN_REV} | grep -o '[0-9]*'                             ) ]; then
	TRUST_SVN_ACTION='svn update -r     '$( echo ${TRUST_SVN_REV} | grep -o '[0-9]*' )
    fi

fi


## Display contextual summary of trusting test
##---------------------------------------------------
echo

if [ -t 0 ]; then cat ./inc/banner.txt; else cat ./inc/banner.html; fi

echo
echo '****************************************************************************************************'
echo '*                                                                                                  *'
echo '*                           NEMO Trusting (Continuous Integration Tool)                            *'
echo "*                                             ver.$rev                                             *"
echo '*                                                                                                  *'
echo '****************************************************************************************************'
echo
printf "\t§ Testing configuration\t\t%s based on %s\n" ${TRUST_CFG_NEW} ${TRUST_CFG_REF}
printf "\t§ SVN working copy\t\t%s/%s\n"               ${TRUST_DIR_WORK} ${TRUST_SVN_BRANCH}
printf "\t§ Benchmark folder\t\t%s\n"       	       ${TRUST_DIR_STORE}
printf "\t§ (Super)Computer\t\t%s\n" 		       ${TRUST_MAIN_HPCC}
printf "\t§ User installation\t\t%s\n\n" 	       ${TRUST_MAIN_USER}


## Make timestamped directory with messenger files
##---------------------------------------------------
print_step 'Timestamped testing directory'

mkdir -p ${TRUST_DIR_SCRATCH} ${TRUST_DIR_STORE}
cd       ${TRUST_DIR_SCRATCH}
echo     ${TRUST_DIR_SCRATCH}

init_files

get_date


## Get SVN revision on XIOS & NEMO essentials directories
##---------------------------------------------------
print_step "SVN action on NEMO directories: ${TRUST_SVN_ACTION}"

get_nemo_rev


## Check softwares versions (after sourced arch environment)
##---------------------------------------------------
print_step 'Get testing environement'

get_soft_rel

cat model.log | awk '{printf "%-20s %s %s\n", $1, $2, $3}'
env | sort > env.log


## XIOS compilation from scratch
##---------------------------------------------------
print_step 'Compile XIOS'

cd ${TRUST_DIR_XIOS}

eval ./make_xios ${xios_mode} --arch ${TRUST_MAIN_HPCC} --job ${TRUST_COMPILE_NPROC} \
    ${stdout_redir} /dev/null

[ ! -e lib/libxios.a ] && get_out 1 || echo 'Success'


## NEMO compilation from scratch
##---------------------------------------------------
print_step "Compile ${TRUST_CFG_REF} configuration"

cd ${TRUST_DIR_NEMOGCM}/CONFIG

if [[ -d ${TRUST_CFG_NEW} && ${TRUST_FLAG_DEBUG} -eq 0 ]]; then
    ./makenemo -n ${TRUST_CFG_NEW} clean_config \
	> /dev/null <<EOF
y
EOF
fi

eval ./makenemo -n ${TRUST_CFG_NEW} -r ${TRUST_CFG_REF} \
                -m ${TRUST_MAIN_HPCC} -j ${TRUST_COMPILE_NPROC} \
                   ${TRUST_CFG_KEY_ADD} ${TRUST_CFG_KEY_DEL}    \
    ${stdout_redir} /dev/null

[ ! -e ${TRUST_CFG_NEW}/BLD/bin/nemo.exe ] && get_out 2 || echo 'Success'


## Get all inputs for running
##---------------------------------------------------
print_step 'Set job (copying or extracting inputs)'

cd ${TRUST_DIR_SCRATCH}

get_inputs

cp   ${TRUST_DIR_NEMOGCM}/CONFIG/${TRUST_CFG_NEW}/cpp_* .
find ${TRUST_DIR_NEMOGCM}/CONFIG/${TRUST_CFG_NEW}/EXP00   \
    -regex '.*\(_cfg\|.in\|opa\|_ref\|.xml\)' \
    -exec  cp {} . \;


## Check inputs
##---------------------------------------------------
print_step 'Compare inputs'

diff_inputs


## Job submission & computation
##---------------------------------------------------
print_step 'Submit job'

## Copy the submitting script to testing folder
cp ${TRUST_JOB_SCRIPT} ${TRUST_DIR_SCRATCH}
TRUST_JOB_ID=$( eval ${TRUST_JOB_SUBMIT} )

[ $? -ne 0 ] && get_out 4 || printf "Success (job ID %s)\n" ${TRUST_JOB_ID}

print_step 'Pending job'

job_pending

print_step 'Job finished'


## Check job state & get computation performances if succeeded
##---------------------------------------------------
print_step 'Test job state'

if [[ ! -e time.step || $( grep 'E R R O R' ocean.output ) ]]; then
    get_out 5
else
    echo 'Success' ## Must be reviewed
fi

print_step 'Get job performances'

get_time

get_memy


## Check outputs
##---------------------------------------------------
TRUST_FLAG_RESULT='OK' ## 'OK' by default

print_step 'Compare outputs'

diff_results

print_step 'Compare restarts'

diff_restarts

[ $TRUST_RESULT == 'FAILED' ] && get_out 8


## End, at least nothing major has changed ;-)
##---------------------------------------------------
get_out 0
