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

# - Define number of processes to run each executable
nproc_exe1=$2
nproc_exe2=1 # AMIP is always one process

leg_start_date=$3
leg_end_date=$4
ifs_cmip_fixyear=$5

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

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


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

if [ $1 = fortran ]; then
    exe2=amip-forcing
    source_exe2=$srcdir/../sources/amip-forcing/bin/amip-forcing
elif [ $1 = python ]; then
    exe2='python3 amip_forcing.py'
    # exe2='coverage run amip_forcing.py'
    # exe2='python3 -m cProfile -s cumtime amip_forcing.py'
    source_exe2=$srcdir/../sources/amip-forcing/src/python/*.py
else
    echo 'Invalid args. You must specify a language for the AMIP reader: <fortran | python>'
    exit 1
fi

# - Define rundir
rundir=${srcdir}/work_${1}_${nproc_exe1}_${nproc_exe2}_${leg_start_date}_${leg_end_date}_${ifs_cmip_fixyear}


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/.
ln -sf $datadir/*.nc  $rundir/.
cp -f $datadir/*.sh  $rundir/.
cp -f $source_exe1 $rundir/.
cp -f $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)

. ./namelist.amip.sh > ./namelist.amip
. ./namcouple.sh > ./namcouple

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

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

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

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