#! /bin/bash -e

PBF_FILE="opentripplanner.osm.pbf"

# freely available elevation data in geotiff format (https://srtm.csi.cgiar.org/)
ELEVATION_BASE_URL="https://srtm.csi.cgiar.org/wp-content/uploads/files/srtm_5x5/TIFF/"
ELEVATION_FILES=({{ otp_elevation_files|map("to_json")|join(" ") }})

IMAGE_NAME="{{ otp_image }}"
CONTAINER_NAME="graph-build"

CURL_OPTS="--location --fail -s --show-error -#"

# where input and intermediate files are
BUILD_DIR=build
# where the final build output is. this is read by OTP
OUTPUT_DIR=latest

podman stop $CONTAINER_NAME || true
podman rm --force $CONTAINER_NAME || true

mkdir -p -m 775 build
cd build

# download extract elevation zip files. this only needs to run once.
for i in "${ELEVATION_FILES[@]}"
do
  :
  zipfile="${i}.zip"
  tiffile="${i}.tif"
  if [ -f "$tiffile" ]; then
    echo "$zipfile exists."
  else
    echo "$tiffile does not exist. Downloading ..."
    curl ${CURL_OPTS} "${ELEVATION_BASE_URL}{$zipfile}" -o ${zipfile}
    unzip ${zipfile} ${tiffile}
    rm ${zipfile}
  fi
done

{% for item in manual_osm_downloads %}

PBF_FILE="{{ item.local_name }}"
PBF_DOWNLOAD_URL="{{ item.url }}"

if [ -f "$PBF_FILE" ]; then
  echo "$PBF_FILE exists. Downloading updates."
  pyosmium-up-to-date -v $PBF_FILE
else
  echo "$PBF_FILE does not exist. Downloading ..."
  curl ${CURL_OPTS} "${PBF_DOWNLOAD_URL}" -o ${PBF_FILE}
fi

{% endfor %}

# delete GTFS files from previous graph build
echo "Deleting existing GTFS data from previous build"
rm -rf *.gtfs.zip

{% if graph_build_extra_instructions is defined %}
{{ graph_build_extra_instructions }}
{% endif %}

{% for item in manual_download_gtfs_feeds %}
curl ${CURL_OPTS} "{{ item.url }}" -o "{{ item.feed_id}}.gtfs.zip"
{% endfor %}

mkdir -p report

# actually build the OTP graph

{% for cmd in ["--buildStreet --save", "--loadStreet --save"] %}

podman run --pull=newer \
  -v {{ otp_base_dir }}/${BUILD_DIR}:/var/opentripplanner/:z \
  --name ${CONTAINER_NAME} \
  --rm \
  -e JAVA_TOOL_OPTIONS="{{ otp_graph_build_jvm_opts }}" \
  ${IMAGE_NAME} {{ cmd }} {% if otp_abort_graph_build_on_invalid_config %}--abortOnUnknownConfig{% endif %} > /dev/null

{% endfor %}

# move the graph and its config from /build to /latest
cd ..
mkdir -p -m 775 ${OUTPUT_DIR}
cp ${BUILD_DIR}/graph.obj  ${OUTPUT_DIR}/
cp ${BUILD_DIR}/router-config.json ${BUILD_DIR}/otp-config.json ${OUTPUT_DIR}

send-to-matrix "📦️ OTP graph build complete on {{ inventory_hostname }}" || true
