#!/bin/bash


comments() {
    state=$1

    if [ $state == 'E R R O R' ]; then
	if [ -e ocean.output ]; then
	    last_time_step=$( cat ${TEST_DIR}/time.step | tr -d [:space:] )
	    STEP='nemo.exe crashed at '${last_time_step} && export STEP
	    line=$( grep -m1 "$state" ocean.output | tr -d '\n' )
	else
	    STEP='nemo.exe crashed at initialization'    && export STEP
	    return
	fi
    fi

    if [ $( diff -q env.log ${REFE_DIR}/env.log ) ]; then
	line=$( diff env.log ${REFE_DIR}/env.log  | tr -d '\n' )
    fi

    printf "Comments\n$line\n" | tee mesg_10_comments_${CFG_USER}_${CFG_ARCH}.txt
}

get_cpu_time() {
    # Portability !
    real_cpu_time=$( ${JOB_VIEW} ${JOB_ID} | awk 'END{print $9}' )
    printf "Real CPU time\n${real_cpu_time}\n" | tee mesg_09_realcputime_${CFG_USER}_${CFG_ARCH}.txt
}

diff_inputs() {
    mesg='Same'

    for file in inputs_list.txt $( ls namelist_* ) $( ls *.xml ); do
	diff $file ${REFE_DIR}/$file
	[ $? -ne 0 ] && mesg='Different'
    done

    printf "Input files\n$mesg\n" | tee mesg_08_inputfiles_${CFG_USER}_${CFG_ARCH}.txt
}

diff_restart() {
    last_time_step=$( cat ${REFE_DIR}/time.step | tr -d [:space:] )
    echo 'Last time step of standard run: '${last_time_step}

    if [ $( find ${TEST_DIR} -name "*${last_time_step}_restart*.nc" -print -quit ) ]; then
	base_name=$( find ${TEST_DIR} -name "*${last_time_step}_restart*.nc" -print -quit           \
	             | awk -F/ '{print $NF}' | sed "s/^\(.*\)$last_time_step\_.*/\1$last_time_step/" )

	for comp in restart restart_ice restart_trc; do
	    printf "${base_name}_${comp}.nc: "

	    nb_dom=$( find ${TEST_DIR} -name "${base_name}_${comp}_[0-9]*.nc" | wc -l | awk '{print $1}' )
	    if [ ${nb_dom} -gt 1 ]; then
		${NEMO_TRBD}/rebuild_nemo -t $NPROC ${base_name}_$comp ${nb_dom} > /dev/null
	    fi

	    cmp ${TEST_DIR}/${base_name}_$comp.nc ${REFE_DIR}/${base_name}_$comp.nc
	    if [ $? -ne 0 ]; then
		STATUS='FAILED'; STEP='Restart files different'
		printf "$CDO diffn\n"
		$CDO diffn ${TEST_DIR}/${base_name}_$comp.nc ${REFE_DIR}/${base_name}_$comp.nc 2> /dev/null
	    else
		printf "identical\n"
	    fi

	    \rm  ${TEST_DIR}/${base_name}_${comp}_[0-9]*.nc
	done

    else
	STATUS='FAILED'; STEP='No restart files found at last time step'
	printf "no restart files found for comparison\n"
    fi

    [ $STATUS == 'FAILED'] && get_out $STATUS $STEP
}

get_soft_rel() {
    for rel in $CDO $COMPILER $MPI $NETCDF; do
                                 arch_rel=$( echo $LOADEDMODULES | sed  "s#.*$rel/\([^:]*\).*#\1#" )
	[ -z "${arch_rel}"  ] && arch_rel=$( echo $PATH          | sed  "s#.*$rel/\([^/]*\).*#\1#" )
	[ $rel == $COMPILER ] && arch_rel=$( $rel --version      | grep -m1 -o ' [0-9.]* '         )
	echo $rel ${arch_rel} >> env.log
    done

    sed -n 3p env.log | sed 'i\Compiler'    > mesg_05_compiler_${CFG_USER}_${CFG_ARCH}.txt
    sed -n 4p env.log | sed 'i\MPI libs'    > mesg_06_mpi_${CFG_USER}_${CFG_ARCH}.txt
    sed -n 5p env.log | sed 'i\NetCDF libs' > mesg_07_netcdf_${CFG_USER}_${CFG_ARCH}.txt
}

get_nemo_rev() {
    svn_opt='status'

    # If -v|--version option has been set, modify svn command
    if [[    $( echo ${NEMO_VERS} | grep  "HEAD\|up\|update"   ) \
	  || $( echo ${NEMO_VERS} | tr -d '[:alpha:][:punct:]' )  ]]; then
	rev=$( echo ${NEMO_VERS} | tr -d '[:alpha:][:punct:]' ) || rev='HEAD'
	svn_cmd='svn update -r '$rev 
    else
	svn_cmd='svn '${svn_opt}
    fi

    rev=0
    for dir in ${DIR_XIOS}  ${NEMO_ARCH} ${NEMO_CONF} ${NEMO_ENGI} \
	       ${NEMO_EIOI} ${NEMO_EFCM} ${NEMO_TCMP} ${NEMO_TRBD}  ; do

	# For time being, just get revision number from XIOS
	if [ $dir == ${DIR_XIOS} ]; then
	    echo 'XIOS '$( svn info $dir | awk '(NR == 5) {print $NF}' ) >> env.log
	    continue
	fi

	${svn_cmd} $dir
	rev_loc=$( svn info $dir | awk '(NR == 5) {print $NF}' )
	(( ${rev_loc} >= $rev )) && rev=${rev_loc}
    done

    printf "NEMOGCM rev.\n$rev\n" > mesg_02_nemogcm_${CFG_USER}_${CFG_ARCH}.txt
}

mesg_make() {
    paste -d ';' mesg_*_${CFG_USER}_${CFG_ARCH}.txt > trusting_${DATE_STR}_${CFG_USER}_${CFG_ARCH}.txt
    cat                                               trusting_${DATE_STR}_${CFG_USER}_${CFG_ARCH}.txt
}

mesg_publish() {
  
if [ $PUBLISH -eq 1 ]; then

  if [ -f ${REFE_DIR}/trusting_${CFG_USER}_${CFG_ARCH}.txt ]; then cmd='sed -n 2p'; else cmd='cat'; fi

  $cmd trusting_${DATE_STR}_${CFG_USER}_${CFG_ARCH}.txt >> ${REFE_DIR}/trusting_${CFG_USER}_${CFG_ARCH}.txt

  # Send mail only when FAILED
  if [[ ! -z $MAIL && $STATUS == 'FAILED' ]]; then
      cat << END_MAIL > trusting.mail
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Dear $USER,

The trusting sequence for ${CONF_REF} has failed at step:
`tail -n 1 mesg_03_step_${CFG_USER}_${CFG_ARCH}.txt`
Directory : ${TEST_DIR}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

END_MAIL
      cat mesg_*_${CFG_USER}_${CFG_ARCH}.txt        >> trusting.mail
      mail -s "[trusting ${CONF_REF}] FAILED" $MAIL  < trusting.mail
  fi

fi
}

print_step() { STEP=$1; export STEP && printf "Step.....\n$TEP\n"; }

get_out() {
    mesg_make; mesg_publish

    # Save tested configuration if trusting failed
    if [ $STATUS == 'FAILED' ]; then
	cd ${TEST_DIR}
	touch mesg_08_inputfiles_${CFG_USER}_${CFG_ARCH}.txt mesg_09_realcputime_${CFG_USER}_${CFG_ARCH}.txt \
	      mesg_10_comments_${CFG_USER}_${CFG_ARCH}.txt
	tar -czf ${REFE_DIR}/trusting_${DATE_STR}_${CFG_USER}_${CFG_ARCH}.tar.gz *
    fi

    printf "Status\n$STATUS\n"  > mesg_03_status_${CFG_USER}_${CFG_ARCH}.txt
    printf "Step.....\n$STEP\n" > mesg_04_step_${CFG_USER}_${CFG_ARCH}.txt

    exit 1
}
