#!/usr/bin/sh
set -u

URL="http://127.0.0.1:8080"

# Service is normally started automatically by RPM installation.
# If it is not running, try to start it.
if ! systemctl is-active --quiet deye-local-monitor.service; then
    systemctl start deye-local-monitor.service >/dev/null 2>&1 || true
fi

# Give the local web service a moment to become available.
i=0
while [ "$i" -lt 20 ]; do
    if /usr/bin/python3 - "$URL" <<'PY'
import socket
import sys
from urllib.parse import urlparse

u = urlparse(sys.argv[1])
host = u.hostname or "127.0.0.1"
port = u.port or 80

try:
    with socket.create_connection((host, port), timeout=0.5):
        raise SystemExit(0)
except OSError:
    raise SystemExit(1)
PY
    then
if command -v chromium >/dev/null 2>&1; then exec chromium --app="$URL"; fi
if command -v chromium-browser >/dev/null 2>&1; then exec chromium-browser --app="$URL"; fi
if command -v google-chrome >/dev/null 2>&1; then exec google-chrome --app="$URL"; fi
if command -v google-chrome-stable >/dev/null 2>&1; then exec google-chrome-stable --app="$URL"; fi
if command -v firefox >/dev/null 2>&1; then exec firefox --new-window "$URL"; fi
exec xdg-open "$URL"
    fi

    sleep 1
    i=$((i + 1))
done

if command -v chromium >/dev/null 2>&1; then exec chromium --app="$URL"; fi
if command -v chromium-browser >/dev/null 2>&1; then exec chromium-browser --app="$URL"; fi
if command -v google-chrome >/dev/null 2>&1; then exec google-chrome --app="$URL"; fi
if command -v google-chrome-stable >/dev/null 2>&1; then exec google-chrome-stable --app="$URL"; fi
if command -v firefox >/dev/null 2>&1; then exec firefox --new-window "$URL"; fi
exec xdg-open "$URL"
