#!/usr/bin/env bash

# source the helpers for globals and functions
. /valhalla/scripts/helpers.sh

# Strategy:
#   - rebuild if:
#     - build_elevation is true and elevation doesn't exist (force)
#     - tile extract or folder doesn't exist (force)
#     - use_tiles_ignore_pbf is false and new file constellations exist
#   - downloads pbfs if there are none in the folder
#   - 

# changed 18.11.2021: .file_hashes.txt -> file_hashes.txt
# to be backwards-compatible we have to respect the old way too, which is usually shared with the host
# remove this at some point
if test -f "${CUSTOM_FILES}/.file_hashes.txt"; then
  mv "${CUSTOM_FILES}/.file_hashes.txt" "${HASH_FILE}"
elif ! test -f "${HASH_FILE}"; then
  touch ${HASH_FILE}
fi

# determine if extras were requested
do_elevation="False"
do_admins="False"
do_timezones="False"
if [[ "${build_elevation}" == "True" ]] || [[ "${build_elevation}" == "Force" ]] || ! ([[ -z "${min_x}" ]] && [[ -z "${min_y}" ]] && [[ -z "${max_x}" ]] && [[ -z "${max_y}" ]]); then
  do_elevation="True"
fi
if ([[ "${build_admins}" == "True" ]] && ! test -f "${ADMIN_DB}") || [[ "${build_admins}" == "Force" ]]; then
  do_admins="True"
fi
if ([[ "${build_time_zones}" == "True" ]] && ! test -f "${TIMEZONE_DB}") || [[ "${build_time_zones}" == "Force" ]]; then
  do_timezones="True"
fi

# Find and add .pbf files to the list of files
new_hashes="False"
files=""
files_counter=0
for file in $(ls $CUSTOM_FILES/*.pbf 2>/dev/null); do
  hash_echo=$(hash_exists ${file})
  if ! [[ $hash_echo =~ "True" ]] ; then
    echo "WARNING: Hash not found for: ${file}!"
    new_hashes="True"
  fi
  files="${files} ${file}"
  files_counter=$((files_counter + 1))
done

# determine whether we need a full tile build or not
do_build="False"
if ! test -f "${TILE_TAR}" && ! [ -n "$(ls -A ${TILE_DIR} 2>/dev/null)" ]; then
  # build if no tiles exist
  echo "WARNING: No routing tiles found, starting new build.."
  do_build="True"
elif [[ "${force_rebuild}" == "True" ]]; then
  # respect the env var
  echo "WARNING: force_rebuild True."
  do_build="True"
elif [[ "${do_admins}" == "True" ]]; then
  # rebuild if the admin db has to be built
  echo "WARNING: No admin db found, starting a new build"
  do_build="True"
elif [[ "${do_timezones}" == "True" ]]; then
  # rebuild if the timezone db has to be built
  echo "WARNING: No timezone db found, starting a new build"
  do_build="True"
elif [[ "${do_elevation}" == "True" ]] && ! [ -n "$(ls -A ${ELEVATION_PATH} 2>/dev/null)" ]; then
  # build if elevation was requested but not downloaded yet
  echo "WARNING: No elevation tiles found, starting a new build"
  do_build="True"
elif [[ "${use_tiles_ignore_pbf}" == "True" ]]; then
  # don't build if there are tiles and we want to load them
  echo "INFO: Found routing tiles with 'use_tiles_ignore_pbf' True."
  echo "INFO: Jumping directly to the tile loading!"
  do_build="False"
elif [[ "${new_hashes}" == "True" ]]; then
  # build if there are new/other PBF files
  echo "WARNING: New PBF files were detected, starting new build.."
  echo "WARNING: Hashes $(cat ${HASH_FILE})"
  do_build="True"
else
  # files exist and no reason to rebuild
  echo "INFO: Routing tiles exist and no need to rebuild."
fi

# if no PBFs were found try downloading some
if [[ ${files_counter} == 0 ]] && [[ ${do_build} == "True" ]]; then
  if [[ -z "${tile_urls}" ]]; then
    echo "ERROR: No local PBF files, valhalla_tiles.tar and no tile URLs found. Nothing to do."
    exit 1
  else
    echo "WARNING: No local files and no valhalla_tiles.tar found. Downloading links: ${tile_urls}!"
    for url in ${tile_urls}; do
      fp=$CUSTOM_FILES/$(basename $url)
      download_file "${url}" "${fp}"
      files="${files} ${fp}"
    done
  fi
fi
files=$(echo $files | xargs)

# be careful how to write the config (mostly for restart scenarios where env vars are true all of a sudden)
if test -f "${CONFIG_FILE}"; then
  jq --arg d "${TILE_DIR}" '.mjolnir.tile_dir = $d' "${CONFIG_FILE}"| sponge "${CONFIG_FILE}"
  jq --arg e "${TILE_TAR}" '.mjolnir.tile_extract = $e' "${CONFIG_FILE}"| sponge "${CONFIG_FILE}"
  jq --arg d "${ADMIN_DB}" '.mjolnir.admin = $d' "${CONFIG_FILE}"| sponge "${CONFIG_FILE}"
  jq --arg d "${TIMEZONE_DB}" '.mjolnir.timezone = $d' "${CONFIG_FILE}"| sponge "${CONFIG_FILE}"
  jq --arg d "${ELEVATION_PATH}" '.additional_data.elevation = $d' "${CONFIG_FILE}"| sponge "${CONFIG_FILE}"
else
  additional_data_elevation="--additional-data-elevation $ELEVATION_PATH"
  mjolnir_admin="--mjolnir-admin ${ADMIN_DB}"
  mjolnir_timezone="--mjolnir-timezone ${TIMEZONE_DB}"
  valhalla_build_config --mjolnir-tile-dir ${TILE_DIR} --mjolnir-tile-extract ${TILE_TAR} ${mjolnir_timezone} ${mjolnir_admin} ${additional_data_elevation} --mjolnir-traffic-extract "" --mjolnir-transit-dir "" > ${CONFIG_FILE}  || exit 1
fi

# build the databases maybe
if [[ "${do_admins}" == "True" ]]; then
  maybe_create_dir $(dirname ${ADMIN_DB})
  echo ""
  echo "====================="
  echo "= Building admin db ="
  echo "====================="
  echo ""
  valhalla_build_admins --config "${CONFIG_FILE}" ${files}  || exit 1
fi
if [[ "${do_timezones}" == "True" ]]; then
  maybe_create_dir $(dirname ${TIMEZONE_DB})
  echo ""
  echo "========================"
  echo "= Building timezone db ="
  echo "========================"
  echo ""
  valhalla_build_timezones > ${TIMEZONE_DB} || exit 1
fi

# Finally build the tiles
if [[ "${do_build}" == "True" ]]; then
  echo "INFO: Running build tiles with: ${CONFIG_FILE} ${files}"

  # if we should build with elevation we need to build the tiles in stages
  echo ""
  echo "============================"
  echo "= Build the initial graph. ="
  echo "============================"

  valhalla_build_tiles -c ${CONFIG_FILE} -e build ${files} || exit 1

  # Build the elevation data if requested
  if [[ "$do_elevation" == "True" ]]; then
    if [[ "${build_elevation}" == "Force" ]] && ! test -d "${ELEVATION_PATH}"; then
      echo "WARNING: Rebuilding elevation tiles"
      rm -rf "$ELEVATION_PATH" || exit 1
    fi
    maybe_create_dir "${ELEVATION_PATH}"
    echo ""
    echo "================================="
    echo "= Download the elevation tiles ="
    echo "================================="
    valhalla_build_elevation --from-tiles --decompress -c ${CONFIG_FILE} -v || exit 1
  fi

  echo ""
  echo "==============================="
  echo "= Enhancing the initial graph ="
  echo "==============================="
  valhalla_build_tiles -c ${CONFIG_FILE} -s enhance ${files} || exit 1

  echo "INFO: Successfully built files: ${files}"
  add_hashes "${files}"
fi
