#!/bin/bash


DEF_X_VT=7

VT=$(fgconsole)
[[ $? -ne 0 || $VT -eq $DEF_X_VT ]] && VT=1


function x_ready() {
	for(( i=0; i < 180; i++ )); do
		systemctl status hivex >/dev/null || break
		if [[ -f /run/hive/xready ]]; then
			echo "X server is ready"
			# switch console back if no gui
			[[ ! -z $1 || $( < /run/hive/xready) == 0 ]] && chvt $VT
			return 0
		fi
		sleep 1
		[[ $i -eq 0 ]] && echo -n "Waiting. " || echo -n ". "
	done
	systemctl status hivex >/dev/null && echo "X server is not ready" || echo "Failed"
	return 1
}


function x_stop() {
	if systemctl status hivex >/dev/null; then
		echo "> Stopping X server"
		systemctl stop hivex
		sleep 1
	fi
}


function x_start() {
	if ! systemctl status hivex >/dev/null; then
		echo "> Starting X server"
		systemctl start hivex
	fi
}


function x_restart() {
	if pstree -As $$ | grep -q "xinit"; then
		echo "> Restarting X server"
		( x_stop; x_start; x_ready $1 ) </dev/null >/dev/null 2>&1 &
		exit 0
	else
		x_stop; x_start; x_ready $1
	fi
}


case "$1" in
	start)
		x_start
		x_ready
	;;
	startbg)
		x_start
		x_ready 1
	;;
	restart)
		x_restart
	;;
	restartbg)
		x_restart 1
	;;
	stop)
		x_stop
	;;
	bg)
		systemctl status hivex >/dev/null && chvt $VT
	;;
	fg)
		systemctl status hivex >/dev/null && chvt $DEF_X_VT
	;;
	status)
		systemctl status hivex
	;;
	guienabled)
		[[ -f /run/hive/xready && $( < /run/hive/xready) == 1 ]]
		exit
	;;
	*)
		echo "Usage: hivex start|stop|restart|status|fg|bg|startbg|restartbg"
	;;
esac

exit
