#!/bin/bash -l

# Get some variables provided by autosubmit.
WORKDIR=%HPCROOTDIR%
DYNAMICS_GRID_FILENAME=%simulation.dynamics_grid_filename%
RADIATION_GRID_FILE=%simulation.radiation_grid_filename%
EXTERNAL_PARAMETERS_FILE=%simulation.external_parameters_filename%


# Activate spack
. ${WORKDIR}/proj/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 icon module needed to retrieve some data
spack load --first icon-nwp@%ICON_VERSION%

# Create a folder for the common inidata and go there
COMMON_INIDATA_FOLDER=${WORKDIR}/inidata
mkdir -p "${COMMON_INIDATA_FOLDER}"
cd "${COMMON_INIDATA_FOLDER}" || exit

# Download or copy required input files
function download_file() {
  URL=$1
  FILE=${2:-$(basename "$URL")}
  if [ ! -e "$FILE" ]; then
    echo "Download $URL => $FILE"
    wget -q "$URL" -O "$FILE"
  fi
}

# Download grid files and external parameters
BASEURL=http://icon-downloads.mpimet.mpg.de/grids/public/edzw
download_file $BASEURL/${DYNAMICS_GRID_FILENAME}
download_file $BASEURL/${RADIATION_GRID_FILE}
download_file $BASEURL/${EXTERNAL_PARAMETERS_FILE}

# Link input for radiation
ln -sf "${ICON_DATA_PATH}/rrtmg_lw.nc" .
ln -sf "${ICON_DATA_PATH}/ECHAM6_CldOptProps.nc" .
ln -sf "${ICON_BASE_PATH}/run/ana_varnames_map_file.txt" .


# Change permissions to read only.
chmod 440 ./*