#!/bin/sh
set -e

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

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

TMPDIR=$(mktemp -d)
cleanup() {
    systemctl stop osrm-backend-service 2>/dev/null || true
    rm -rf "$TMPDIR"
}
trap cleanup EXIT

echo "--- checking osrm system user and group exist ---"
if ! getent passwd osrm > /dev/null 2>&1; then
    echo "ERROR: osrm system user was not created by postinst"
    exit 1
fi
if ! getent group osrm > /dev/null 2>&1; then
    echo "ERROR: osrm system group was not created by postinst"
    exit 1
fi
echo "OK: osrm user and group exist"

echo "--- checking service unit is installed ---"
if ! systemctl cat osrm-backend-service.service > /dev/null 2>&1; then
    echo "ERROR: osrm-backend-service.service unit not found"
    exit 1
fi
echo "OK: unit file installed"

echo "--- preparing OSRM map data (MLD pipeline) ---"
osrm-extract -p "$PROFILE" -o "$TMPDIR/data.osrm" "$PBF"
osrm-partition "$TMPDIR/data.osrm"
osrm-customize "$TMPDIR/data.osrm"

echo "--- installing map data into /var/lib/osrm ---"
mkdir -p /var/lib/osrm
cp "$TMPDIR"/data.osrm* /var/lib/osrm/
chown -R osrm:osrm /var/lib/osrm

echo "--- configuring the service ---"
sed -i 's/^OSRM_OPTIONS=.*/OSRM_OPTIONS="--algorithm mld"/' \
    /etc/default/osrm-backend-service

echo "--- starting osrm-backend-service ---"
systemctl start osrm-backend-service

echo "--- waiting for service to become ready ---"
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: service did not become ready within 30 seconds"
        journalctl -u osrm-backend-service --no-pager || true
        exit 1
    fi
    sleep 1
done
echo "Service ready after ${i}s"

echo "--- checking service is active ---"
systemctl is-active osrm-backend-service
echo "OK: service is active"

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

echo "--- nearest: snap coordinate to road network ---"
resp=$(curl -s "http://127.0.0.1:$PORT/nearest/v1/driving/7.4272,43.7384?number=1")
if ! echo "$resp" | grep -q '"code":"Ok"'; then
    echo "ERROR: nearest did not return code Ok"
    exit 1
fi
echo "OK: nearest returned code Ok"

echo "--- stopping service ---"
systemctl stop osrm-backend-service
sleep 1
if systemctl is-active --quiet osrm-backend-service; then
    echo "ERROR: service is still active after stop"
    exit 1
fi
echo "OK: service stopped cleanly"

echo "--- all service checks passed ---"
