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

URL="http://localhost:8787/server-control"
HEALTH="http://127.0.0.1:8787/healthz"

if ! curl -fsS --max-time 2 "$HEALTH" >/dev/null 2>&1; then
  if command -v pkexec >/dev/null 2>&1; then
    pkexec /bin/systemctl start afmp.service
  else
    x-terminal-emulator -e sudo /bin/systemctl start afmp.service
  fi
  for _ in $(seq 1 40); do
    curl -fsS --max-time 2 "$HEALTH" >/dev/null 2>&1 && break
    sleep 0.5
  done
fi

if ! curl -fsS --max-time 2 "$HEALTH" >/dev/null 2>&1; then
  command -v zenity >/dev/null 2>&1 && zenity --error --text="AFMP-serveren kunne ikke startes. Kontakt BEPA, hvis problemet fortsætter."
  exit 1
fi

xdg-open "$URL" >/dev/null 2>&1
