#!/bin/bash

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

#SBATCH --chdir=/scratch/$username
#SBATCH --qos=el
#SBATCH --job-name=flex_compile
#SBATCH --output=flex_compile.%j.out
#SBATCH --error=flex_compile.%j.out
#SBATCH --mail-type=FAIL
#SBATCH --mail-user=$username
# job output is in .ecaccess_DO_NOT_REMOVE

set -x
export VERSION=$version_number
case $${EC_CLUSTER} in
  *ecs*)
  module purge
  module load prgenv/gnu
  module load gcc/8.4.1
  module load ecmwf-toolbox
  module load python3
  module load ecaccess
  export FLEXPART_ROOT_SCRIPTS=$fp_root_scripts
  export MAKEFILE=$makefile
  ;;
  *hpc*)
  module purge
  module load prgenv/gnu gcc/8.4.1
  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 -e '\nSUCCESS!' >>flexcompile
  mail -s flexcompile.$${HOST}.$$$$ $${USER} <flexcompile
  sleep 1
else
  echo Environment: >>flexcompile
  env >> flexcompile
  mail -s "ERROR! flexcompile.$${HOST}.$$$$" $${USER} <flexcompile
  sleep 1
fi
