#!/bin/bash

# Running on chrysalis

#SBATCH  --job-name=ts_atm_monthly_180x360_aave_0001-0010-0010
#SBATCH  --account=e3sm
#SBATCH  --nodes=1
#SBATCH  --output=test_bash_generation_output/post/scripts/ts_atm_monthly_180x360_aave_0001-0010-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}" > ts_atm_monthly_180x360_aave_0001-0010-0010.status

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

# Create symbolic links to input files
input=./archive/atm/hist
for (( year=1; year<=10; year++ ))
do
  YYYY=`printf "%04d" ${year}`
  for file in ${input}/case_name.eam.h0.${YYYY}-*.nc
  do
    ln -s ${file} .
  done
done

ts_fmt=ts_only
echo $ts_fmt


vars=FSNTOA,FLUT,FSNT,FLNT,FSNS,FLNS,SHFLX,QFLX,TAUX,TAUY,PRECC,PRECL,PRECSC,PRECSL,TS,TREFHT,CLDTOT,CLDHGH,CLDMED,CLDLOW,U

ls case_name.eam.h0.????-*.nc > input.txt
if grep -q "*" input.txt; then
  cd test_bash_generation_output/post/scripts
  echo 'Missing input files'
  echo 'ERROR (1)' > ts_atm_monthly_180x360_aave_0001-0010-0010.status
  exit 1
fi
# Generate time series files
# If the user-defined parameter "vars" is "", then ${vars}, defined above, will be too.
cat input.txt | ncclimo \
-c case_name \
-v ${vars} \
--split \
--yr_srt=1 \
--yr_end=10 \
--ypf=10 \
--map=/home/ac.zender/data/maps/map_ne30pg2_to_cmip6_180x360_aave.20200201.nc \
-o trash \
-O output \
--prc_typ=eam



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

# Move output ts files to final destination
{
  dest=test_bash_generation_output/post/atm/180x360_aave/ts/monthly/10yr
  mkdir -p ${dest}
  mv output/*.nc ${dest}
}
if [ $? != 0 ]; then
  cd test_bash_generation_output/post/scripts
  echo 'ERROR (3)' > ts_atm_monthly_180x360_aave_0001-0010-0010.status
  exit 3
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 ts_atm_monthly_180x360_aave_0001-0010-0010.status
echo 'OK' > ts_atm_monthly_180x360_aave_0001-0010-0010.status
exit 0