#!/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_wrf
# flag for cleaning working dir or not
flag_clean=1

# Number of CPUs for each model
# ----------------------------
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=01 ; dy2=31 ; hr2=18
runtime=$((31*24*3600))

# Time Steps
# ----------------------------
atmdt=150

# Outputs Settings
# ----------------------------
wrf_rst_flag=false                 # start from restart ?
wrf_rst_h=24                       # restart interval (h)
wrf_his_h=1                        # output interval (h)
wrf_his_frames=$((31*24))          # nb of outputs per file
wrf_diag_int_m=$((${wrf_his_h}*60))  # diag output interval (m)
wrf_diag_frames=$wrf_his_frames    # nb of diag outputs per file

# MPI Settings for WRF (see WRF namelist documentation README.namelist in real_in directory)
wrf_nprocX=-1      # -1 for automatic settings
wrf_nprocY=-1      # -1 for automatic settings
wrf_niotaskpg=0    # 0 for default settings
wrf_niogp=1        # 1 for default settings

# Path for executables
# ----------------------------
export WRF_EXE_DIR=$wrf/exe_uncoupled

# Namelist file
# ----------------------------
# WRF namelist
wrfnamelist=namelist.input.prep.BENGUELA

# Inputs Settings
# ----------------------------
# date in WRF input files
date='2009_01_2009_01'
# number of WRF domains
nb_dom=1
# is nudging activated?
nudge=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'
cp -f $WRF_EXE_DIR/wrf.exe $MYWORKDIR/wrfexe

## ------------------------ #
## - Copy wrf input files - #
## ------------------------ #

echo 'link input files'
filelist='wrfinput_d01 wrflowinp_d01 wrfbdy_d01'
if [ $nb_dom -ge 2 ] ; then
 filelist="$filelist wrfinput_d02 wrflowinp_d02"
 if [ $nb_dom -eq 3 ] ; then
  filelist="$filelist wrfinput_d03 wrflowinp_d03"
 fi
fi
if [ $nudge -eq 1 ] ; then
 filelist="$filelist wrffdda_d01"
fi
for file in $filelist 
do
 echo "ln -sf ${WRF_FILES_DIR}/${yr1}/${file}_${date} $MYWORKDIR/$file"
 ln -sf ${WRF_FILES_DIR}/${yr1}/${file}_${date} $MYWORKDIR/$file
done
# link data files necessary for running wrf in a dedicated directory $wrf/data
if [ ! -d $wrf/data ] ; then
 mkdir $wrf/data
 ln -s $wrf/run/* $wrf/data/.
 # remove executables that could exist and namelist file
 rm -f $wrf/data/*.exe
 rm -f $wrf/data/namelist.input*
fi
echo 'link wrf data files'
echo "ln -sf ${wrf}/data/* $MYWORKDIR/."
ln -sf ${wrf}/data/* $MYWORKDIR/.

echo 'fill wrf namelist file'
## Fill WRF namelist file
sed -e "s/<yr1>/$yr1/g"   -e "s/<yr2>/$yr2/g"  \
    -e "s/<mo1>/$mo1/g"   -e "s/<mo2>/$mo2/g"  \
    -e "s/<dy1>/$dy1/g"   -e "s/<dy2>/$dy2/g"  \
    -e "s/<hr1>/$hr1/g"   -e "s/<hr2>/$hr2/g"  \
    -e "s/<rst>/$wrf_rst_flag/g"              -e "s/<rst_int_h>/$wrf_rst_h/g"            \
    -e "s/<his_int_h>/${wrf_his_h}/g"         -e "s/<his_nb_out>/${wrf_his_frames}/g"    \
    -e "s/<xtrm_int_m>/${wrf_diag_int_m}/g"   -e "s/<xtrm_nb_out>/${wrf_diag_frames}/g"  \
    -e "s/<nproc_x>/$wrf_nprocX/g"            -e "s/<nproc_y>/$wrf_nprocY/g"             \
    -e "s/<niotaskpg>/$wrf_niotaskpg/g"       -e "s/<niogp>/$wrf_niogp/g"                \
    -e "s/<dt>/${atmdt}/g"                    \
    $WRF_IN_DIR/${wrfnamelist} > $MYWORKDIR/namelist.input

if [ -f $WRF_IN_DIR/myoutfields.txt ]; then
 echo 'copy myoutfields.txt file'
 cp -f $WRF_IN_DIR/myoutfields.txt $MYWORKDIR/.
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 "./wrfexe" >> 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 wrfexe"

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

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

