#!/bin/bash

# Running on chrysalis

#SBATCH  --job-name=climo_atm_monthly_180x360_aave_0001-0010
#SBATCH  --account=e3sm
#SBATCH  --nodes=4
#SBATCH  --output=test_bash_generation_output/post/scripts/climo_atm_monthly_180x360_aave_0001-0010.o%j
#SBATCH  --exclusive
#SBATCH  --time=02:00:00


#SBATCH  --partition=haswell


...

# Turn on debug output if needed
debug=False
if [[ "${debug,,}" == "true" ]]; then
  set -x
fi

# Script dir
cd test_bash_generation_output/post/scripts

# Get jobid
id=${SLURM_JOBID}

# Update status file
STARTTIME=$(date +%s)
echo "RUNNING ${id}" > climo_atm_monthly_180x360_aave_0001-0010.status

# Create temporary workdir
workdir=`mktemp -d tmp.${id}.XXXX`
cd ${workdir}


# --- Monthly climatologies ---
ncclimo \
--case=case_name \
--jobs=${SLURM_NNODES} \
--thr=1 \
--parallel=mpi \
--yr_srt=1 \
--yr_end=10 \
--input=./archive/atm/hist \
--map=/home/ac.zender/data/maps/map_ne30pg2_to_cmip6_180x360_aave.20200201.nc \
--output=trash \
--regrid=output \
--prc_typ=eam



if [ $? != 0 ]; then
  cd test_bash_generation_output/post/scripts
  echo 'ERROR (3)' > climo_atm_monthly_180x360_aave_0001-0010.status
  exit 3
fi

# Move regridded climo files to final destination
subdir=""

{
 subdir=clim
}

dest=test_bash_generation_output/post/atm/180x360_aave/${subdir}/10yr
mkdir -p ${dest}
mv output/*.nc ${dest}

if [ $? != 0 ]; then
  cd test_bash_generation_output/post/scripts
  echo 'ERROR (4)' > climo_atm_monthly_180x360_aave_0001-0010.status
  exit 4
fi

# Delete temporary workdir
cd ..
if [[ "${debug,,}" != "true" ]]; then
  rm -rf ${workdir}
fi

# Update status file and exit

ENDTIME=$(date +%s)
ELAPSEDTIME=$(($ENDTIME - $STARTTIME))

echo ==============================================
echo "Elapsed time: $ELAPSEDTIME seconds"
echo ==============================================
rm -f climo_atm_monthly_180x360_aave_0001-0010.status
echo 'OK' > climo_atm_monthly_180x360_aave_0001-0010.status
exit 0