#!/bin/bash
## Usage
if [ $# -ne 9 ]; 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> <co2_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
co2_interpolate=$9
host=`uname -n`
user=`whoami`

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


exe1='python3 IFS_toy.py'
source_exe1=$srcdir/IFS_toy.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 AMIPDataCoupler.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 CO2BoxDataCoupler.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

CO2_CMODE=false
CO2_EMODE=false

# - 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
        echo 'NOTE: model - fortran / Forcing'  
    else
        . ./namelist_primavera.amip.sh > ./namelist.amip
        echo 'NOTE: model - fortran / PRIMAVERA'
    fi
else
    #if [ $amip_mode = forcing ] || [ $amip_mode = co2 ]; then
    if [ $amip_mode = forcing ] || [ $amip_mode = co2 ]; then
        i=1
        ii=1
        if [ $model = co2box ] || [ $model = datacoupler ]; then
	    var=FileInputVars
	else
	    var=Vars
	fi
        sst_conf_var=${var}"("$((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, ,true,true,"
        sst_conf_var_yml="${var}("$((ii++))"): 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, , true, true"
       
        sic_conf_var=${var}"("$((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,true,true,"
        sic_conf_var_yml="${var}("$((ii++))"): 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, true, true"

        j=1
        jj=1
        oasis_conf_var_yml=""
        oasis_conf_var="!OasisOutputVars(j,:) = <id>, <grid_name>, <timestep>, <scale_factor>, <offset>, <reset>\n"
        oasis_conf_var=$'\n'"OasisOutputVars("$((j++))",:) = 'AMIP_sst', 'AMIP', 'daily', 1, 0, true,"
        oasis_conf_var_yml="OasisOutputVars("$((jj++))") : AMIP_sst, AMIP, daily, 1, 0, true"$'\n'
        oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = 'AMIP_sic', 'AMIP', 'daily', 1, 0, true,"
        oasis_conf_var_yml+="OasisOutputVars("$((jj++))") : AMIP_sic, AMIP, daily, 1, 0, true"$'\n'
        if [ $amip_mode = co2 ]; then
            co2_conf_var=""
	    co2_conf_var+="!FileInputVars(i,:)   = <id> <grid_name> <oasis_name> <file_pattern> <netcdf_variable> <yref_min> <yref_max> <timestep> <interpolate> <scale_factor> <offset> <min> <max> <update> <accum>"$'\n'
            #[ $model = co2box ] && mod=CO2BOX || mod=AMIP
            if [ $model = co2box ] ; then
		mod=CO2BOX
		CO2_CMODE=true # set to false to disable co2 concentrations reading
		CO2_EMODE=true # set to false to disable emissions reading
	    else
		mod=AMIP
		CO2_CMODE=false # don't change this!
		CO2_EMODE=true  # don't change this!
	    fi
            #this fix is required to correctly read the co2 files which havereftime 0-1-1, which isn't supported by python netcdf4
            #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
	    #this fix is required to correctly read the CO2_em_monthly files which have a 365day calendar and also to convert from a grid point/sectors fields to a global one
	    #cdo -L -setcalendar,gregorian -fldsum -vertsum -mul CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc co2-area.nc CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412-global.nc
	    if [ ${CO2_CMODE} == true ] ; then
            co2_conf_var+=${var}"("$((i++))",:) = 'CO2_cconc_monthly', 'GLOBAL', '"$mod"_CO2_cconc', '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', ${co2_interpolate}, 1, 0, , ,true,true,"$'\n'
            co2_conf_var+=${var}"("$((i++))",:) = 'CO2_econc_monthly', 'GLOBAL', '"$mod"_CO2_econc', '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', ${co2_interpolate}, 'co2_ppm_to_mass', 0, , ,false,false,"$'\n'
            co2_conf_var+=${var}"("$((i++))",:) = 'CO2_em_monthly_GLOBAL', 'GLOBAL', '"$mod"_CO2_econc', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412-global.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${co2_interpolate}, 86400, 0, , ,true,true,"$'\n'
	    # add land/ocean fluxes equal to 0.5/0.1 that of emissions, for demonstration purposes
            co2_conf_var+=${var}"("$((i++))",:) = 'CO2_land_monthly_GLOBAL', 'GLOBAL', '"$mod"_CO2_econc', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412-global.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${co2_interpolate}, 43200, 0, , ,true,true,"$'\n'
            co2_conf_var+=${var}"("$((i++))",:) = 'CO2_ocean_monthly_GLOBAL', 'GLOBAL', '"$mod"_CO2_econc', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412-global.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${co2_interpolate}, 8640, 0, , ,true,true,"$'\n'
	    fi
	    if [ ${CO2_EMODE} == true ] ; then
	    # this is the 3D monthly emissions used for ECE4, the calendar fix mentionned below is probably required
        co2_conf_var_yml=""
	    
        
        co2_conf_var+=${var}"("$((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', ${co2_interpolate}, 1, 0, , ,true,true,"$'\n'
        co2_conf_var_yml+="${var}("$((ii++))"): 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, ${co2_interpolate}, 1, 0, , ,true,true"$'\n'
        # add land/ocean fluxes equal to 0.5/0.1 that of emissions, for demonstration purposes
	    co2_conf_var+=${var}"("$((i++))",:) = 'CO2_land_monthly', 'CO2_emis', '"$mod"_CO2_land', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${co2_interpolate}, 0.5, 0, , ,true,true,"$'\n'
	    co2_conf_var_yml+="${var}("$((ii++))"): CO2_land_monthly, CO2_emis, "$mod"_CO2_land, CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc, CO2_em_anthro, 1750, 2018, monthly, ${co2_interpolate}, 0.5, 0, , , true, true"$'\n'
        co2_conf_var+=${var}"("$((i++))",:) = 'CO2_ocean_monthly', 'CO2_emis', '"$mod"_CO2_ocean', 'CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc', 'CO2_em_anthro', 1750, 2018, 'monthly', ${co2_interpolate}, 0.1, 0, , ,true,true,"$'\n'
	    co2_conf_var_yml+="${var}("$((ii++))"): CO2_ocean_monthly, CO2_emis, "$mod"_CO2_ocean, CO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_200001-201412.nc, CO2_em_anthro, 1750, 2018, monthly, ${co2_interpolate}, 0.1, 0, , ,true,true"
	 
        
        
        fi
            #OasisOutputVars(i,:) = <id> <grid_name> <timestep> <scale_factor> <offset> <reset>
	    if [ ${CO2_CMODE} == true ] ; then
            oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = '"$mod"_CO2_cconc', 'GLOBAL', 'daily', 1, 0, true,"
            oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = '"$mod"_CO2_econc', 'GLOBAL', 'daily', 'co2_mass_to_ppm', 0, false,"
	    fi
	    if [ ${CO2_EMODE} == true ] ; then
	    # this is the 3D monthly emissions used for ECE4
            oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = '"$mod"_CO2_emis', 'CO2_emis', 'daily', 1, 0, true,"
            oasis_conf_var_yml+="OasisOutputVars("$((jj++))") : "$mod"_CO2_emis, CO2_emis, daily, 1, 0, true"$'\n'
            oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = '"$mod"_CO2_land', 'CO2_emis', 'daily', 1, 0, true,"
            oasis_conf_var_yml+="OasisOutputVars("$((jj++))") : "$mod"_CO2_land, CO2_emis, daily, 1, 0, true"$'\n'
            oasis_conf_var+=$'\n'"OasisOutputVars("$((j++))",:) = '"$mod"_CO2_ocean', 'CO2_emis', 'daily', 1, 0, true,"
            oasis_conf_var_yml+="OasisOutputVars("$((jj++))") : "$mod"_CO2_ocean, CO2_emis, daily, 1, 0, true"
        fi
        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, , ,"
	co2_conf_var=""
	oasis_conf_var=""
    fi
    . ./namelist_python.amip.sh > ./namelist.amip
    echo 'NOTE: model - fortran / namelist_python.amip.sh'
    . ./namelist_python.amip_yaml.sh > ./namelist.amip.yaml
    [ $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}'
${MPIRUN} -np $nproc_exe1 $exe1 : -np $nproc_exe2 $exe2

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

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

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