#!/bin/sh

### BEGIN INIT INFO
# Provides: landscape-client
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Landscape client daemons
# Description: The Landscape client daemons are needed so the
#              Landscape server can manage a computer.
### END INIT INFO

LANDSCAPE_DEFAULTS=/etc/default/landscape-client
NAME=landscape-client
DAEMON=/usr/bin/$NAME
PIDDIR=/var/run/landscape
SOCKETDIR=/var/lib/landscape/client/sockets
PIDFILE=$PIDDIR/$NAME.pid
RUN=0 # overridden in /etc/default/landscape-client
CLOUD=0 # overridden in /etc/default/landscape-client
DAEMON_GROUP=landscape
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

[ -f $DAEMON ] || exit 0

. /lib/lsb/init-functions
[ -f $LANDSCAPE_DEFAULTS ] && . $LANDSCAPE_DEFAULTS

check_config () {
    # This $RUN check should match the semantics of
    # l.sysvconfig.SysVConfig.is_configured_to_run.
    if [ $RUN -eq 0 ]; then
	echo "$NAME is not configured, please run landscape-config."
	exit 0
    fi
}

case "$1" in
	start)
		check_config
		log_daemon_msg "Starting the $NAME daemon"
		install --owner=landscape --directory $PIDDIR
		# Cleanup leftover sockets if there's no other landscape process
		# running. This shouldn't be usually necessary, but it can
		# happen in case the client crashed badly and the socket points
		# to a process with the same PID.
                if [ -d "${SOCKETDIR:?}" ]; then
			if ! pidofproc -p "$PIDFILE" "$DAEMON" > /dev/null; then
				find "${SOCKETDIR:?}" -maxdepth 1 -type s -print0 | xargs -r0 rm -f
				find "${SOCKETDIR:?}" -maxdepth 1 -type l -print0 | xargs -r0 rm -f
			fi
		fi

		FULL_COMMAND="start-stop-daemon --start --quiet --oknodo --startas $DAEMON --pidfile $PIDFILE -g $DAEMON_GROUP -- --daemon --pid-file $PIDFILE"
		if [ x"$DAEMON_USER" != x ]; then
			sudo -u $DAEMON_USER $FULL_COMMAND
		else
			$FULL_COMMAND
		fi
		log_end_msg $?
		;;

	stop)
		log_daemon_msg "Stopping $NAME daemon"
		start-stop-daemon --retry 30 --stop --quiet --pidfile $PIDFILE
		log_end_msg $?
		;;

	status)
		# We want to maintain backward compatibility with Dapper,
		# so we're not going to use status_of_proc()
		pidofproc -p $PIDFILE $DAEMON >/dev/null
		status=$?
		if [ $status -eq 0 ]; then
			log_success_msg "$NAME is running"
		else
			log_failure_msg "$NAME is not running"
		fi
		exit $status
		;;

	restart|force-reload)
		$0 stop && $0 start
		;;

	*)
		echo "Usage: $0 {start|stop|status|restart|force-reload}"
		exit 1
		;;
esac

exit 0
