#!/bin/sh
set -e

PROFILE=/usr/share/osrm/profiles/car.lua
PORT=15010

TESTDIR=$(dirname "$(readlink -f "$0")")
PBF="$TESTDIR/monaco-260425.osm.pbf"
GOLDEN="$TESTDIR/golden-mld"

TMPDIR=$(mktemp -d)
cleanup() {
    [ -n "$OSRM_PID" ] && kill "$OSRM_PID" 2>/dev/null || true
    rm -rf "$TMPDIR"
}
trap cleanup EXIT

BASE="$TMPDIR/monaco.osrm"

echo "--- osrm-extract (car profile, Monaco) ---"
osrm-extract -p "$PROFILE" -o "$BASE" "$PBF"

echo "--- osrm-partition (MLD) ---"
osrm-partition "$BASE"

echo "--- osrm-customize (MLD) ---"
osrm-customize "$BASE"

echo "--- osrm-routed trial mode (MLD) ---"
osrm-routed --algorithm MLD --trial=1 "$BASE"

echo "--- starting osrm-routed (MLD) ---"
osrm-routed --algorithm MLD --port "$PORT" --threads 2 "$BASE" &
OSRM_PID=$!

# Wait up to 30 seconds for the server to start accepting connections
i=0
until curl -s "http://127.0.0.1:$PORT/" > /dev/null 2>&1; do
    i=$((i + 1))
    if [ "$i" -ge 30 ]; then
        echo "ERROR: osrm-routed did not become ready within 30 seconds"
        exit 1
    fi
    sleep 1
done
echo "Server ready after ${i}s"

check_response() {
    local label="$1"
    local actual_file="$2"
    local golden_file="$GOLDEN/$label.json"
    local response
    response=$(cat "$actual_file")

    echo "Response [$label]: $response"

    if ! echo "$response" | grep -q '"code":"Ok"'; then
        echo "ERROR [$label]: expected \"code\":\"Ok\""
        exit 1
    fi

    if ! diff -u "$golden_file" "$actual_file"; then
        echo "ERROR [$label]: response differs from golden file $golden_file"
        exit 1
    fi
    echo "OK [$label]: matches golden"
}

echo "--- route: Casino de Monte-Carlo -> Palais Princier (MLD) ---"
curl -s "http://127.0.0.1:$PORT/route/v1/driving/7.4272,43.7384;7.4200,43.7309?overview=false" \
    > "$TMPDIR/route.json"
check_response route "$TMPDIR/route.json"

echo "--- nearest: snap coordinate to road network (MLD) ---"
curl -s "http://127.0.0.1:$PORT/nearest/v1/driving/7.4272,43.7384?number=1" \
    > "$TMPDIR/nearest.json"
check_response nearest "$TMPDIR/nearest.json"

echo "--- table: duration matrix for three Monaco waypoints (MLD) ---"
curl -s "http://127.0.0.1:$PORT/table/v1/driving/7.4272,43.7384;7.4200,43.7309;7.4250,43.7350" \
    > "$TMPDIR/table.json"
check_response table "$TMPDIR/table.json"

echo "--- all MLD routing checks passed ---"
