#!/bin/sh
# atlas-open — open the local Atlas UI in the default browser, waiting briefly for
# the control plane to answer first. Launched by the atlas-desktop .desktop entry.
# The atlas-node/atlasd services are enabled at install, so they are normally
# already up; this just avoids a "connection refused" flash right after boot.
set -eu

# Default to the loopback listener; honor an edited ATLAS_HTTP in the local preset.
addr="127.0.0.1:8090"
if [ -r /etc/atlas/local.env ]; then
	# shellcheck disable=SC1091
	. /etc/atlas/local.env 2>/dev/null || true
	[ -n "${ATLAS_HTTP:-}" ] && addr="$ATLAS_HTTP"
fi
# ATLAS_HTTP may be ":8090" or "0.0.0.0:8090"; normalize to something reachable.
case "$addr" in
	:*) addr="127.0.0.1${addr}" ;;
	0.0.0.0:*) addr="127.0.0.1:${addr#0.0.0.0:}" ;;
esac
url="http://${addr}"

if command -v curl >/dev/null 2>&1; then
	i=0
	while [ "$i" -lt 30 ]; do
		if curl -fsS -o /dev/null "${url}/healthz" 2>/dev/null; then
			break
		fi
		i=$((i + 1))
		sleep 0.5
	done
fi

exec xdg-open "$url"
