# Get some variables provided by autosubmit.
# TODO: What do we do to ensure that these variables are defined in the proj file?
WORKDIR=%HPCROOTDIR%
ICON_VERSION=%ICON_VERSION%
SPACK_URL=%spack.url%
SPACK_BRANCH=%spack.branch%
SPACK_COMPILER=%spack.compiler%

# If the workdir directory does not exist create it
if [ ! -d ${WORKDIR} ]; then
  mkdir -p ${WORKDIR}
fi

# Go to the working directory
cd ${WORKDIR}

. ${WORKDIR}/proj/platforms/common/spack_utils.sh
load_spack

if [ $(
  spack find icon-nwp@${ICON_VERSION} &>/dev/null
  echo $?
) -ne 0 ]; then
  echo "Installing icon-nwp@${ICON_VERSION}."

  if [[ $(spack compiler info ${SPACK_COMPILER}) ]]; then
    echo "Found Compiler"
  else
    echo "could not find compiler, try to install it... this may take a while"
    spack add ${SPACK_COMPILER}
    spack install
    spack compiler add $(spack location --install-dir $SPACK_COMPILER)
  fi

  spack add ucx%${SPACK_COMPILER}+dc+dm+ib_hw_tm+mlx5_dv+rc+rdmacm+thread_multiple+ud+verbs~cuda
  spack add openmpi%${SPACK_COMPILER}+pmi+legacylaunchers~cuda schedulers=slurm fabrics=ucx
  spack add icon-nwp@${ICON_VERSION}%${SPACK_COMPILER} ^openmpi%${SPACK_COMPILER}
  spack install
else
  echo "icon-nwp@${ICON_VERSION} already installed!"
fi

# Need to get ECCODES DWD definitions:
eccodes_version=$(spack find eccodes | grep eccodes@ | cut -d "@" -f 2)

definitions_tar_file=eccodes_definitions.edzw-${eccodes_version}-1.tar.bz2
if [ ! -f ${definitions_tar_file} ]; then
  defs_url=https://opendata.dwd.de/weather/lib/grib/${definitions_tar_file}
  wget ${defs_url}

  # Decompress definitions file
  tar -xf ${definitions_tar_file}
  # Create a file containing the environment variable that needs to be set in order to use DWD's definitions:
  echo "export ECCODES_DEFINITION_PATH=${WORKDIR}/definitions.edzw-${eccodes_version}-1" >eccodes_defs.env
fi