#!/usr/bin/env bash
set -euo pipefail

project_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
target_directory="$project_root/application/worker/libs"
base_url="https://github.com/mapsforge/mapsforge/releases/download/0.29.0"

mkdir -p "$target_directory"

download_and_verify() {
    local name="$1"
    local expected="$2"
    local target="$target_directory/$name"
    local temporary="$target.download"

    if [[ -f "$target" ]]; then
        echo "$expected  $target" | sha256sum --check --status || {
            echo "Prüfsumme einer vorhandenen Abhängigkeit ist falsch: $target" >&2
            exit 1
        }
        echo "Abhängigkeit geprüft: $name"
        return
    fi

    echo "Lade offizielle Mapsforge-Abhängigkeit: $name"
    curl --fail --location --output "$temporary" "$base_url/$name"
    echo "$expected  $temporary" | sha256sum --check --status || {
        echo "Prüfsummenfehler für $name" >&2
        rm -f -- "$temporary"
        exit 1
    }
    mv -- "$temporary" "$target"
}

download_and_verify \
    "mapsforge-map-writer-0.29.0-jar-with-dependencies.jar" \
    "b507829b5a562be32e4fab14c8a76ffd45cebe99f6999cc955de3fcb4ed22dbf"
download_and_verify \
    "mapsforge-poi-writer-0.29.0-jar-with-dependencies.jar" \
    "a414872bd994b025bb8402034a80add23ca3cdbde72f716886794e3b8d2ad701"
