#!/bin/bash
## Usage

if [ $# -ne 10 ]; then
    echo 'Invalid args.'
    echo 'Usage ./run_example.sh <model> <model_mode> <ifs_nproc> <leg_start_date> <leg_end_date> <ifs_cmip_fixyear> <ifs_grid> <amip_interpolate> <co2_interpolate> <YAML_template.yaml>'
    echo 'Try .bash ./run_example.sh datacoupler forcing 4 2005-01-01 2005-03-01 0 128 true false template_conf_datacoupler_forcing.yaml'
    exit 1
fi

set -xuve

model=$1
model_mode=$2 # forcing, primavera or co2box
# - Define number of processes to run each executable
nproc_exe1=$3
nproc_exe2=1 # AMIP is always one process

leg_start_date=$4
leg_end_date=$5
ifs_cmip_fixyear=$6
ifs_grid=$7
amip_interpolate=$8
co2_interpolate=$9
yaml_conf_template=${10}
host=`uname -n`
user=`whoami`

## - Define paths
srcdir=`pwd`
datadir=$srcdir/data

# ece_3_toy_model as exe1 
exe1='python3 toy_model.py'
source_exe1=/../$srcdir/../sources/ece3-toy-model/toy_model.py


if [ $model = fortran ]; then
    exe2='./amip-forcing'
    if [ $model_mode = forcing ]; then
        source_exe2=$srcdir/../sources/amip-forcing/bin/amip-forcing
    else
        source_exe2=$srcdir/../sources/amip-primavera/bin/amip-forcing
    fi
elif [ $model = python ] || [ $model = pythoncompat ]; then
    exe2='python3 amip_forcing.py'

    source_exe2=$srcdir/../sources/amip-forcing/src/python/*.py
elif [ $model = datacoupler ] ; then
    exe2='python3 DataCoupler.py'

    source_exe2=$srcdir/../sources/data-coupler/*.py

else
    echo 'Invalid args. You must specify a language for the AMIP reader: <fortran | python> | <pythoncompat>'
    exit 1
fi

# - Define rundir
rundir=${srcdir}/work_${model}_${model_mode}_${nproc_exe1}_${leg_start_date}_${leg_end_date}_${ifs_cmip_fixyear}_${ifs_grid}_${amip_interpolate}


echo '*****************************************************************'
#echo '*** '$casename' : '$run
echo ''
echo 'Rundir       :' $rundir
#echo 'Architecture :' $arch
echo 'Host         : '$host
echo 'User         : '$user
echo ''
echo $exe1' runs on '$nproc_exe1 'processes'
echo $exe2' runs on '$nproc_exe2 'processes'
echo ''
######################################################################
### Create rundir and copy everything needed

\rm -fr $rundir
mkdir -p $rundir
ln -sf $datadir/ICMGGa22e+000000  $rundir/.
ln -sf $datadir/*.txt  $rundir/.
# Get SST and SIC
if [ $model_mode = forcing ]; then
    ln -sf $datadir/forcing/siconcbcs*.nc  $rundir/.
    ln -sf $datadir/forcing/tosbcs*.nc  $rundir/.
    ln -sf $datadir/forcing/rmp_AMIP_to_L${ifs_grid}_GAUSWGT*.nc $rundir/.
elif [ $model_mode = primavera ]; then
    ln -sf $datadir/$model_mode/HadI*.nc  $rundir/.
    ln -sf $datadir/$model_mode/rmp_PSIC_to_${ifs_grid}_GAUSWGT.nc $rundir/.
    ln -sf $datadir/$model_mode/rmp_PSST_to_${ifs_grid}_GAUSWGT.nc $rundir/.
fi
if [ $model=datacoupler ]; then
    ln -sf $datadir/forcing/siconcbcs*.nc  $rundir/.
    ln -sf $datadir/forcing/tosbcs*.nc  $rundir/.
    ln -sf $datadir/forcing/rmp_AMIP_to_L${ifs_grid}_GAUSWGT*.nc $rundir/.
    
    ln -sf $datadir/co2/CO2-em-anthro_*.nc $rundir/.
    ln -sf $datadir/co2/CO2-em-AIR-anthro_*.nc $rundir/.
    ln -sf $datadir/co2/mole-fraction-of-carbon-dioxide-in-air_*.nc* $rundir/.
    ln -sf $datadir/co2/rmp_CO2_emis_to_B${ifs_grid}_GAUSWGT*.nc $rundir/.
fi
# Get grids and masks
if [ $model = fortran ] || [ $model = pythoncompat ]; then
    cp -f $datadir/$model_mode/masks.nc  $rundir/.
    cp -f $datadir/$model_mode/grids.nc  $rundir/.
    cp -f $datadir/$model_mode/areas.nc  $rundir/.
else
    cp -f $datadir/grids-noamip.nc  $rundir/grids.nc
    cp -f $datadir/masks-noamip.nc  $rundir/masks.nc
    cp -f $datadir/areas-noamip.nc  $rundir/areas.nc
fi
#cp -f $datadir/*.sh  $rundir/.
cp -f $datadir/convert-ece4pyreader-grids.sh  $rundir/.
cp -f $datadir/*.yaml  $rundir/.
ln -sf $source_exe1 $rundir/.
ln -sf $source_exe2 $rundir/.
cp -f $srcdir/*.py $rundir/.
cd $rundir

######################################################################
### Generate namelist
leg_length_sec=$(( $(date -u -d "${leg_end_date}" +%s) - $(date -u -d "${leg_start_date}" +%s) ))
cpl_freq_amip_sec=86400 # Always
leg_start_date_yyyymmdd=$(date -u -d "${leg_start_date}" +%Y%m%d)

if [ $model = fortran ] || [ $model = pythoncompat ]; then
    if [ $model_mode = forcing ]; then
        . ./namelist.amip.sh > ./namelist.amip
        . ./namcouple.sh > ./namcouple

    elif [ $model_mode = primavera ]; then
        . ./namelist_primavera.amip.sh > ./namelist.amip
        . ./namcouple_primavera.sh > ./namcouple
    else
    echo 'Error: for fortran or pythoncompat models, Only forcing or primavera is valid for mode.' 
    exit 9 
    fi
else
     
    # Comleting the YAML template that user has provided and store it (yaml_conf_file) 
    
    # TODO: dynamically generate YAML file name based on the exp.
    #yaml_conf_file=$(grep -F "ModelNameReceive" "$yaml_conf_template" | awk '{print $3}')'_exp_conf.yaml' 
    yaml_conf_file='DataCoupler_exp_conf.yaml' 
    . ./$yaml_conf_template > $yaml_conf_file

    # Generating a namcouple  based on the input on the YAML file above to be used by OASIS 
    namcouple_output="namcouple"
    toy_model_yaml_conf_output="yaml_conf_file_ifs_toy_model.yaml"
    
    # Run the py namcouple creator
    namlist_yaml_conf_creator_script='python3 DataCouplerPreprocessor.py' 
    $namlist_yaml_conf_creator_script --conf $yaml_conf_file --namcouple_output $namcouple_output --toy_model_yaml_conf_output $toy_model_yaml_conf_output
fi

######################################################################
### Definition of mpirun command and batch script

echo 'Executing the model using mpirun : ${MPIRUN}'

# To seprate the DataCoupler with YAML input file from legecy codes 
if  [ $model = datacoupler ] ; then
    ${MPIRUN} -np $nproc_exe1 $exe1 --conf $toy_model_yaml_conf_output : -np $nproc_exe2 $exe2 --conf $yaml_conf_file 
else
    ${MPIRUN} -np $nproc_exe1 $exe1 : -np $nproc_exe2 $exe2
fi


# convert output
. convert-ece4pyreader-grids.sh ${leg_start_date}

#echo $casename 'is executed or submitted to queue.'
echo 'Results are found in rundir : '$rundir 
echo 'Run Example is successfully executed'

######################################################################
