#! /usr/bin/env bash

# $Header: /u/gcmpack/MITgcm/tools/example_scripts/nasa_ames/test_submit_pleiades,v 1.2 2017/04/21 19:22:23 jmc Exp $
# $Name:  $

today=`date +%Y%m%d`
dInWeek=`date +%a`

if test $# = 0
then
  TEST_LIST='ieee fast'
else
  TEST_LIST=$*
fi

headNode=`hostname -s`
QSUB="/PBS/bin/qsub"
QSTAT="/PBS/bin/qstat -u $USER"
#dNam=$headNode
#QSUB="/usr/bin/sbatch"
#QLIST="/usr/bin/squeue -u $USER"
dNam='pleiades'
HERE="$HOME/test_${dNam}"
TST_DISK="/nobackupp2/$USER"
TST_DIR="$TST_DISK/test_${dNam}"
logPfix='test_submit'

SUB_DIR="$HERE/nasa_ames"
OUT_DIR="$HERE/output"
LOG_FIL="$OUT_DIR/$logPfix."`date +%m%d`".log"
#SUB_DIR="$HERE/temp"

#-- clean up old log files and start a new one:
cd $OUT_DIR

rm -f $logPfix.*.log_bak
if test -f $LOG_FIL ; then mv -f $LOG_FIL ${LOG_FIL}_bak ; fi
echo -n '-- Starting: '					| tee -a $LOG_FIL
date							| tee -a $LOG_FIL

n=$(( `ls $logPfix.*.log | wc -l` - 10 ))
if test $n -gt 0 ; then
  echo ' remove old log files:'				| tee -a $LOG_FIL
    ls -lt $logPfix.*.log | tail -"$n"			| tee -a $LOG_FIL
    ls -t  $logPfix.*.log | tail -"$n" | xargs rm -f
fi

#-------------------------------------------------------------
# defaults
#export PATH="$PATH:/usr/local/bin"
if [ -d ~/bin ]; then export PATH=$PATH:~/bin ; fi
#- to get case insensitive "ls" (and order of tested experiments)
export LC_ALL="en_US.UTF-8"
#  Turn off stack limit for FIZHI & AD-tests
#ulimit -s unlimited

if test -f /etc/profile.d/modules.sh    ; then . /etc/profile.d/modules.sh    ; fi
#- load standard modules:
#module add fedora slurm maui svante
#module add slurm
module list 						>> $LOG_FIL 2>&1

#- method to acces CVS:
cmdCVS='cvs -d :pserver:cvsanon@mitgcm.org:/u/gcmpack -q'

#---+----1----+----2----+----3----+----4----+----5----+----6----+----7-|--+----|
#-- Download/Update reference version of MITgcm code:
checkOut=1
gcmDIR='MITgcm'
exp2add=''
updFile='updated_code'

echo "cd $TST_DISK ; pwd (x2)" | tee -a $LOG_FIL
cd $TST_DISK	| tee -a $LOG_FIL 2>&1
pwd		| tee -a $LOG_FIL
if test ! -d $TST_DIR ; then
   echo -n "Creating a working dir: $TST_DIR ..."	| tee -a $LOG_FIL
  #/bin/rm -rf $TST_DIR
   mkdir $TST_DIR
   retVal=$?
   if test "x$retVal" != x0 ; then
      echo "Error: unable to make dir: $TST_DIR (err=$retVal ) --> Exit" | tee -a $LOG_FIL
      exit 1
   fi
fi
cd $TST_DIR
pwd		| tee -a $LOG_FIL

#- remove date/lock-file:
if test -f $updFile ; then rm -f $updFile ; sleep 2 ; fi

if [ $checkOut -eq 1 ] ; then
  if test -d $gcmDIR/CVS ; then
    echo -n "Update dir $gcmDIR using '$cmdCVS update -P -d' ..." | tee -a $LOG_FIL
    echo '' >> $LOG_FIL
    ( cd $gcmDIR ; $cmdCVS update -P -d )		>> $LOG_FIL 2>&1
    RETVAL=$?
    if test "x$RETVAL" != x0 ; then echo ''
       echo "cvs update on '"`hostname`"' fail (return val=$RETVAL) => exit" | tee -a $LOG_FIL
       exit
    else echo "  done"					| tee -a $LOG_FIL
    fi
 else
    echo "no dir: $gcmDIR/CVS => try a fresh check-out"	| tee -a $LOG_FIL
    checkOut=2
  fi
fi
if [ $checkOut -eq 2 ] ; then
    test -e $gcmDIR && rm -rf $gcmDIR
    echo -n "Downloading using '$cmdCVS co -P -d $gcmDIR MITgcm' ..."	| tee -a $LOG_FIL
    $cmdCVS co -P -d $gcmDIR MITgcm > /dev/null
    RETVAL=$?
    if test "x$RETVAL" != x0 ; then echo ''		| tee -a $LOG_FIL
      echo "cvs co on '"`hostname`"' fail (return val=$RETVAL) => exit"	| tee -a $LOG_FIL
      exit
    else echo "  done"					| tee -a $LOG_FIL
    fi
    if test -d $gcmDIR/verification ; then
      for exp2add in $addExp ; do
        echo " add dir: $exp2add (from Contrib:verification_other)" | tee -a $LOG_FIL
        ( cd $gcmDIR/verification ; $cmdCVS co -P -d $exp2add \
                       MITgcm_contrib/verification_other/$exp2add > /dev/null )
      done
    fi
    /usr/bin/find $gcmDIR -type d | xargs chmod g+rxs
    /usr/bin/find $gcmDIR -type f | xargs chmod g+r
fi

#- update date/lock-file:
if test -d $gcmDIR/verification ; then
  echo $today > $updFile ; sleep 2
  ls -l $updFile					| tee -a $LOG_FIL
fi

#-- leave TST Dir and go back to output dir
cd $OUT_DIR
#---+----1----+----2----+----3----+----4----+----5----+----6----+----7-|--+----|
#-- now really do something:

  JOB_LIST=$TEST_LIST
  NB_SUB_JOBS=0
  for i in $JOB_LIST
  do
    case $i in
      'pgiAdm') sfx='pgi_adm' ;;
      'pgiMth') sfx='pgi_mth' ;;
             *) sfx=`echo ${i} | sed 's/MPI$/_mpi/'`  ;;
    esac
    BATCH_SCRIPT="test_${dNam}_$sfx"
    if test -f $SUB_DIR/$BATCH_SCRIPT ; then
      #- job name ( $JOB ) & output-file name ( $JOB.std??? ) must match
      #  definition within $BATCH_SCRIPT slurm script
      JOB="tst_${i}"
      job_exist=`$QSTAT | grep $JOB | wc -l`
      #sJob=`printf "%8.8s" $JOB` #- squeue truncate name to only 1rst 8c
      #job_exist=`$QLIST | grep $sJob | wc -l`
      if test "x_$job_exist" = x_0 ; then
        #-- move previous output file
        outList=`ls $JOB.std??? 2> /dev/null`
        if test "x$outList" != x ; then
          echo -n " moving job $JOB old output files:"	| tee -a $LOG_FIL
          if test -d $OUT_DIR/prev ; then
            for xx in $outList ; do
              pp=$OUT_DIR/prev/$xx ; echo -n " $xx"	| tee -a $LOG_FIL
              test -f $pp.sav && mv -f $pp.sav $pp.old
              test -f $pp     && mv -f $pp     $pp.sav
              chmod a+r $xx ; mv -f $xx $OUT_DIR/prev
            done
            echo " to dir ./prev"			| tee -a $LOG_FIL
          else
            echo " <-- missing dir $OUT_DIR/prev"	| tee -a $LOG_FIL
          fi
        else echo " no old output files from job '$JOB'" | tee -a $LOG_FIL
        fi
        #-- submit job
          echo -n "--> $JOB : "				| tee -a $LOG_FIL
          $QSUB $SUB_DIR/$BATCH_SCRIPT			| tee -a $LOG_FIL
          NB_SUB_JOBS=`expr $NB_SUB_JOBS + 1`
      else
          echo "--> $JOB :"				| tee -a $LOG_FIL
          $QSTAT | grep $JOB				| tee -a $LOG_FIL
          #$QLIST | grep $sJob				| tee -a $LOG_FIL
          echo ' job already exist => skip this test'	| tee -a $LOG_FIL
      fi
    else
       echo 'no file:' $BATCH_SCRIPT 'to submit'	| tee -a $LOG_FIL
    fi
  done
  echo "info-sub-list: NB_SUB_JOBS='$NB_SUB_JOBS'"	>> $LOG_FIL
  echo -n '-- Finished at: '				| tee -a $LOG_FIL
  date							| tee -a $LOG_FIL

#---+----1----+----2----+----3----+----4----+----5----+----6----+----7-|--+----|
exit 0
