#@ shell           = /usr/bin/ksh 

        # Specifies the shell that parses the script. If not  
        # specified, your login shell will be used. 

#@ class           = np 

        # Specifies that your job should be run in the class (queue) 
        # np, which is used to run parallel jobs. 

#@ job_type        = parallel 

        # Specifies that your job is parallel 
       
#@ job_name        = ecearth3

        # Assigns the specified name to the request 
    
#@ output          = $(job_name).$(schedd_host).$(jobid).out 

        # Specifies the name and location of STDOUT. If not given, the 
        # default is /dev/null.  The file will be written in the 
        # submitting directory, by default.  

#@ error           = $(job_name).$(schedd_host).$(jobid).err 

        # Specifies the name and location of STDERR. If not given, the 
        # default is /dev/null.  The file will be written in the 
        # submitting directory, by default. 

#@ notification    = always  

        # Specifies that email should be sent only if the job fails.  
        # Other options include: always, complete, start, and 
        # never. The default is notification = complete. 

#@ resources       = ConsumableCpus(1) ConsumableMemory(1200mb) 

        # Specifies quantities of the resources which will be 'consumed' 
        # by each process/task of a job step. ConsumableCpus and 
        # ConsumableMemory must be specified with a value which is 
        # greater than zero.   
        # The value ConsumableCpus indicates the number of threads per 
        # (MPI) process/task. This job will be run using 1 thread 
        # per MPI process/task.   
        # The value ConsumableMemory specifies the (real) memory per 
        # (MPI) process/task which is shared between threads. This job 
        # will request 100 megabytes of real memory.   

#@ node             = 4 

        # Specifies that your job requires 2 nodes 
    
#@ tasks_per_node   = 32 

        # Specifies the number of (MPI) processes/tasks of a parallel job  
        # you want to run per node. In this example your job requires  
        # 32 processes/tasks per node.   

#@ cpu_limit        = 12:00:00

        # Specifies the maximum CPU time in HH:MM:SS used by any single process.  
        # In this job 1 MPI process/task can use up to a total of 1 min CPU time. 
        # Note: All limits are capped by those specified in the class. 

#@ wall_clock_limit = 24:00:00

        # Specifies that your job requires HH:MM:SS of wall clock 
        # time. This job requires 3 min of wall clock time. 
        # Note: All limits are capped by those specified in the class. 

#@ queue 
set -xv
exp_name=IFS3
alias gdate='/opt/freeware/bin/date'

# Simulation start and end date. Use any (reasonable) syntax you want.
run_start_date="1990-01-01"
run_end_date="${run_start_date} + 10 years"

# Set $force_run_from_scratch to 'true' if you want to force this run to start
# from scratch, possibly ignoring any restart files present in the run
# directory. Leave set to 'false' otherwise.
# NOTE: If set to 'true' the run directory $run_dir is cleaned!
force_run_from_scratch=true

# Resolution
ifs_grid=T255L91

# Restart frequency. Use any (reasonable) number and time unit you want.
# For runs without restart, leave this variable empty
rst_freq="1 year"

# Coupling frequency [hrs]
cpl_freq_hrs=0

# Directories
start_dir=${PWD}
ctrl_file_dir=${start_dir}/ctrl

# Architecture
build_arch=ecconf

# This file is used to store information about restarts
ece_info_file="ece.info"

# -----------------------------------------------------------------------------
# *** Read platform dependent configuration
# -----------------------------------------------------------------------------

# Configure paths for building/running EC-Earth
ecearth_source_dir=/perm/ms/se/sm0g/Projects/ecearth3-c1a
run_dir=${TEMP}/${USER}/run/${exp_name}
ini_data_dir=${PERM}/ecearth3/setup

stdout_file=${start_dir}/out/out.out 

# Configure grib api paths
export GRIB_DEFINITION_PATH=/usr/local/lib/metaps/lib/grib_api/1.9.16/share/definitions
export GRIB_SAMPLES_PATH=/usr/local/lib/metaps/lib/grib_api/1.9.16/ifs_samples/grib1
export GRIB_BIN_PATH=/usr/local/lib/metaps/lib/grib_api/1.9.16/bin64


# Configure number of processors per node
#proc_per_node=32

# -----------------------------------------------------------------------------
# *** IFS configuration
# -----------------------------------------------------------------------------

ifs_version=36r4

ifs_time_step_sec=2700

ifs_output_freq=$(( 6 * 3600 / ifs_time_step_sec ))
ifs_di_freq=$(( 1 * 3600 / ifs_time_step_sec ))
ifs_ddh_freq=$(( 1 * 3600 / ifs_time_step_sec ))

ifs_res_hor=$(echo ${ifs_grid} | sed 's:T\([0-9]\*\)L\([0-9]\*\):\1:')
ifs_res_ver=$(echo ${ifs_grid} | sed 's:T\([0-9]\*\)L\([0-9]\*\):\2:')

ifs_numproc=128

ifs_exe_file=${ecearth_source_dir}/ifs-${ifs_version}/bin/ifsmaster-${build_arch}

ifs_lastout=false

ifs_cmip5=FALSE
ifs_cmip5_rcp=0
ifs_volcanoes=FALSE

# =============================================================================
# *** END of User configuration
# =============================================================================

# -----------------------------------------------------------------------------
# *** Define some helper functions
# -----------------------------------------------------------------------------

function info
{
    echo "*II* $@"
}

function error
{
    echo "*EE* $@"
    exit 1
}

function cleanup
{
    # Cleanup function, triggered by the traps set in the run-script
    set +u

    if [ -r ${tempfile} ]
    then
        rm -f ${tempfile}
    fi

    if [ -r ${stdout_file} -a -d ${run_dir} ]
    then
        cp ${stdout_file} ${run_dir}
    fi
}

# -----------------------------------------------------------------------------
# *** Make sure to clean up on exit
# -----------------------------------------------------------------------------

trap 'cleanup' EXIT SIGHUP SIGINT SIGTERM

# -----------------------------------------------------------------------------
# *** Create the run dir if necessary and go there
#     Everything is done from here.
# -----------------------------------------------------------------------------
if [ ! -d ${run_dir} ]
then
    mkdir -p ${run_dir}
fi
cd ${run_dir}

# -----------------------------------------------------------------------------
# *** Determine the time span of this run and whether it's a restart leg
# -----------------------------------------------------------------------------

# Regularise the format of the start and end date of the simulation
run_start_date=$(gdate -uR -d "${run_start_date}")
run_end_date=$(gdate -uR -d "${run_end_date}")

# Check for restart information file and set the current leg start date
#   Ignore restart information file if force_run_from_scratch is true
if ! $force_run_from_scratch && [ -r ${ece_info_file} ]
then
    leg_is_restart=true
    . ${ece_info_file}
    leg_start_date=${leg_end_date}
    leg_number=$((leg_number+1))
else
    leg_is_restart=false
    leg_start_date=${run_start_date}
    leg_number=1
fi

# Compute the end date of the current leg
if [ -n "${rst_freq}" ]
then
    leg_end_date=$(gdate -uR -d "${leg_start_date} + ${rst_freq}")
else
    leg_end_date=${run_end_date}
fi

if [ $(gdate -d "${leg_end_date}" +%s) -gt $(gdate -d "${run_end_date}" +%s) ]
then
    leg_end_date=${run_end_date}
fi

# Some time variables needed later
leg_length_sec=$(( $(gdate -d "${leg_end_date}" +%s) - $(gdate -d "${leg_start_date}" +%s) ))
leg_start_sec=$(( $(gdate -d "${leg_start_date}" +%s) - $(gdate -d "${run_start_date}" +%s) ))
leg_end_sec=$(( $(gdate -d "${leg_end_date}" +%s) - $(gdate -d "${run_start_date}" +%s) ))
leg_start_date_yyyymmdd=$(gdate -d "${leg_start_date}" +%Y%m%d)
leg_start_date_yyyy=$(gdate -d "${leg_start_date}" +%Y)
leg_end_date_yyyy=$(gdate -d "${leg_end_date}" +%Y)

# Check whether there's actually time left to simulate - exit otherwise
if [ ${leg_length_sec} -le 0 ]
then
    info "Leg start date equal to or after end of simulation."
    info "Nothing left to do. Exiting."
    exit 0
fi


# -----------------------------------------------------------------------------
# *** Prepare the run directory for a run from scratch
# -----------------------------------------------------------------------------
if ! $leg_is_restart
then
    # -------------------------------------------------------------------------
    # *** This is no restart, hence, clean the run dir and link the executables
    # -------------------------------------------------------------------------
    rm -fr ${run_dir}/*

    ln -s ${ifs_exe_file}

    # -------------------------------------------------------------------------
    # *** Files needed for IFS (linked)
    # -------------------------------------------------------------------------

    # Initial data
    ln -s \
    ${ini_data_dir}/ifs/${ifs_grid}/${leg_start_date_yyyymmdd}/ICMGGECE3INIUA \
                                                        ICMGG${exp_name}INIUA
    ln -s \
    ${ini_data_dir}/ifs/${ifs_grid}/${leg_start_date_yyyymmdd}/ICMGGECE3INIT \
                                                        ICMGG${exp_name}INIT
    ln -s \
    ${ini_data_dir}/ifs/${ifs_grid}/${leg_start_date_yyyymmdd}/ICMSHECE3INIT \
                                                        ICMSH${exp_name}INIT
    ln -s \
                      ${ini_data_dir}/ifs/${ifs_grid}/climate/ICMSEAECE3INIT \
                                                       ICMSEA${exp_name}INIT

    # Other stuff
    ln -s ${ini_data_dir}/ifs/postins
    ln -s ${ini_data_dir}/ifs/dirlist
    ln -s ${ini_data_dir}/ifs/rtables/* .

    # Run-off file
    ln -s ${ini_data_dir}/ifs/${ifs_grid}/runoff_maps.txt

fi # ! $leg_is_restart

# -----------------------------------------------------------------------------
# *** Create some control files
# -----------------------------------------------------------------------------

# IFS namelist file
case ${ifs_grid} in
    T255L91) . ${ctrl_file_dir}/namelist.ifs-T255L91.sh > fort.4
             ;;
    *)       . ${ctrl_file_dir}/namelist.ifs-default.sh > fort.4
             ;;
esac

# -----------------------------------------------------------------------------
# *** IFS climatology data
# -----------------------------------------------------------------------------
icmclfile=${ini_data_dir}/ifs/${ifs_grid}/climate/ICMCL
tempfile=tmp.$$
grib_set=${GRIB_BIN_PATH}${GRIB_BIN_PATH:+/}grib_set

# Create data for december, the year before the leg starts
${grib_set} \
-s dataDate=$(printf "%04d" $((leg_start_date_yyyy-1)))1215 ${icmclfile}-12 \
                                                       ICMCL${exp_name}INIT

# Create data for all month in the years of the leg
for y in $(seq  ${leg_start_date_yyyy} ${leg_end_date_yyyy})
do
    yy=$(printf "%04d" $y)
    for m in $(seq 1 12)
    do
        mm=$(printf "%02d" $m)
        ${grib_set} -s dataDate=${yy}${mm}15 ${icmclfile}-${mm} ${tempfile}
        cat ${tempfile} >> ICMCL${exp_name}INIT
    done
done

# Create data for january, the year after the leg ends
${grib_set} -s dataDate=$(printf "%04d" $((leg_end_date_yyyy+1)))0115 ${icmclfile}-01 \
                                                                          ${tempfile}
cat ${tempfile} >> ICMCL${exp_name}INIT

# Clean up
rm -f ${tempfile}


export DR_HOOK_IGNORE_SIGNALS='-1'
export OASIS3=no

./${ifs_exe_file##*/} -v ecmwf -e ${exp_name}
