#!/bin/sh

### BEGIN INIT INFO
# Provides: landscape-client
# Required-Start: $local_fs $remote_fs hal dbus
# Required-Stop: $local_fs $remote_fs hal dbus
# 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
PIDFILE=$PIDDIR/$NAME.pid
RUN=0 # overridden in /etc/default/landscape-client
CLOUD=0 # overridden in /etc/default/landscape-client
DAEMON_GROUP=landscape

[ -f $DAEMON ] || exit 0

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

# This $RUN check should match the semantics of
# l.sysvconfig.SysVConfig.is_configured_to_run.
if [ $RUN -eq 0 ]; then
	if [ $CLOUD -eq 1 ]; then
		if landscape-is-cloud-managed; then
			# Install the cloud default configuration file
			cp /usr/share/landscape/cloud-default.conf /etc/landscape/client.conf
			# Override default file for not going in this conditional again at
			# next startup
			sed -i "s/^RUN=.*/RUN=1/" $LANDSCAPE_DEFAULTS
			if ! grep -q "^RUN=" $LANDSCAPE_DEFAULTS; then
				echo "RUN=1" >> $LANDSCAPE_DEFAULTS
			fi
		else
			echo "$NAME is not configured, please run landscape-config."
			exit 0
		fi
	else
		echo "$NAME is not configured, please run landscape-config."
		exit 0
	fi
fi

case "$1" in
	start)
		log_daemon_msg "Starting the $NAME daemon"
		if [ ! -e $PIDDIR ]; then
			mkdir $PIDDIR
			chown landscape $PIDDIR
		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
