#!/bin/sh
set -e

TESTDIR=$(dirname "$(readlink -f "$0")")
PBF="$TESTDIR/monaco-260425.osm.pbf"
PORT=15020

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

test_profile() {
    local profile_name="$1"
    local profile_path="/usr/share/osrm/profiles/${profile_name}.lua"
    local base="$TMPDIR/${profile_name}.osrm"

    echo "=== Testing profile: $profile_name ==="

    echo "--- osrm-extract ($profile_name profile, Monaco) ---"
    osrm-extract -p "$profile_path" -o "$base" "$PBF"

    echo "--- osrm-contract ($profile_name, CH) ---"
    osrm-contract "$base"

    echo "--- osrm-routed trial mode ($profile_name) ---"
    osrm-routed --algorithm CH --trial=1 "$base"

    echo "--- starting osrm-routed ($profile_name) ---"
    osrm-routed --algorithm CH --port "$PORT" --threads 2 "$base" &
    OSRM_PID=$!

    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 ($profile_name) did not become ready within 30 seconds"
            exit 1
        fi
        sleep 1
    done
    echo "Server ready after ${i}s"

    echo "--- route: Casino -> Palais Princier ($profile_name) ---"
    resp=$(curl -s "http://127.0.0.1:$PORT/route/v1/${profile_name}/7.4272,43.7384;7.4200,43.7309?overview=false")
    echo "Response: $resp"
    if ! echo "$resp" | grep -q '"code":"Ok"'; then
        echo "ERROR: $profile_name route did not return code Ok"
        exit 1
    fi
    echo "OK: $profile_name route returned code Ok"

    kill "$OSRM_PID" 2>/dev/null
    OSRM_PID=
    # Wait for the port to be released before the next profile
    sleep 2
}

test_profile foot
test_profile bicycle

echo "--- all profile checks passed ---"
