#!/bin/sh



#!/bin/sh
# title="$icon_gps Osmin"
# Author: magdesign
# Description: this script enables geoclue agent and starts osmin
# Notes: v0.9 Requires: osmin, geoclue, gnss-share
# todo: promt for ols if installed, code cleanup

# check requirements
if command -v osmin >/dev/null 2>&1 ; then
	echo "osmin installed"
else
	notify-send -u critical "Please install osmin"
	exit 1
fi

if command -v gnss-share >/dev/null 2>&1 ; then
	echo "gnss-share installed"
else
	notify-send -u critical "Please install gnss-share"
	#exit 1
fi
# should we check for geoclue, ols ?

if [[ $(rc-service gnss-share status | awk '{print $3}') == "started" ]]; then
	echo "gnss-share is running"
		if pgrep -x "geoclue-2.0" >/dev/null; then
			echo "geoclue is already running"
		else
			echo "starting geoclue"
			/usr/libexec/geoclue-2.0/demos/agent > /dev/null 2>&1 &
		fi
else
		echo "gnss-share is not running, starting it..."
		# Try to start gnss-share with password prompt handling
	if ! doas rc-service gnss-share start; then
			sxmo_terminal.sh -- sh -c "doas rc-service gnss-share start"
		echo "starting geoclue"
		/usr/libexec/geoclue-2.0/demos/agent > /dev/null 2>&1 &
	fi
		# enable GPS
		# mmcli -m any --location-enable-gps-raw
		# mmcli -m any --location-enable-gps-nmea
		# mmcli -m any --location-get
		# qmicli -d qrtr://0 --loc-set-nmea-types=all #qualcomm devices only!!!		
fi

# launch osmin
osmin &

# give some time to start services before check
sleep 4
if pgrep "gnss-share" >/dev/null; then
	notify-send -t 2000 "gnss running"
else
	notify-send -u critical "gnss-share not running!"
fi	
if pgrep "geoclue" >/dev/null; then
	notify-send -t 2000 "geoclue running"
else
	notify-send -u critical "geoclue not running!"
fi


# Wait for osmin to exit
wait $!

# Check if no other services are using geoclue or gnss-share (not sure if this relly works, also due sudo rights)
if ! pgrep -x "osmin" > /dev/null && ! pgrep -x "pure-maps" > /dev/null && ! pgrep -f "other_geoclue_using_services" > /dev/null; then
	if pgrep -x "geoclue-2.0" >/dev/null; then
		echo "Stopping geoclue"
		killall geoclue-2.0
		notify-send -t 1000 "geoclue stopped"
	fi

	# Check if gnss-share is running and stop it if no other services are using it
	if ! doas rc-service gnss-share stop; then
			sxmo_terminal.sh -- sh -c "doas rc-service gnss-share stop"
	fi
		notify-send -t 1000 "gnss-share stopped"

fi

exit 0

