#!/bin/ksh
###############################################################################
#                              RUN EC_EARTH
###############################################################################
#@ shell            = /usr/bin/ksh
#@ class            = np
#@ job_type         = parallel
#@ job_name         = run
#@ output           = $(job_name).$(jobid).out
#@ error            = $(job_name).$(jobid).err
#@ notification     = error 
#@ resources        = ConsumableCpus(1) ConsumableMemory(1200mb)
#@ ec_smt           = no
#@ total_tasks      = 55
#@ wall_clock_limit = 00:30:00
#@ queue
#
###############################################################################

# modules setup

# setup the grib_api env.
PATH=/usr/local/lib/metaps/lib/grib_api/1.9.16/bin64:$PATH
PATH=/opt/freeware/bin:$PATH

set -xuve
#module list

# =============================================================================
# *** BEGIN User configuration
# =============================================================================

# -----------------------------------------------------------------------------
# *** General configuration
# -----------------------------------------------------------------------------
# Experiment name (exactly 4 letters!)
exp_name=ECE3

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

# 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=false

# Resolution
ifs_grid=T255L62
nem_grid=ORCA1L46
lim=LIM2

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

# Coupling frequency [hrs]
cpl_freq_hrs=3

# Directories
ecearth_base_dir=/perm/ms/spesiccf/c3m/models/ecearth/v3.0.1
start_dir=${PWD}
ctrl_file_dir=${ecearth_base_dir}/setup/ctrl
run_dir=/scratch/ms/spesiccf/$USER/test/run_${ifs_grid}_${nem_grid}_${LOADL_STEP_ID}
ini_data_dir=${ecearth_base_dir}/inidata
bin_dir=${ecearth_base_dir}/bin

# Architecture
build_arch=ecconf

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

# -----------------------------------------------------------------------------
# *** Read platform dependent configuration
# -----------------------------------------------------------------------------
grib_api_path=/usr/local/lib/metaps/lib/grib_api/1.9.16

export GRIB_DEFINITION_PATH=${grib_api_path}/share/definitions
export GRIB_SAMPLES_PATH=${grib_api_path}/ifs_samples/grib1
export GRIB_BIN_PATH=${grib_api_path}/bin64

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

ifs_version=36r4

case ${ifs_grid} in
     T159*)  ifs_time_step_sec=3600 ;;
     T255*)  ifs_time_step_sec=2700 ;;
     T511*)  ifs_time_step_sec=900 ;;
     T799*)  ifs_time_step_sec=720  ;;
     *) error "Unsupported grid type: ${ifs_grid}"
     ;;
esac

ifs_output_freq=$(( 6 * 3600 / ifs_time_step_sec ))
ifs_di_freq=$(( 24 * 3600 / ifs_time_step_sec ))
ifs_ddh_freq=$(( 120 * 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=32

ifs_exe_file=${bin_dir}/ifsmaster-${build_arch}

ifs_lastout=true

ifs_cmip5=TRUE
ifs_cmip5_rcp=0
ifs_volcanoes=TRUE
ifs_ncmip5fixyr=0

# -----------------------------------------------------------------------------
# *** NEMO/LIM configuration
# -----------------------------------------------------------------------------

nem_version=3.3.1
lim_version=$(echo $lim | cut -d 'M' -f 2)

case ${nem_grid} in
     ORCA1*)   nem_time_step_sec=3600 ;;
     ORCA025*) nem_time_step_sec=1200 ;;
     *) error "Unsupported grid type: ${nem_grid}"
    ;;
esac
lim_time_step_sec=3600

nem_res_hor=$(echo ${nem_grid} | sed 's:ORCA\([0-9]*\)L\([0-9]*\):\1:')
nem_res_ver=$(echo ${nem_grid} | sed 's:ORCA\([0-9]*\)L\([0-9]*\):\2:')

nem_exe_file=${bin_dir}/${nem_grid}_${lim}/nemo.exe

nem_numproc=16

advsch=tvd
rstctl=1

# -----------------------------------------------------------------------------
# *** OASIS configuration
# -----------------------------------------------------------------------------

oas_namcut_script=${ecearth_base_dir}/sources/sources/util/namcouple-split/namsplit.pl

oas_numproc=7

# Flux correction that compensates for the mismatch in the LSM of IFS and NEMO
# The QS, RUNOFF and CALVING coupling fields are multiplied by this factor. See
# documentation on the EC-Earth 3 Wiki for more details.
oas_qs_fluxcorr=0.985
oas_rnf_fluxcorr=0.985

oas_exe_file=${bin_dir}/oasis3.MPI1.x

# Restart files for the coupling fields
oas_cpl_flds="TAUX_OCE TAUY_OCE TAUX_ICE TAUY_ICE \
              QS___OCE QS___ICE QNS__OCE QNS__ICE DQDT_ICE \
              PRCP_LIQ PRCP_SOL EVAP_TOT EVAP_ICE RNF__OCE CALV_OCE \
              O_SSTSST O_TepIce O_AlbIce OIceFrac O_IceTck O_SnwTck"

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

# =============================================================================
# *** This is where the code begins ...
# =============================================================================

# -----------------------------------------------------------------------------
# *** 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=$(date -uR -d "${run_start_date}")
run_end_date=$(date -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=$(date -uR -d "${leg_start_date} + ${rst_freq}")
else
    leg_end_date=${run_end_date}
fi

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

# Some time variables needed later
leg_length_sec=$(( $(date -d "${leg_end_date}" +%s) - $(date -d "${leg_start_date}" +%s) ))
leg_start_sec=$(( $(date -d "${leg_start_date}" +%s) - $(date -d "${run_start_date}" +%s) ))
leg_end_sec=$(( $(date -d "${leg_end_date}" +%s) - $(date -d "${run_start_date}" +%s) ))
leg_start_date_yyyymmdd=$(date -u -d "${leg_start_date}" +%Y%m%d)
leg_start_date_yyyy=$(date -u -d "${leg_start_date}" +%Y)
leg_end_date_yyyy=$(date -u -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}
    ln -s ${nem_exe_file}
    ln -s ${oas_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
    # Other stuff
    ln -s ${ini_data_dir}/ifs/rtables/* .

    # Output control (ppt files)
    mkdir postins
    cp ${ctrl_file_dir}/ppt* postins/
    f_min=$(( ifs_output_freq * ifs_time_step_sec / 60 ))
    for t in $(seq $f_min $f_min 1439)
    do
        hh=$(printf %02d $((t/60)) )
        mm=$(printf %02d $((t%60)) )
        ln -s pptdddddd0000 postins/pptdddddd$hh$mm
    done
    /bin/ls -1 postins/* > dirlist

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

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

    # Various stuff
    ln -s ${ini_data_dir}/nemo/${nem_grid}/bathy_meter.nc
    ln -s ${ini_data_dir}/nemo/${nem_grid}/coordinates.nc
    ln -s ${ini_data_dir}/nemo/${nem_grid}/ahmcoef

    # Initial data
    ln -s ${ini_data_dir}/nemo/${nem_grid}/temperature_*.nc .
    ln -s ${ini_data_dir}/nemo/${nem_grid}/salinity_*.nc .

    # IOM files
    ln -s ${ctrl_file_dir}/xmlio_server.def
    ln -s ${ctrl_file_dir}/iodef.xml

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

    # Name table file
    ln -s ${ini_data_dir}/oasis/cf_name_table.txt

    oas_grid_dir=${ini_data_dir}/oasis/T${ifs_res_hor}-ORCA${nem_res_hor}

    # Run-off file
    ln -s ${oas_grid_dir}/runoff_maps.txt

    # Grid definition files
    ln -s ${oas_grid_dir}/areas.nc
    ln -s ${oas_grid_dir}/grids.nc
    ln -s ${oas_grid_dir}/masks.nc

    # Weight files
    case ${ifs_res_hor} in
        159)  oas_agrd=080
              ;;
        255)  oas_agrd=128
              ;;
        511)  oas_agrd=256
              ;;
        799)  oas_agrd=400
              ;;
        *)    error "Unsupported horizontal resolution (IFS): ${ifs_res_hor}"
              ;;
    esac

    case ${nem_res_hor} in
          1)  oas_ogrd=O1t0
              ;;
        025)  oas_ogrd=Ot25
              ;;
          *)  error "Unsupported horizontal resolution (NEMO): ${nem_res_hor}"
              ;;
    esac

    for n in $(seq 0 $((oas_numproc-1)))
    do
        ln -s \
        ${oas_grid_dir}/rmp_A${oas_agrd}_to_${oas_ogrd}_GAUSWGT.nc \
                        rmp_A${oas_agrd}_to_${oas_ogrd}_GAUSWGT_${n}.nc
        ln -s \
        ${oas_grid_dir}/rmp_${oas_ogrd}_to_L${oas_agrd}_GAUSWGT.nc \
                        rmp_${oas_ogrd}_to_L${oas_agrd}_GAUSWGT_${n}.nc
    done

    for f in ${oas_cpl_flds}
    do
        cp ${oas_grid_dir}/rst/$f .
    done

fi # ! $leg_is_restart

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

# IFS, NEMO, LIM namelist and OASIS namcouple files
. ${ctrl_file_dir}/namelist.ifs-${ifs_grid}.sh                                  > fort.4
. ${ctrl_file_dir}/namelist.nemo-${nem_grid}.sh                     > namelist
. ${ctrl_file_dir}/namelist.lim${lim_version}-ORCA${nem_res_hor}.sh > namelist_ice
. ${ctrl_file_dir}/namcouple.sh                                     > namcouple

# Split OASIS namcouple file (if necessary)
if (( oas_numproc == 1 ))
then
    ln -s namcouple namcouple_0
elif [ -n "$oas_namcut_script" -a -x $oas_namcut_script ]
then
    ${oas_namcut_script} ${oas_numproc} namcouple
else
    error "Couldn't run script to split the OASIS namcouple file (\$oas_namcut_script)."
fi

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

# 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}

# -----------------------------------------------------------------------------
# *** Link the appropriate NEMO restart files of the previous leg
# -----------------------------------------------------------------------------
if $leg_is_restart
then
    ns=$(printf %08d $(( leg_start_sec / nem_time_step_sec )))
    for n in $(seq 0 $((nem_numproc-1)))
    do
        np=$(printf %04d ${n})
        ln -fs ${exp_name}_${ns}_restart_oce_${np}.nc restart_oce_${np}.nc
        ln -fs ${exp_name}_${ns}_restart_ice_${np}.nc restart_ice_${np}.nc
    done
fi

# -----------------------------------------------------------------------------
# *** Remove some OASIS files of the previous leg
# -----------------------------------------------------------------------------
if $leg_is_restart
then
    rm -f anaisout_*
fi

# -----------------------------------------------------------------------------
# *** Start the run
# -----------------------------------------------------------------------------
export DR_HOOK_IGNORE_SIGNALS='-1'
export OASIS3=yes
export OASIS3DEBUGLEVEL=2

### --- PLATFORM DEPENDENT CODE ---
# ulimit -s unlimited
### --- END of PLATFORM DEPENDENT CODE ---

t1=$(date +%s)

### --- PLATFORM DEPENDENT CODE ---
rm -f model.conf
for node in $(seq 1 $oas_numproc)
do
    echo "$oas_exe_file" >> model.conf
done

for node in $(seq 1 $ifs_numproc)
do
    echo "$ifs_exe_file -v ecmwf -e  $exp_name" >> model.conf
done

for node in $(seq 1 $nem_numproc)
do
    echo "$nem_exe_file" >> model.conf
done

/usr/bin/poe -pgmmodel mpmd -cmdfile model.conf
### --- END of PLATFORM DEPENDENT CODE ---

t2=$(date +%s)

tr=$(date -d "0 -$t1 sec + $t2 sec" +%T)

# -----------------------------------------------------------------------------
# *** Write the restart control file
# -----------------------------------------------------------------------------
echo "#"                                             | tee -a ${ece_info_file}
echo "# Finished leg at `date '+%F %T'` after ${tr} (hh:mm:ss)" \
                                                     | tee -a ${ece_info_file}
echo "leg_number=${leg_number}"                      | tee -a ${ece_info_file}
echo "leg_start_date=\"${leg_start_date}\""          | tee -a ${ece_info_file}
echo "leg_end_date=\"${leg_end_date}\""              | tee -a ${ece_info_file}

# -----------------------------------------------------------------------------
# *** Platform independent finalising of the run
# -----------------------------------------------------------------------------
# Rename run-files so they are not overwritten in the next leg
filesToCopy="NODE.001_01 rcf $oas_cpl_flds fort.4 ifs.stat ocean.output"
for file in ${filesToCopy}
do
    cp ${file} ${file}.$(printf %03d $((leg_number)))
done
rm -f NODE.001_01

# -----------------------------------------------------------------------------
# *** Platform dependent finalising of the run
# -----------------------------------------------------------------------------
finalise

exit 0
