#!/usr/bin/env bash
### ===========================================================================
###
### Creates initial state for coupler, atmosphere side
### Takes state from atmospheric hist file
###
### ===========================================================================
##
##  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 :
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/ATM/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_histmth.nc
# CreateRestartAtm4Oasis.bash --oce eORCA1.2 /ccc/store/cont003/gencmip6/p86maf/IGCM_OUT/IPSLCM6/PROD/piControl/CM61-LR-pi-03/ATM/Output/MO/CM61-LR-pi-03_23400101_23491231_1M_histmth.nc
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/work/cont003/gencmip6/bedidil/SAVE8_ORCA2/STORE1/dynamico_grid.nc
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/work/cont003/gencmip6/bedidil/SAVE9_ORCA2_DYN30_1MO/STORE1/histmth.nc

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

##
## Command line parameters
## ===========================================================================
# Default values
Comment="Preliminary attempt - Do not trust !"
OCE="Unknown"

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

case ${arch} in
    ( irene )
    set +e
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${CCCWORKDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    MpiRun="time ccc_mprun"
    PyRun="time ccc_mprun -n 1" # Needed to force python to run on one process only
    module purge
    module load hdf5
    module load netcdf-c
    module load nco
    module load cdo
    module load python3
    module load datadir/igcmg
    module list
    set -e
    ;;
    ( spip )
    R_IN=${HOME}/Scratch/IGCM
    TMPDIR=${HOME}/Scratch/TMP
    SUBMIT_DIR=$(pwd)
    MpiRun="/opt/local/bin/mpirun -n 1"
    PyRun="time"
    ;;
    ( * )
    exit -1
    ;;
esac
set -o verbose
set -o xtrace
set -e

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -o   | --oce      ) shift ; OCE=${1}     ;; # Just needed to add information in the file and file name
	( -c   | --comment  ) shift ; Comment=${1} ;; # Just needed to add information in the file
	( -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


set -e

#AtmFile=${1:-/ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/ATM/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_histmth.nc}
#AtmFile=${1:-/ccc/work/cont003/gencmip6/bedidil/SAVE8_ORCA2/STORE1/dynamico_grid.nc}
AtmFile=${1:-/ccc/work/cont003/gencmip6/bedidil/SAVE9_ORCA2_DYN30_1MO/STORE1/histmth.nc}

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

##
## Extract variables
## ===========================================================================
ncks --overwrite --fl_fmt=${FL_FMT} --history --dimension time_counter,0,0 --variable lon,lat,sols,soll,fract_oce,fract_sic,precip,snow,evap_sic,evap_oce,wind10m,taux_oce,tauy_oce,taux_sic,tauy_sic ${AtmFile} flxat_fields.nc
ncwa --overwrite --fl_fmt=${FL_FMT} --history --average time_counter flxat_fields.nc flxat_fields_notime.nc # remove time dimension 
ncatted --history --attribute history,global,d,c,""  flxat_fields_notime.nc          # cleaning of history attributes

##
## Determines if the file is unstructured (Dynamico) or lon/lat (LMDZ)
## Set atmosphere name
## ===========================================================================
Count=$(ncdump -h flxat_fields_notime.nc | grep nvertex | wc -l)
if [[ ${Count} -gt 0 ]] ; then
    IsUnstructured=yes
    dim_cell=$(ncdump -h flxat_fields_notime.nc |& grep "cell *=" | awk '{print $3}' ) # Get nominal DYNAMICO resolution (nbp parameter)
    ico_nbp=$( echo "sqrt(($dim_cell-2)/10)" | bc -l | sed 's/\..*//' )
    ATM=ICO${ico_nbp}
    ncrename --history --dimension cell,y flxat_fields_notime.nc
cat <<EOF > add_dim.nco
defdim("x",1) ;
lon      [y,x] = lon       ;
lat      [y,x] = lat       ;
sols     [y,x] = sols      ;
soll     [y,x] = soll      ;
fract_oce[y,x] = fract_oce ;
fract_sic[y,x] = fract_sic ;
precip   [y,x] = precip    ;
snow     [y,x] = snow      ;
evap_sic [y,x] = evap_sic  ;
evap_oce [y,x] = evap_oce  ;
wind10m  [y,x] = wind10m   ;
taux_oce [y,x] = taux_oce  ;
tauy_oce [y,x] = tauy_oce  ;
taux_sic [y,x] = taux_sic  ;
tauy_sic [y,x] = tauy_sic  ;
EOF
    ncap2 --history --overwrite --fl_fmt=${FL_FMT} --script-file add_dim.nco flxat_fields_notime.nc tmp_flxat_fields_notime.nc
    mv tmp_flxat_fields_notime.nc flxat_fields_notime.nc
else
    # lat/lon
    IsUnstructured=no
    dim_lat=$(ncdump -h flxat_fields_notime.nc | grep "lat *=" | awk '{print $3}' )
    dim_lon=$(ncdump -h flxat_fields_notime.nc | grep "lon *=" | awk '{print $3}' )
    ncrename --history --dimension lon,x flxat_fields_notime.nc
    ncrename --history --dimension lat,y flxat_fields_notime.nc
cat <<EOF > add_dim.nco
lon[y,x] = lon ;
lat[y,x] = lat ;
EOF
    ncap2 --history --overwrite --fl_fmt=${FL_FMT} --script-file add_dim.nco flxat_fields_notime.nc tmp_flxat_fields_notime.nc
    mv tmp_flxat_fields_notime.nc flxat_fields_notime.nc
    (( dim_lat = dim_lat - 1 ))
    ATM=LMD${dim_lon}${dim_lat}
    (( n_lat = dim_lat - 1 ))


fi

echo "Version atmosphere : " ${ATM}


##
## Creates flxat file
## ===========================================================================

python3 create_flxat.py --IsUnstructured=${IsUnstructured} --input flxat_fields_notime.nc --output tmp_flxat.nc

[[ ${IsUnstructured} = yes ]] && ncks --fl_fmt=${FL_FMT} --history --append --variable bounds_lon,bounds_lat flxat.nc  tmp_flxat.nc 
ncks --fl_fmt=${FL_FMT} --append --history --variable COTAUXXU,COTAUYYU,COTAUZZU,COTAUXXV,COTAUYYV,COTAUZZV,COTOTRAI,COTOTSNO,COTOTEVA,COICEVAP,COQSRMIX,COQNSMIX,COSHFICE,CONSFICE,CODFLXDT,COCALVIN,COLIQRUN,COWINDSP,COTAUMOD tmp_flxat.nc flxat.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,"${ATM} http://lmdz.lmd.jussieu.fr"      \
	--attribute Ocean,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,"${AtmFile}"                     \
	--attribute directory,global,o,c,"$(pwd)"                             \
	--attribute description,global,o,c,"Fields needed by OASIS-MCT"       \
	--attribute timeStamp,global,o,c,"$(date)"                            \
	--attribute Program,global,o,c,"Generated by ${0}"                    \
	--attribute uuid,global,o,c,"${UUID}"                                 \
	--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 Comment,global,o,c,"Preliminary attempt - Do not trust !" \
	--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$" \
	flxat.nc


##
## Creates other files
## ===========================================================================
mv flxat.nc flxat_${ATM}_maskFrom_${OCE}.nc
ncks --history --variable COCALVIN flxat_${ATM}_maskFrom_${OCE}.nc icbrg_${ATM}_maskFrom_${OCE}.nc
ncks --history --variable COCALVIN flxat_${ATM}_maskFrom_${OCE}.nc icshf_${ATM}_maskFrom_${OCE}.nc

##
## Cleaning
## ===========================================================================
rm -f flxat_fields.nc flxat_fields_notime.nc tmp_flxat.nc

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