#!/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

# CreateRestartAtm4Oasis.bash --oce eORCA1.4.2 /ccc/store/cont003/gencmip6/p86caub/IGCM_OUT/ICOLMDZOR/DEVT/test/ICOLOR-SROUT.11.NBP60.HISTMTH/ATM/Output/DA/ICOLOR-SROUT.11.NBP60.HISTMTH_19950101_19950105_1D_histday.nc

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================
set +vx
##
## 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=$(ccc_home --cccwork)/TMP/CPLRESTART
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR:-$(pwd)}}
    MpiRun="time ccc_mprun"
    PyRun="time ccc_mprun -n 1" # Needed to force python to run on one process only
    source $(ccc_home -u igcmg)/MachineEnvironment/irene/env_atlas_irene
    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

mkdir -p ${TMPDIR} 
cd ${TMPDIR}

bVerbose='Yes'
bXtrace='Yes'
bError='Yes'

while [[ ${1} = -* || ${1} = +* ]] ; do
    #echo ${Red}"${1}"${Norm}
    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    ) bVerbose='Yes'   ;;
	( -x | --xtrace     ) bXtrace='Yes'    ;;
	( -xv | -vx         ) bVerbose='Yes' ; bXtrace='Yes' ;;
	( -e                ) bError='Yes'     ;;
	( -V | +v | --noverbose  ) bVerbose='No'  ;;
	( -X | +x | --noxtrace   ) bXtrace='No'   ;;
	( -XV | -VX | +vx | +xv  ) bVerbose='No'; bXtrace='No' ;;
	( -E | +e           ) bError='No'    ;;
	( -* ) echo ${Bold}"Unknown option : ${1}"${Norm} ; return 1 ;;
    esac
    shift
done

[[ "X${bVerbose}" = "XYes" ]] && set -o verbose
[[ "X${bVerbose}" = "XNo"  ]] && set +o verbose
[[ "X${bXtrace}"  = "XYes" ]] && set -o xtrace
[[ "X${bXtrace}"  = "XNo"  ]] && set +o xtrace
[[ "X${bError}"   = "XYes" ]] && set -o errexit
[[ "X${bError}"   = "XNo"  ]] && set +o errexit

#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/scratch/cont003/gencmip6/p86caub/RUN_DIR/9114048_89294/ICOLOR-SROUT.11.NBP80.HISTMTH.89294/histday.nc}

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

Count=$(ncdump -h  ${AtmFile} | grep nvertex | wc -l)
if [[ ${Count} -gt 0 ]] ; then
    IsUnstructured=True
    dim_cell=$(ncdump -h  ${AtmFile} |& 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}
else
    # lat/lon
    IsUnstructured=False
    dim_lat=$(ncdump -h ${AtmFile} | grep "lat *=" | awk '{print $3}' )
    dim_lon=$(ncdump -h ${AtmFile} | grep "lon *=" | awk '{print $3}' )
    #ncrename --history --dimension lon,x flxat_fields_notime.nc
    #ncrename --history --dimension lat,y flxat_fields_notime.nc
    (( dim_lat = dim_lat - 1 ))
    ATM=LMD${dim_lon}${dim_lat}
    (( n_lat = dim_lat - 1 ))
fi

echo ${Blue}"Version atmosphere : ${ATM}"${Norm}

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

python3 ${SUBMIT_DIR}/create_flxat.py --IsUnstructured=${IsUnstructured} --input ${AtmFile} --output 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 Program,global,o,c,"Generated by ${0}"      \
        --attribute originalFiles,global,o,c,"${AtmFile}"       \
	--attribute uuid,global,o,c,"${UUID}"                                 \
	--attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	--attribute Comment,global,o,c,"${Comment}"                           \
	flxat.nc

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

##
echo ${Blue}"TMPDIR : ${TMPDIR}"${Norm}

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