#!/bin/bash

# 
# This script creates the file "ECDYN.nc" for a given date 
# defined by year, month, day and hour between 0, 6, 12 or 18hGMT
# using ERA5 data at IDRIS, spirit2, spirit1 or on your local machine using
# data from spirit2, provided that you have an account on spirit2.
#
# You need to be in the UNIX group subipsl at IDRIS or in the
# UNIX group ecmwf on spirit2, to access the data. 
#
# This main script is calling 2 scripts: get_ERA.sh and create_ECDYN_ERA.sh
#
# get_ERA.sh extracts the data (u, v, ta, r, etc; see $VARS below) 
# from ERA reanalyses at the chosen date on your actual directory
#
# create_ECDYN_ERA.sh merges the data into ECDYN.nc, together with an ancien
# CDSW field (see below) and renames different fields.
# 
# "ECDYN.nc" also contains ST and CDSW (which could be in "ECPHY.nc").
# CDSW is not modified because we do not know what to put into it.
#
# NB: The field CDSW is coming from the file ECDYN_high_res.nc 
# available here :
# https://www.lmd.jussieu.fr/~lmdz/pub/3DInputData/Init/ECDYN_high_res.nc
#
# This script was largely inspired by the script "create_ECDYN.sh"
# available at "https://lmdz.lmd.jussieu.fr/utilisateurs/utilisation-de-lmdz"
# written by Lionel GUEZ.
# It was completely rewritten and parameterized as follows:
#
# 1/ getting data fields (script get_ERA.sh) was separated from 
#    the merging part (script create_ECDYN_ERA.sh)
# 2/ it allows to get any day and hour of a given year and month. 
# 3/ it allows to use ERA5 dataset
#
# Usage :
#
# ./ECDYN_ERA.sh $machine $year $month $day $hour
#
# For example, to create ECDYN.nc 
# on spirit2 for 1995 year, January 1st at 0h,
# launch ./ECDYN_ERA.sh as below :
#
# ./ECDYN_ERA.sh spirit2 1995 01 01 0
#
# Author: Ionela MUSAT, 1st April 2022
#

echo $host may be spirit2 or IDRIS
host=$1
year=$2
month=$3
day=$4
hour=$5

ana=ERA5
mesolog=`whoami`
resol=GLOBAL_025

echo
echo get the input data for ECDYN.nc for ${year}${month}${day} at ${hour}GMT
echo 

VARS="u v ta r geopt stl1 sp"

for var in $VARS; do

case $var in
          ta) freq=hourly
                    ddt=AN_PL
                    suf=ap1e5
                    ndpd=24 ;;
          u|v|r) freq=4xdaily
                    ddt=AN_PL
                    suf=aphe5
                    ndpd=4 ;;
          geopt|stl1|sp) freq=hourly
                    ddt=AN_SF
                    suf=as1e5
                    ndpd=24 ;;
esac

   ./get_ERA.sh ${ana} ${host} ${mesolog} ${resol} ${freq} ${ddt} ${suf} ${ndpd} ${year} ${month} ${day} ${hour} ${var}

done

echo
echo merge input data into ECDYN.nc for ${year}${month}${day} at ${hour}GMT
echo 

./create_ECDYN_ERA.sh ${host} ${year} ${month} ${day} ${hour}

exit
