#!/bin/sh
# chkconfig: 2345 99 01
# description: Run the Sigma agent.
### BEGIN INIT INFO
# Provides:          sigma_agent
# Required-Start:    $remote_fs $network $syslog
# Required-Stop:     $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: SigmaSRC Platform agent
# Description:       Runs the SigmaSRC Platform compliance agent.
### END INIT INFO

# Set our umask
umask 022

. /etc/sigma/agent.conf

# Bootstrap script.
# XXX for now, the scheduler; later the watchdog.
#
BOOTSTRAP=$AVBIN/scheduler.py

start() {
	# Check if the configuration file exists.
	#
	if [ ! -f $AVCONF/config ]
	then
		echo "Sigma client configuration file does not exist."
		exit 1
	fi

	# Refuse to start until configured. A blank or placeholder (qali01)
	# central-server means the installer never collected one (e.g. a silent
	# install with no answers); don't start, and tell the admin how to fix it.
	cs=`sed -n 's/^[[:space:]]*central-server[[:space:]]*=[[:space:]]*\([^:[:space:]]*\).*/\1/p' $AVCONF/config | head -1`
	if [ -z "$cs" ] || [ "$cs" = "qali01" ]
	then
		echo "Sigma agent is not configured (no central server set)." 1>&2
		echo "Run:  sudo sigma-agent-setup" 1>&2
		exit 1
	fi

	# Check if Python can be run
	if $PYTHON -c pass
	then
		:
	else
		echo "Can't run $PYTHON interpreter."
		exit 1
	fi

	# Check if the executable is there.
	#
	if [ ! -f $BOOTSTRAP ]
	then
		echo "$BOOTSTRAP not found."
		exit 1
	else
		echo "Starting $BOOTSTRAP..."
		$PYTHON $BOOTSTRAP --daemon
	fi

}

stop_agent() {
	$PYTHON $AVBIN/sdc.py --stop
}

restart() {
	stop_agent
	start
}

status() {
	$PYTHON $AVBIN/status.py $*
}

logtail() {
	$PYTHON $AVBIN/logtail.py $*
}


case "$1" in
start)
	start
	;;
stop)
	stop_agent
	;;
restart)
	restart
	;;
status)
	shift
	status $*
	;;
logtail)
	shift
	logtail $*
	;;
*)
	echo "Usage: $0 {start|stop|restart|status|logtail}"
	exit 1
	;;
esac
