#!/bin/bash
## Usage
if [ $# -ne 8 ]; then
    echo 'Invalid args.'
    echo 'Usage ./run_example.sh <lang> <amip_mode> <ifs_nproc> <leg_start_date> <leg_end_date> <ifs_cmip_fixyear> <ifs_grid> <amip_interpolate>'
    echo 'Try ./run_example.sh python forcing 4 1990-01-01 1991-01-01 0 L128 true'
    exit 1
fi

set -xuve

model=$1
amip_mode=$2 # forcing or primavera
# - 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

host=`uname -n`
user=`whoami`

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


exe1='python3 IFS_mock.py'
source_exe1=$srcdir/IFS_mock.py

if [ $model = fortran ]; then
    exe2='./amip-forcing'
    if [ $amip_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'
    # exe2='coverage run -p --branch --include=*/amip-forcing/src/python/* amip_forcing.py'
    # exe2='python3 -m cProfile -s cumtime amip_forcing.py'
    source_exe2=$srcdir/../sources/amip-forcing/src/python/*.py
elif [ $model = datacoupler ] ; then
    exe2='python3 DataCouplerAMIP.py'
    # exe2='coverage run -p --branch --include=*/amip-forcing/src/python/* amip_forcing.py'
    # exe2='python3 -m cProfile -s cumtime amip_forcing.py'
    source_exe2=$srcdir/../sources/data-coupler/*.py
elif [ $model = co2box ] ; then
    exe2='python3 DataCouplerCO2Box.py'
    # exe2='coverage run -p --branch --include=*/amip-forcing/src/python/* amip_forcing.py'
    # exe2='python3 -m cProfile -s cumtime amip_forcing.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}_${amip_mode}_${nproc_exe1}_${leg_start_date}_${leg_end_date}_${ifs_cmip_fixyear}_${ifs_grid}_${amip_interpolate}
# export COVERAGE_FILE=${rundir}/../.coverage

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 [ $amip_mode = forcing ] || [ $amip_mode = co2 ]; then
if [ $amip_mode = forcing ] || [ $amip_mode = co2 ] ; 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/.
    if [ $amip_mode = co2 ]; then
        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
else
    ln -sf $datadir/$amip_mode/HadI*.nc  $rundir/.
    ln -sf $datadir/$amip_mode/rmp_PSIC_to_${ifs_grid}_GAUSWGT.nc $rundir/.
    ln -sf $datadir/$amip_mode/rmp_PSST_to_${ifs_grid}_GAUSWGT.nc $rundir/.
fi
# Get grids and masks
if [ $model = fortran ] || [ $model = pythoncompat ]; then
    cp -f $datadir/$amip_mode/masks.nc  $rundir/.
    cp -f $datadir/$amip_mode/grids.nc  $rundir/.
    cp -f $datadir/$amip_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 $source_exe1 $rundir/.
ln -sf $source_exe2 $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 [ $amip_mode = forcing ]; then
        . ./namelist.amip.sh > ./namelist.amip
    else
        . ./namelist_primavera.amip.sh > ./namelist.amip
    fi
else
    #if [ $amip_mode = forcing ] || [ $amip_mode = co2 ]; then
    if [ $amip_mode = forcing ] || [ $amip_mode = co2 ]; then
        i=1
        sst_conf_var="Vars("$((i++))",:) = 'AMIP_sst_monthly', 'AMIP', 'AMIP_sst', 'tosbcs_input4MIPs_SSTsAndSeaIce_CMIP_PCMDI-AMIP-1-1-3_gn_187001-201706.nc', 'tosbcs', 1870, 2016, 'monthly', ${amip_interpolate}, 1, 273.15, 271.38, ,"
        sic_conf_var="Vars("$((i++))",:) = 'AMIP_sic_monthly', 'AMIP', 'AMIP_sic', 'siconcbcs_input4MIPs_SSTsAndSeaIce_CMIP_PCMDI-AMIP-1-1-3_gn_187001-201706.nc', 'siconcbcs', 1870, 2016, 'monthly', ${amip_interpolate}, 0.01, 0, 0, 1,"
        if [ $amip_mode = co2 ]; then
            [ $model = co2box ] && mod=CO2BOX || mod=AMIP
            co2_conf_var="Vars("$((i++))",:) = 'CO2_em_monthly', 'CO2_emis', '"$mod"_CO2_emis', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${amip_interpolate}, 1, 0, , ,"
            co2_conf_var+=$'\n'"Vars("$((i++))",:) = 'CO2_em_AIR_anthro', 'CO2_emis', '"$mod"_CO2_emis', 'CO2-em-AIR-anthro_input4MIPs_emissions_CMIP_CEDS-2017-08-30_gn_200001-201412.nc', 'CO2_em_AIR_anthro', 1750, 2018, 'monthly', ${amip_interpolate}, 1, 0, , ,"
            #this fix is required to parse the co2 files which havereftime 0-1-1, which isn't supported by python
            #cdo -R -setreftime,1849-01-01,00:00 mole-fraction-of-carbon-dioxide-in-air_input4MIPs_GHGConcentrations_CMIP_UoM-CMIP-1-2-0_gr1-GMNHSH_184901-201412.nc mole-fraction-of-carbon-dioxide-in-air_input4MIPs_GHGConcentrations_CMIP_UoM-CMIP-1-2-0_gr1-GMNHSH_184901-201412.nc.mod
            co2_conf_var+=$'\n'"Vars("$((i++))",:) = 'CO2_conc_monthly', 'CO2_conc', '"$mod"_CO2_conc', 'mole-fraction-of-carbon-dioxide-in-air_input4MIPs_GHGConcentrations_CMIP_UoM-CMIP-1-2-0_gr1-GMNHSH_184901-201412.nc.mod', 'mole_fraction_of_carbon_dioxide_in_air', 1849, 2014, 'monthly', false, 1, 0, , ,"
        else
            co2_conf_var=""
        fi
    else
        sst_conf_var="Vars(1,:) = 'AMIP_sst_daily', 'PSST', 'AMIP_sst', 'HadISST2_prelim_0to360_alldays_sst_[year].nc', 'sst', 1850, 2016, 'daily', false, 1, 0, , ,"
        sic_conf_var="Vars(2,:) = 'AMIP_sic_daily', 'PSIC', 'AMIP_sic', 'HadISST2_prelim_0to360_alldays_sic_[year].nc', 'sic', 1850, 2016, 'daily', false, 1, 0, , ,"
    fi
    . ./namelist_python.amip.sh > ./namelist.amip
    [ $model = co2box ] &&  . ./namelist.co2box.sh > ./namelist.co2box
fi
if [ $amip_mode = forcing ]; then
    . ./namcouple.sh > ./namcouple
elif [ $amip_mode = co2 ]; then
    [ $model = co2box ] && . ./namcouple_co2box.sh > ./namcouple || . ./namcouple_co2.sh > ./namcouple
else
    . ./namcouple_primavera.sh > ./namcouple
fi

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

echo 'Executing the model using mpirun'
mpirun -np $nproc_exe1 $exe1 : -np $nproc_exe2 $exe2

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

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

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