#!/bin/bash
### ===========================================================================
###
### Creates initial state for coupler, ocean side
### Take data from NEMO grid_T and icemod files
###
### ===========================================================================
##
##  Warning, to install, configure, run, use any of Olivier Marti's
##  software or to read the associated documentation you'll need at least
##  one (1) brain in a reasonably working order. Lack of this implement
##  will void any warranties (either express or implied).
##  O. Marti assumes no responsability for errors, omissions,
##  data loss, or any other consequences caused directly or indirectly by
##  the usage of his software by incorrectly or partially configured
##  personal.
##

# Usage exemples :
# CreateRestartOce4Oasis.bash /ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/OCE/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_grid_T.nc/ccc/store/c# CreateRestartOce4Oasis.bash /ccc/store/cont003/gencmip6/p86mart/IGCM_OUT/IPSLCM6/DEVT/pdControl/CM6010.2.rivgeo-LR-pdCtrl/OCE/Output/MO/CM6010.2.rivgeo-LR-pdCtrl_22400101_22491231_1M_grid_T.nc
## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

##
## Command line parameters
## ===========================================================================
# Default values
Comment="Preliminary attempt - Do not trust !"
IceVar=ice_pres # siconc #> Variable containing sea ice fraction [0-1]

#
# Defines computer
# ================
if [[ $(hostname) = curie* ]] ; then arch=curie ; center=tgcc ; fi
if [[ $(hostname) = irene* ]] ; then arch=irene ; center=tgcc ; fi

case ${arch} in
    ( curie | irene )
    set +vx
    module unload cdo nco ferret
    module unload netcdf hdf5
    module load python # /2.7.12
    module load netcdf/4.3.3.1_hdf5_parallel # Version for XIOS
    module load nco
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${SCRATCHDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    ;;
    ( * )
    exit -1
    ;;
esac
set -o verbose
set -o xtrace
set -e

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -c   | --comment  ) shift ; Comment=${1} ;;
	( -i   | --ice      ) shift ; IceVar=${1}  ;;
	( -a   | --alb      ) shift ; AlbVar=${1}  ;;
	( -v | --verbose    ) set -o verbose   ;;
	( -x | --xtrace     ) set -o xtrace    ;;
	( -xv | -vx         ) set -o xtrace verbose  ;;
	( -e                ) set -e           ;;
	( -V | --noverbose  ) set +o verbose   ;;
	( -X | --noxtrace   ) set +o xtrace    ;;
	( -XV | -VX         ) set +o xtrace verbose    ;;
	( -E                ) set +e           ;;
	( -* ) echo ${Bold}"Unknown option : ${1}"${Norm} ; return 1 ;;
    esac
    shift
done

OceFile=${1:-/ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/OCE/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_grid_T.nc}

#OceFile=${1:-/ccc/store/cont003/gencmip6/p86mart/IGCM_OUT/IPSLCM6/DEVT/pdControl/CM6010.2.rivgeo-LR-pdCtrl/OCE/Output/MO/CM6010.2.rivgeo-LR-pdCtrl_22400101_22491231_1M_grid_T.nc}
#

#
# Format for OASIS files : should be NetCDF3 classic or NetCDF3 64 bits
# ---------------------------------------------------------------------------
FL_FMT=64bit

##
## Defines associated sea ice file
## ===========================================================================
IceFile=$(echo ${OceFile} | sed 's=/OCE/=/ICE/=' | sed 's=grid_T=icemod=')

##
## Extract variables
## ===========================================================================
ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 -v ${IceVar} ${IceFile} sstoce_fields.nc
ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 -v tos       ${OceFile} oce_fields.nc
ncks --append --fl_fmt=${FL_FMT} --history oce_fields.nc   sstoce_fields.nc
ncwa --overwrite --fl_fmt=${FL_FMT} --history -a time_counter sstoce_fields.nc sstoce_fields_notime.nc # Remove time dimension
ncatted --history --attribute history,global,d,c,""  sstoce_fields_notime.nc           # Clean attributes

##
## Find ocean name
## ===========================================================================
dim_y=$(ncdump -h sstoce_fields_notime.nc | grep "y *=" | awk '{print $3}' )
dim_x=$(ncdump -h sstoce_fields_notime.nc | grep "x *=" | awk '{print $3}' )
echo ${dim_x} ${dim_y}

[[ ${dim_x} = 182 && ${dim_y} = 149 ]] && OCE=ORCA2.3
[[ ${dim_x} = 362 && ${dim_y} = 332 ]] && OCE=eORCA2.1


##
## Creates sstoce file
## ===========================================================================

cat <<EOF > create_sstoce.nco
OIceFrac       = double ( ${IceVar}(:,:) ) ; 
//tos.simple_fill_miss(tos)               ;
O_SSTSST[y,x]  = double ( (tos   (:,:) + 273.15d) * (1.0d-OIceFrac) ) ;
//O_AlbIce[y,x]  = double ( ialb   (:,:)            * OIceFrac(:,:)   ) ;
//O_TepIce[y,x]  = double ( (tsice (:,:) + 273.15d) * OIceFrac(:,:)   ) ;
O_AlbIce[y,x]  = double (   0.65d            * OIceFrac(:,:)   ) ;
O_TepIce[y,x]  = double ( (-20.0d + 273.15d) * OIceFrac(:,:)   ) ;
O_OCurx1[y,x]  = 0.0d ;
O_OCury1[y,x]  = 0.0d ;
O_OCurz1[y,x]  = 0.0d ;
EOF

ncap2 --overwrite --fl_fmt=${FL_FMT} --history -S create_sstoce.nco sstoce_fields_notime.nc tmp_sstoc.nc

ncks --fl_fmt=${FL_FMT} --overwrite --history -v OIceFrac,O_SSTSST,O_AlbIce,O_TepIce,O_OCurx1,O_OCury1,O_OCurz1 tmp_sstoc.nc sstoc.nc

ncatted --history --attribute comment,O_SSTSST,o,c,"SST weighted by fraction of open ocean"          sstoc.nc
ncatted --history --attribute comment,O_SSTSST,o,c,"Albedo weighted by fraction of sea ice"          sstoc.nc
ncatted --history --attribute comment,O_SSTSST,o,c,"Ice temperature weighted by fraction of sea ice" sstoc.nc

##
## Add some information in file headers
## ===========================================================================

UUID=$(uuid)
NCO="$(ncks --version |& tail -1|sed 's/ncks //')"
ncatted --history \
	--attribute nco_openmp_thread_number,global,d,,                       \
	--attribute source,global,o,c,"IPSL Earth system model"               \
	--attribute group,global,o,c,"ICMC IPSL Climate Modelling Center"     \
	--attribute Institution,global,o,c,"IPSL https://www.ipsl.fr"         \
	--attribute Model,global,o,c,"${OCE} https://www.nemo-ocean.eu"       \
	--attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}')" \
	--attribute originalFiles,global,o,c,"${OceFile} ${IceFile}"          \
	--attribute directory,global,o,c,"$(pwd)"                             \
	--attribute description,global,o,c,"Fields needed by OASIS-MCT"       \
	--attribute timeStamp,global,o,c,"$(date)"                            \
	--attribute uuid,global,o,c,"${UUID}"                                 \
	--attribute Program,global,o,c,"Generated by ${0}"                    \
	--attribute HOSTNAME,global,o,c,"$(hostname)"                         \
	--attribute LOGNAME,global,o,c,"$(whoami)"                            \
	--attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	--attribute OS,global,o,c,"$(uname -o)"                               \
	--attribute release,global,o,c,"$(uname -r)"                          \
	--attribute hardware,global,o,c,"$(uname -i)"                         \
	--attribute directory,global,o,c,"$(pwd)"                             \
	--attribute Comment,global,o,c,"${Comment}"                           \
	sstoc.nc

##
## Cleaning
## ===========================================================================
rm -f sstoce_fields.nc sstoce_fields_notime.nc tmp_flxat.nc oce_fields.nc

mv sstoc.nc sstoc_${OCE}.nc

## ===========================================================================
##
##                               That's all folk's !!!
##
## ===========================================================================
