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

if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root (use sudo)." >&2
  exit 1
fi

OSRM_USER=${OSRM_USER:-myroadtrip}
OSRM_GROUP=${OSRM_GROUP:-myroadtrip}
OSRM_DATA_DIR=${OSRM_DATA_DIR:-/srv/osrm}
OSRM_DATASET_URL=${OSRM_DATASET_URL:-https://download.geofabrik.de/europe/france-latest.osm.pbf}
OSRM_PROFILE=${OSRM_PROFILE:-car}
OSRM_CONTAINER_IMAGE=${OSRM_CONTAINER_IMAGE:-osrm/osrm-backend:latest}
TILESERVER_IMAGE=${TILESERVER_IMAGE:-maptiler/tileserver-gl:latest}
TILES_DIR=${TILES_DIR:-/srv/tiles}
COMPOSE_PATH=${COMPOSE_PATH:-/srv/myroadtrip/docker-compose.maps.yml}
SERVICE_PATH=${SERVICE_PATH:-/etc/systemd/system/maps-stack.service}

ensure_package() {
  if ! dpkg -s "$1" >/dev/null 2>&1; then
    apt-get install -y "$1"
  fi
}

echo ">>> Ensuring dependencies are installed..."
apt-get update
ensure_package curl
ensure_package ca-certificates
ensure_package docker.io
ensure_package docker-compose-plugin

systemctl enable --now docker

mkdir -p "$OSRM_DATA_DIR" "$TILES_DIR"
chown -R "$OSRM_USER:$OSRM_GROUP" "$OSRM_DATA_DIR" "$TILES_DIR"

OSM_FILE="$OSRM_DATA_DIR/$(basename "$OSRM_DATASET_URL")"
if [[ ! -f "$OSM_FILE" ]]; then
  echo ">>> Downloading dataset: $OSRM_DATASET_URL"
  curl -L "$OSRM_DATASET_URL" -o "$OSM_FILE"
else
  echo ">>> Dataset already present at $OSM_FILE (delete it to re-download)."
fi

echo ">>> Running OSRM preprocessing with profile: $OSRM_PROFILE"
docker pull "$OSRM_CONTAINER_IMAGE"
docker run -t --rm -v "$OSRM_DATA_DIR":/data "$OSRM_CONTAINER_IMAGE" osrm-extract -p "/opt/$OSRM_PROFILE.lua" "/data/$(basename "$OSM_FILE")"
docker run -t --rm -v "$OSRM_DATA_DIR":/data "$OSRM_CONTAINER_IMAGE" osrm-partition "/data/$(basename "$OSM_FILE" .osm.pbf).osrm"
docker run -t --rm -v "$OSRM_DATA_DIR":/data "$OSRM_CONTAINER_IMAGE" osrm-customize "/data/$(basename "$OSM_FILE" .osm.pbf).osrm"

echo ">>> Writing docker compose file to $COMPOSE_PATH"
install -d -o "$OSRM_USER" -g "$OSRM_GROUP" "$(dirname "$COMPOSE_PATH")"
cat >"$COMPOSE_PATH"<<EOF
version: "3.8"

services:
  osrm:
    image: $OSRM_CONTAINER_IMAGE
    container_name: osrm
    restart: unless-stopped
    command: >
      osrm-routed --algorithm mld
      /data/$(basename "$OSM_FILE" .osm.pbf).osrm
    volumes:
      - $OSRM_DATA_DIR:/data
    ports:
      - "127.0.0.1:5000:5000"

  tiles:
    image: $TILESERVER_IMAGE
    container_name: tileserver
    restart: unless-stopped
    command: >
      --public_url https://tiles.roadtripper.io
      --verbose
    volumes:
      - $TILES_DIR:/data
    ports:
      - "127.0.0.1:8080:80"
EOF
chown "$OSRM_USER:$OSRM_GROUP" "$COMPOSE_PATH"

echo ">>> Writing systemd unit $SERVICE_PATH"
cat >"$SERVICE_PATH"<<EOF
[Unit]
Description=MyRoadTrip Maps Stack (OSRM + Tileserver)
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$(dirname "$COMPOSE_PATH")
ExecStart=/usr/bin/docker compose -f "$COMPOSE_PATH" up -d
ExecStop=/usr/bin/docker compose -f "$COMPOSE_PATH" down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

echo ">>> Enabling and starting maps-stack.service"
systemctl daemon-reload
systemctl enable --now maps-stack.service

echo ">>> OSRM stack is running. Check status with 'systemctl status maps-stack' and 'docker ps'."
