##!/bin/bash
# ------------------------------------------------------------------
# Author: andreasalazar@g.harvard.edu
# Title: build_script.sh
# Description: creates a CESM2 case, configures it, and builds it
# ------------------------------------------------------------------
USAGE="Usage: $0 CASE"
OPTIONS="res [default:f19_g17], compset [default:F2000climo] in that order"
NOTES=""
# --- Options processing -------------------------------------------
if [ $# == 0 ] ; then
    echo $USAGE
    echo $OPTIONS
    echo $NOTES
    exit 1;
fi
CASE=$1

export PBS_ACCOUNT=XX # # what is the name of your project account (UHAR0028)

RES=${2:-"f19_g17"} # default resolution 2 degree atm, 1 degree ocean
COMPSET=${3:-"B1850"} # default component set 
echo RES:$RES
echo COMPSET:$COMPSET

export COMPILER="intel"

# Set directories
# illustration of directories: http://www.cesm.ucar.edu/events/tutorials/2016/practical1-bertini.pdf p.48
SCRIPTDIR=$PWD # where is build_script (pwd  = here)
CESMROOT=XX # where is the source code [ex: /glade/work/asalazar/cesm2]
cd $CESMROOT/cime/scripts/
CASEROOT="${HOME}/caseroots/${CASE}" # where is the case root?
OUTPUT="/glade/derecho/scratch/XX/${CASE}" # where is output? (scratch is good)
RUNDIR="${OUTPUT}/run" # where is the run directory?
echo $CASEROOT

# Create case, this sets up the caseroot and the bld and run directories
./create_newcase --case ${CASEROOT} --res ${RES} --compset ${COMPSET} --project ${PBS_ACCOUNT} --compiler intel --run-unsupported|| exit -1

cd $CASEROOT # move to caseroot 
./case.setup --clean

# Move custom modifications (user_nl_*, source mods) to CASEROOT
cp -a $SCRIPTDIR/$0 $CASEROOT # make a copy in the caseroot
cp -a $SCRIPTDIR/user_nl_* $CASEROOT # move all namelist modifications to caseroop


# Modify tasks/cores: env_mach_pes.xml

./xmlchange JOB_WALLCLOCK_TIME=12:00:00

# Set up case run scripts
./case.setup

# Modify build: env_build.xml
./xmlchange EXEROOT=$OUTPUT/bld

# Build executables, this is where the source code is compiled
qcmd -- ./case.build 
echo 

# Modify run: env_run.xml

# storage:
./xmlchange --id RUN_STARTDATE --val 0001-01-01 # start on year 0

./xmlchange RUNDIR=$RUNDIR
./xmlchange DOUT_S=TRUE # Reorganizes the files into nice folders when output
./xmlchange DOUT_S_ROOT=$OUTPUT # where do you want to out the files?

# duration of run:
./xmlchange STOP_OPTION=XX # units of run, ndays, nmonths, nyears
./xmlchange STOP_N=XX # how many of the above units to run
./xmlchange RESUBMIT=XX # total times submitted = RESUBMIT+1

# continuation or new run?
./xmlchange CONTINUE_RUN=FALSE

# Instructions to submit the job upon build
printf "To submit job, issue:\n"
printf "cd ${CASEROOT}\n"
printf "./case.submit\n"

