#!/usr/bin/env 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.
##
###
### Documentation : https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/MOSAIX
###
## SVN information
#  $Author$
#  $Date$
#  $Revision$
#  $Id$
#  $HeadURL$

## Usage exemples :
#
# CreateRestartOce4Oasis.bash --ocefile /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 --icefile /ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/ICE/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_icemod.nc --icefrc ice_pres --icetem tsice --icealb ialb
#
# CreateRestartOce4Oasis.bash --ocefile /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 --icefrc siconc

# CreateRestartOce4Oasis.bash --ocefile /ccc/store/cont003/gen7451/personr/IGCM_OUT/ORCA025_LIM3_PISCES/DEVT/ORCA025ia/eOR025L3P-IA-REF07-MUSCL/OCE/Output/MO/eOR025L3P-IA-REF07-MUSCL_20090101_20091231_1M_grid_T.nc
#
# CreateRestartOce4Oasis.bash --ocefile /ccc/work/cont003/gencmip6/p48ethe/ICMC-TOOLS/DATA/eOR025L3P-IA-REF07-MUSCL_20090101_20091231_1M_grid_T.nc --icefile /ccc/work/cont003/gencmip6/p48ethe/ICMC-TOOLS/DATA/eOR025L3P-IA-REF07-MUSCL_20090101_20091231_1M_icemod.nc --icefrc siconc/oce --icetem sistem
# 
# 
## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

##
## Command line parameters
## ===========================================================================
# Default values
Comment="Preliminary attempt - Do not trust !"
#
# --ocefile : file in which sea surface temperature is read
# --icefile : file in which sea ice fraction, albedo and surface temperature are read.
#             if not specified, these variables are readed in the ocean file
#
## Variable in ocean file :
OceSst=tos      #> Variable containing sea surface temperature (°C) : --ocesst tos
## Variables in ice file
IceFrc=ice_pres #> Variable containing sea ice fraction [0-1]       : --icefrc ice_pres
IceAlb=none     #> Variable containing sea ice albedo [0-1]. If 'none', set to 0.65         : --icealb ialb
IceTem=none     #> Variable containing sea ice surface temperature (°C). If 'none', set to -20°C : --icetem tsice

# Complementary syntaxes for variables names
# --icefrc siconc/oce means that siconc variable should be taken in the ocean file ...
# --icealb ialb/oce
# --icetem tsice/oce

## Filling
# If the ocean in the coupled model has a different geometry that the one in the files.
# In general, the forced ocean does run with no closed sea, when the coupled model does.
# This step is he mandatory
Fill=yes # If yes, fill the continents. --fill / --nofill

# nperio parameter for ORCA. Normally guess from name or dimensions. For ORCA2, set to nperio=4, but should be set to nperio=6 for some paleo configs
# --nperio 4

DefaultIceAlb=0.65
DefaultIceTem=-20.0

#OceFile=/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=/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
#

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

case ${arch} in
    ( 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
    module load python3
    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

Nperio=""

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -c   | --comment  ) shift ; Comment=${1}  ;;
	( --ocefile         ) shift ; OceFile=${1}  ;;
	( --icefile         ) shift ; IceFile=${1}  ;;
	( --ocesst          ) shift ; OceSst=${1}   ;;
	( --icefrc          ) shift ; IceFrc=${1}   ;;
	( --icetem          ) shift ; IceTem=${1}   ;;
	( --icealb          ) shift ; IceAlb=${1}   ;;
	( --fill            ) Fill="yes" ;;
	( --nofill          ) Fill="no"  ;;
	( --nperio          ) shift ; Nperio="--nperio ${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} ; exit 1 ;;
    esac
    shift
done

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

##
## Defines associated sea ice file
## ===========================================================================
if [[ -z ${IceFile} ]] ; then IceFile=${OceFile} ; fi
IceFrcFile=${IceFile}
IceTemFile=${IceFile}
IceAlbFile=${IceFile}

## Select file for each variable
OceSstFile=${OceFile}
if [[ ${OceSst} = */ice ]] ; then
    OceSstFile=${IceFile}
    OceSst=${OceSst%%/*}
fi


if [[ ${IceAlb} = */oce ]] ; then
    IceAlbFile=${OceFile}
    IceAlb=${IceFrc%%/*}
fi
if [[ ${IceFrc} = */oce ]] ; then
    IceFrcFile=${OceFile}
    IceFrc=${IceFrc%%/*}
fi
if [[ ${IceTem} = */oce ]] ; then
    IceTemFile=${OceFile}
    IceTem=${IceTem%%/*}
fi


echo "Oce sst         - Variable ${OceSst} - File ${OceSstFile}"
echo "Ice fraction    - Variable ${IceFrc} - File ${IceFrcFile}"
echo "Ice albedo      - Variable ${IceAlb} - File ${IceAlbFile}"
echo "Ice temperature - Variable ${IceTem} - File ${IcetemFile}"


##
## Extract variables
## ===========================================================================
ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 --variable ${IceFrc} ${IceFrcFile} sstoce_fields.nc
ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 --variable ${OceSst} ${OceSstFile} oce_sst.nc

ncks --append    --fl_fmt=${FL_FMT} --history oce_sst.nc   sstoce_fields.nc
if [[ "X${IceAlb}" != "Xnone" ]] ; then
    ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 --variable ${IceAlb} ${IceAlbFile} ice_alb.nc
    ncks --append    --fl_fmt=${FL_FMT} --history ice_alb.nc   sstoce_fields.nc
fi
if [[ "X${IceTem}" != "Xnone" ]] ; then
    ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 --variable ${IceTem} ${IceTemFile} ice_tem.nc
    ncks --append    --fl_fmt=${FL_FMT} --history ice_tem.nc   sstoce_fields.nc
fi
ncwa --overwrite --fl_fmt=${FL_FMT} --history --average 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 *=" | grep -v "nvertex" | awk '{print $3}' )
dim_x=$(ncdump -h sstoce_fields_notime.nc | grep "x *=" | grep -v "nvertex" | awk '{print $3}' )
echo ${dim_x} ${dim_y}

[[ ${dim_x} =  182 && ${dim_y} =  149 ]] && OCE=ORCA2.3
[[ ${dim_x} =  362 && ${dim_y} =  332 ]] && OCE=eORCA1.2
[[ ${dim_x} = 1442 && ${dim_y} = 1207 ]] && OCE=eORCA025.1

##
## Creates sstoce file
## ===========================================================================
cat <<EOF > create_sstoce.nco
*OceSst[y,x]    = double ( ${OceSst}(:,:) + 273.15d ) ;
OIceFrc[y,x]   = double ( ${IceFrc}(:,:) ) ; 
//
EOF

if [[ "X${IceAlb}" != "Xnone" ]] ; then
    cat <<EOF >> create_sstoce.nco
*IceAlb[y,x]  = double ( ${IceAlb}(:,:) ) ;
//
EOF
else
     cat <<EOF >> create_sstoce.nco
*IceAlb[y,x] = double ( ${DefaultIceAlb}d ) ;
//
EOF
fi

if [[ "X${IceTem}" != "Xnone" ]] ; then
    cat <<EOF >> create_sstoce.nco
*IceTem[y,x] = double ( ${IceTem}(:,:) + 273.15d ) ;
//
EOF
else
     cat <<EOF >> create_sstoce.nco
*IceTem[y,x] = double ( ${DefaultIceTem}d + 273.15d ) ;
//
EOF
fi

cat <<EOF >>  create_sstoce.nco
O_SSTSST[y,x]  = OceSst (:,:) * (1.0d-OIceFrc(:,:)) ;
O_AlbIce[y,x]  = IceAlb (:,:)       * OIceFrc(:,:)  ;
O_TepIce[y,x]  = IceTem (:,:)       * OIceFrc(:,:)  ;
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 --script-file create_sstoce.nco sstoce_fields_notime.nc tmp_sstoc.nc
ncks --fl_fmt=${FL_FMT} --overwrite --history --variable OIceFrc,O_SSTSST,O_AlbIce,O_TepIce,O_OCurx1,O_OCury1,O_OCurz1 tmp_sstoc.nc sstoc.nc
ncatted --history --attribute long_name,O_SSTSST,o,c,"SST weighted by fraction of open ocean"          sstoc.nc
ncatted --history --attribute long_name,O_AlbIce,o,c,"Albedo weighted by fraction of sea ice"          sstoc.nc
ncatted --history --attribute long_name,O_TepIce,o,c,"Ice temperature weighted by fraction of sea ice" sstoc.nc

ncatted --history --attribute comment,O_SSTSST,o,c,"Variable ${OceSst} taken in ${OceSstFile}"  sstoc.nc
ncatted --history --attribute comment,OIceFrc,o,c,"Variable ${IceFrc} taken in ${IceFrcFile}"   sstoc.nc

if [[ ${IceAlb} = none ]] ; then  ncatted --history --attribute comment,O_AlbIce,o,c,"Set to ${DefaultIceAlb}"  sstoc.nc
else                              ncatted --history --attribute comment,O_AlbIce,o,c,"Variable ${IceAlb} taken in ${IceAlbFile}"  sstoc.nc
fi
if [[ ${IceTem} = none ]] ; then  ncatted --history --attribute comment,O_TepIce,o,c,"Set to ${DefaultIceTem}"  sstoc.nc
else                              ncatted --history --attribute comment,O_TepIce,o,c,"Variable ${IceTem} taken in ${IceTemFile}"  sstoc.nc
fi

##
## Filling the fields
## ===========================================================================
if [[ ${Fill} = yes ]] ; then
    mv sstoc.nc sstoc_nofilled.nc
    python3 FillOceRestart.py --input sstoc_nofilled.nc --output sstoc.nc ${Nperio}
fi

##
## Add some information in file header
## ===========================================================================

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}"                           \
	--attribute SVN_Author,global,o,c,"$Author$"                 \
        --attribute SVN_Date,global,o,c,"$Date$" \
	--attribute SVN_Revision,global,o,c,"$Revision$"               \
	--attribute SVN_Id,global,o,c,"$Id$" \
	sstoc.nc

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

mv sstoc.nc sstoc_${OCE}.nc

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