#!/bin/bash
#
# luci - Luci cluster management application init script
#
# chkconfig: - 25 78
# description: Starts and stops luci
#
#
### BEGIN INIT INFO
# Provides:     luci
# Required-Start:   $network $time
# Required-Stop:    $network $time
# Default-Start:
# Default-Stop:
# Short-Description:    Starts and stops luci
# Description:      Starts and stops the luci cluster management application
### END INIT INFO

PATH="/bin:/usr/bin:/sbin:/usr/sbin:/usr/sbin"

# Defaults for luci. These can be overridden by the contents of 
# /etc/sysconfig/luci (or /etc/default/luci on deb-based distributions)
LUCI_USER=luci
LUCI_GROUP=luci
LUCI_DATA_DIR=/var/lib/luci
LUCI_DB_FILE=$LUCI_DATA_DIR/data/luci.db
LUCI_PID_FILE=$LUCI_DATA_DIR/data/luci.pid
LUCI_CONFIG_FILE=$LUCI_DATA_DIR/etc/luci.ini
LUCI_PASTER_LOG=$LUCI_DATA_DIR/log/luci.log

if [ -d /etc/sysconfig ]; then
	[ -f /etc/sysconfig/luci ] && . /etc/sysconfig/luci
elif [ -d /etc/default ]; then
	[ -f /etc/default/luci ] && . /etc/default/luci
fi

# Create the luci database if luci has not previously run (or the database
# has disappeared).
luci_init() {
	if [ ! -f "$LUCI_DB_FILE" ]; then
		paster setup-app "$LUCI_CONFIG_FILE" >& /dev/null
		if [ $? -ne 0 ]; then
			echo "Unable to create the luci database file."
			return 1
		fi
		chown $LUCI_USER:$LUCI_GROUP "$LUCI_DB_FILE"
		if [ $? -ne 0 ]; then
			echo "Unable to change ownership of the luci database file."
			return 1
		fi
	fi
	return 0
}

luci_start() {
	luci_status >& /dev/null
	if [ $? -eq 0 ]; then
		# echo already started
		return 0
	fi

	luci_init
	if [ $? -ne 0 ]; then
		return $?
	fi
	/usr/bin/paster serve --daemon --user "$LUCI_USER" --group "$LUCI_GROUP" "$LUCI_CONFIG_FILE" --log-file="$LUCI_PASTER_LOG" --pid-file="$LUCI_PID_FILE" >/dev/null
	return $?
}

luci_stop() {
	luci_status >& /dev/null
	if [ $? -ne 0 ]; then
		# already stopped
		return 0
	else
		/usr/bin/paster serve --stop-daemon --daemon --user "$LUCI_USER" --group "$LUCI_GROUP" "$LUCI_CONFIG_FILE" --log-file="$LUCI_PASTER_LOG" --pid-file="$LUCI_PID_FILE" >/dev/null
		return $?
	fi
}

luci_restart() {
	luci_status >& /dev/null
	if [ $? -ne 0 ]; then
		luci_stop || return 1
	fi
	luci_start
	return $?
}

luci_status() {
	out=`/usr/bin/paster serve --status --daemon --user "$LUCI_USER" --group "$LUCI_GROUP" "$LUCI_CONFIG_FILE" --log-file="$LUCI_PASTER_LOG" --pid-file="$LUCI_PID_FILE"`
	ret=$?
	echo "$out" | tail -1
	return $ret
}

ret=0

case "$1" in
start)
	luci_start
	ret=$?
;;
stop)
	luci_stop
	ret=$?
;;
restart|reload|force-reload)
	luci_restart
	ret=$?
;;
condrestart)
	luci_status >& /dev/null
	if [ $? -eq 0 ]; then
		luci_restart
		ret=$?
	fi
;;
status)
	luci_status
	ret=$?
;;
*)
    echo "Usage: $0 {start|stop|reload|restart|status}"
    ret=3
;;
esac

exit $ret
