# 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}

# Check if experiment's spack installation already exists, if it doesn't, clone it.
SPACK_ENV=spack/share/spack/setup-env.sh
if [ ! -f ${SPACK_ENV} ] ; then
  git clone ${SPACK_URL} -b ${SPACK_BRANCH}
  #TODO: Would be good to enable the re-utilization of existing spack packages (via packages.yaml or upstreams.yaml)
fi

# Setup the environment
source ${SPACK_ENV}


if [ $( spack find icon-nwp@${ICON_VERSION} &> /dev/null ; echo $? ) -ne 0 ]; then
        echo "Installing icon-nwp@${ICON_VERSION}."
        # Compile openmpi with schedulers=slurm
        spack install openmpi%${SPACK_COMPILER}+legacylaunchers schedulers=slurm
        spack install icon-nwp@${ICON_VERSION}%${SPACK_COMPILER} ^openmpi%${SPACK_COMPILER}
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