#!/bin/bash

#TODO:
# - Interpolate SST forcing file from regular grid to the destination grid
# - Integrate the SST into the analysis file
# - Add SST climatology in the external parameter file.

# Get some variables provided by autosubmit.
WORKDIR=%HPCROOTDIR%
PROJ_FOLDER=${WORKDIR}/production_project

SST_FORCING=$( basename %simulation.initial_conditions.sea_surface_temperature_forcing% )
INTERPOLATED_SST=sst_climatology.nc
DESTINATION_GRID=%simulation.dynamics_grid_filename%
EXTERNAL_PARAMETERS_FILE=%simulation.external_parameters_filename%
STARTDATE=%SDATE%
MEMBER=%MEMBER%


# Member folder
MEMBER_DIR=${WORKDIR}/${STARTDATE}/${MEMBER}

cd ${MEMBER_DIR} || exit


# Get analysis file path
ANALYSIS_FILE=$(find . -name "igaf*.m*.grb" -print -quit)


# Load spack
. ${WORKDIR}/production_project/platforms/common/spack_utils.sh
load_spack "%spack.init%" "%spack.root%" "%spack.url%" "%spack.branch%" "%spack.externals%" "%spack.compiler%" "%spack.disable_local_config%" "%spack.user_cache_path%" "%spack.user_config_path%" "%spack.upstreams%"

# Load dwd-icon-tools
spack load --first dwd-icon-tools % "%spack.compiler%"

# Set environment variable for eccodes-dwd definitions:
source ${WORKDIR}/eccodes_defs.env

# Activate virtual environment
source ${WORKDIR}/python_environment/bin/activate

# Get the functions to interpolate and adapt the input files
source ${PROJ_FOLDER}/templates/event-generator/adapt_member_utils.sh

# Interpolate SST
interpolate_SST "${DESTINATION_GRID}" "${SST_FORCING}" "${INTERPOLATED_SST}"


# Interpolate extpar
#interpolate_extpar "${DESTINATION_GRID}" "${EXTERNAL_PARAMETERS_FILE}"


# Integrate sst to extpar
integrate_sst_to_extpar "${INTERPOLATED_SST}" "${EXTERNAL_PARAMETERS_FILE}"


# Interpolate analysis
interpolate_analysis "icon_grid_0024_R02B06_G.nc" "${ANALYSIS_FILE}" "${DESTINATION_GRID}"


integrate_sst_to_analysis "${INTERPOLATED_SST}"
