#!/bin/ksh

# ON ECS or HPC servers:
# start with ecaccess-job-submit -queueName <QUEUENAME> <NAME_OF_THIS_FILE>  on gateway server
# start with srun <NAME_OF_THIS_FILE> directly on machine

#SBATCH --chdir=$$SCRATCH
#SBATCH --qos=el
#SBATCH --job-name=flex_extract
#SBATCH --output=flex_extract.%j.out
#SBATCH --error=flex_error.%j.out
#SBATCH --mail-type=FAIL
#SBATCH --mail-user=$username

## CRAY specific batch requests
##PBS -N flex_ecmwf
##PBS -q ns
##PBS -S /usr/bin/ksh
##PBS -o $$SCRATCH/flex_extract.$${Jobname}.$${Job_ID}.out
# job output is in .ecaccess_DO_NOT_REMOVE
##PBS -j oe
##PBS -V
##PBS -l EC_threads_per_task=1
##PBS -l EC_memory_per_task=3200MB

set -x
export VERSION=$version_number
case $${EC_CLUSTER} in
  *ecs*)
#  module switch prgenv/gnu
  module load ecmwf-toolbox
  module load python3
  module load ecaccess
  export FLEXPART_ROOT_SCRIPTS=$fp_root_scripts
  export MAKEFILE=$makefile
  ;;
  *hpc*)
#  module switch PrgEnv-cray PrgEnv-intel
  module load python3
  module load ecmwf-toolbox
  module load ecaccess
  echo $${GROUP}
  echo $${HOME}
  echo $${HOME} | awk -F / '{print $1, $2, $3, $4}'
  export GROUP=`echo $${HOME} | awk -F / '{print $4}'`
  export SCRATCH=$${SCRATCH}
  export FLEXPART_ROOT_SCRIPTS=$fp_root_scripts
  export MAKEFILE=$makefile
  ;;
esac

mkdir -p $${FLEXPART_ROOT_SCRIPTS}/flex_extract_v$${VERSION}
cd $${FLEXPART_ROOT_SCRIPTS}/flex_extract_v$${VERSION}   # if FLEXPART_ROOT is not set this means cd to the home directory
tar -xvf $${HOME}/flex_extract_v$${VERSION}.tar
cd Source/Fortran
\rm *.o *.mod $fortran_program 
make -f $${MAKEFILE} >flexcompile 2>flexcompile

ls -l $fortran_program >>flexcompile
if [ $$? -eq 0 ]; then
  echo 'SUCCESS!' >>flexcompile
  mail -s flexcompile.$${HOST}.$$$$ $${USER} <flexcompile
else
  echo Environment: >>flexcompile
  env >> flexcompile
  mail -s "ERROR! flexcompile.$${HOST}.$$$$" $${USER} <flexcompile
fi
