#!/bin/bash
#
# chkconfig: 2345 85 15
# description: Livecare Agent adds remote desktop support to X11/Wayland environments.
# processname: lcagent
# pidfile: /var/run/lcagent.pid
# config: /etc/sysconfig/lcagent

### BEGIN INIT INFO
# Provides: lcagent
# Required-Start: $syslog $local_fs
# Required-Stop: $syslog $local_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop livecare agent daemon
# Description: Livecare Agent adds remote desktop support to X11/Wayland
#              environments.
### END INIT INFO

# source function library
. /etc/init.d/functions

if test -e /etc/sysconfig/lcagent ; then
	. /etc/sysconfig/lcagent
fi

RETVAL=0

check() {
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	
	# Check if lcagent is executable
	test -x /usr/bin/lcagent || exit 5
}

__lcagent() {
	echo $$ > /var/run/lcagent.pid
	while ! /usr/bin/lcagent; do
		sleep 5
	done
	return 0
}

start() {
	check
		
	if [ ! -f /var/lock/subsys/lcagent ]; then
		echo -n $"Starting Livecare Agent service: "
	
		if [ -z "$DISPLAY" ]; then
			DISPLAY=":0"
		fi

		export -f __lcagent
		DISPLAY=$DISPLAY daemon --pidfile /var/run/lcagent.pid /bin/bash -c "__lcagent &"
		RETVAL=$?
		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/lcagent || rm -f /var/lock/subsys/lcagent
		echo
	fi
	return $RETVAL
}

stop() {
	check
	
	echo -n $"Shutting down Livecare Agent service: "
	killproc /usr/bin/lcagent
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/lcagent
	echo
	return $RETVAL
}

restart() {
	stop
	start
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	force-reload|reload|try-restart)
		echo "$0: Unimplemented feature."
		RETVAL=3
		;;
	restart)
		restart
		;;
	condrestart)
		if [ -f /var/lock/subsys/lcagent ]; then
			restart
		fi
		;;
	status)
		status lcagent
		RETVAL=$?
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart|condrestart|reload|force-reload|try-restart}"
		RETVAL=2
esac

exit $RETVAL
