#! /bin/bash

SCRIPT=$0
CMD=$1
case "$CMD" in
systemctl)
	if [ $(id -u) != "0" ] ; then
		sudo $SCRIPT $*
	else
		PACKET=$2
		SUBCMD=$3
		if [ $PACKET = "pywwetha" -a ! -e /etc/sidu-base/systemctl.d/pywwetha ] ; then
			echo "pywwetha is not installed. ignored."
		elif [ ! -e /etc/sidu-base/systemctl.d/$PACKET ] ; then
			echo "+++ sidu-control: Not a registered packet: $PACKET"
			echo "+++ call: $SCRIPT $*"
			exit 2
		else
			case "$SUBCMD" in
			start|stop|status|restart)
				systemctl $SUBCMD $PACKET.service
				;;
			*)
				echo "+++ sidu-control: unknown subcommand: $SUBCMD. Try start stop restart or status"
				echo "+++ call: $SCRIPT $*"
				exit 3
				;;
			esac
		fi	
	fi
	;;
linkderef)
	SUBCMD=$2
	LINK=$(which $SUBCMD)
	while [ True ] ; do
		PARENTDIR=$(dirname $(dirname "$LINK") )
		SUBDIR="$LINK"
		LINK=$(readlink $LINK)
		test -z "$LINK" && break
		if [ $(expr $LINK : "[.][.]") != 0 ] ; then
			LINK=${LINK/../$PARENTDIR}
		fi
	done
	echo $SUBDIR
	;;
browser)
	VIRTHOST=$2
	SUBCOMMAND=$3
	BASE=$4
	if [ -x /usr/bin/pywwetha-control -o -e /etc/sidu-base/systemctl.d/pywwetha ] ; then
		sudo $SCRIPT systemctl pywwetha $SUBCOMMAND
	fi	
	test -n "$BASE" && sudo $SCRIPT systemctl sidu-base $SUBCOMMAND	
	if [ "$SUBCOMMAND" = start -o "$SUBCOMMAND" = restart ] ; then
		if [ -n "${DISPLAY}" ] ; then
		# Launches x-www-browser if we are in kde, xfce, lxde, rqt, gnome
		        x-www-browser http://$VIRTHOST
		else
		# Launches www-browser (elinks) if we are in nox
		        www-browser http://$VIRTHOST
		fi
	fi
	;;
*)
	echo "+++ sidu-control: unknown command: $CMD"
	echo "+++ call: $SCRIPT $*"
	exit 1
	;;
esac
