#!/bin/bash -e

# --------------------------------------------------
#
# Script to launch coupled simulations with WRF, WW3 and CROCO 
#
# --------------------------------------------------
#
# Further Information:   
# http://www.croco-ocean.org
#  
# This file is part of CROCOTOOLS
#
# CROCOTOOLS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# CROCOTOOLS is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA
#
# Copyright (c) 2018 S. Jullien
# swen.jullien@ifremer.fr
# --------------------------------------------------

#=========================================================================
#=======================  USER CHANGES  ==================================
#=========================================================================

# source file exporting paths 
# for the configuration
# ----------------------------
source run_env

# Path of working directory 
#(where the simulations are launched)
# ----------------------------
export MYWORKDIR=$wconf/outputs_frc_croco
# flag for cleaning working dir or not
flag_clean=1

# Number of CPUs
# ----------------------------
NBPROC_1=$1
#MPI_LAUNCH_CMD="mpirun"
#MPI_LAUNCH_CMD="poe"
MPI_LAUNCH_CMD=$MPI_LAUNCH

# Runtime Settings
# ----------------------------
yr1=2009 ; mo1=01 ; dy1=01 ; hr1=00
yr2=2009 ; mo2=02 ; dy2=01 ; hr2=00
runtime=$((31*24*3600))

# Time Steps
# ----------------------------
ocedt=3600 ; ocendtfast=60; ocentimes=$((${runtime}/${ocedt}))

# Outputs Settings
# ----------------------------
oce_nrst=24    # restart interval (in number of timesteps) 
oce_nhis=1     # history output interval (in number of timesteps) 
oce_navg=1     # average output interval (in number of timesteps) 

# Path for executables
# ----------------------------
export CROCO_EXE_DIR=$PWD/croco_in

# Inputs Settings
# ----------------------------
# suffix for CROCO executable
crocosuffix='.frc'
# list of CROCO input files
inputlist='ini bry frc'
# suffix for CROCO input files
datesuffix=''
datesuffixcfsr='_Y20??M*'
# if online interpolation of atmospheric fields is used
interponline=0

#=========================================================================
#=======================  END USER CHANGES  ==============================
#=========================================================================

## ---------------------------- #
## - Create and Clean Workdir - #
## ---------------------------- #

if ! [ -e $MYWORKDIR ] ; then
 echo 'create working directory: '$MYWORKDIR
 mkdir $MYWORKDIR
elif [ $flag_clean == 1 ] ; then
 echo 'clean working directory: '$MYWORKDIR
 rm -Rf $MYWORKDIR/*
fi

## -------------------- #
## - Copy executables - #
## -------------------- #

echo 'copy executables and settings'
cp -f $CROCO_EXE_DIR/croco$crocosuffix $MYWORKDIR/crocox
cp -f $CROCO_EXE_DIR/cppdefs.h$crocosuffix $MYWORKDIR/.
cp -f $CROCO_EXE_DIR/param.h $MYWORKDIR/.

## -------------------------- #
## - Copy CROCO input files - #
## -------------------------- #

echo 'fill namelist croco.in'
## - Fill croco.in file -##
sed -e "s/<ocentimes>/$ocentimes/g" -e "s/<ocedt>/$ocedt/g"       -e "s/<ocendtfast>/$ocendtfast/g" \
    -e "s/<oce_nrst>/$oce_nrst/g"   -e "s/<oce_nhis>/$oce_nhis/g" -e "s/<oce_navg>/$oce_navg/g"     \
    -e "s/<yr1>/$yr1/g"             -e "s/<mo1>/$mo1/g"           \
    -e "s/<yr2>/$yr2/g"             -e "s/<mo2>/$mo2/g"           \
    $CROCO_IN_DIR/croco.in.base > $MYWORKDIR/croco.in

echo 'link input files'
echo "ln -sf ${CROCO_FILES_DIR}/croco_grd.nc $MYWORKDIR/"
ln -sf ${CROCO_FILES_DIR}/croco_grd.nc $MYWORKDIR/.
for file in $inputlist ; do
 echo "ln -sf ${CROCO_FILES_DIR}/croco_${file}${datesuffix}.nc $MYWORKDIR/croco_${file}.nc"
 ln -sf ${CROCO_FILES_DIR}/croco_${file}${datesuffix}.nc $MYWORKDIR/croco_${file}.nc
done

if [ $interponline == 1 ] ; then
 for varlist in Downward_Short-Wave_Rad_Flux_surface \
                Downward_Long-Wave_Rad_Flux \
                Upward_Long-Wave_Rad_Flux_surface \
                Upward_Short-Wave_Rad_Flux_surface \
                U-component_of_wind \
                V-component_of_wind \
                Precipitation_rate \
                Temperature_height_above_ground \
                Specific_humidity \
                Temperature_surface
 do
  echo "ln -sf ${CROCO_FILES_DIR}/*/${varlist}${datesuffixcfsr}.nc $MYWORKDIR/."
  ln -sf ${CROCO_FILES_DIR}/*/${varlist}${datesuffixcfsr}.nc $MYWORKDIR/.
 done
fi

## ------------- #
## - Execution - #
## ------------- #

echo 'enter in the working directory'
cd $MYWORKDIR
pwd

# Prepare MPI run command
if [ $MPI_LAUNCH_CMD == poe ] ; then
 for nn in $(seq 1 $NBPROC_1); do
  echo "./crocox" >> run_file
 done
 chmod +x run_file
 mpirun_cmd="poe  -pgmmodel MPMD -cmdfile ./run_file"
else
#elif [ $MPI_LAUNCH_CMD == mpirun ] ; then
 mpirun_cmd="$MPI_LAUNCH_CMD -np $NBPROC_1 crocox"

#else
# echo 'ERROR: '$MPI_LAUNCH_CMD' not implemented yet... Exit'
# exit
fi

echo 'launch run: '$mpirun_cmd
# RUN
$mpirun_cmd

