#!/bin/bash
#
# @(#) Fibranet NSP, SL
# Copyright (C) 2005 by Jordi Sanfeliu <admin@fibranet.com>
#
#	/etc/rc.d/init.d/monitorix
#
# Starts the Monitorix
#
# chkconfig: 2345 99 10
# description: system monitoring tool

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

RETVAL=0
LOCK="/var/lock/monitorix"
PROGRAM="Fibranet Monitorix"

start() {
	# Check if monitorix is already running
	lockfile -r1 $LOCK >/dev/null 2>&1
	RETVAL=$?
	if [ $? -eq 0 ]; then
		gprintf "Starting %s: " "$PROGRAM"
		echo_success
		echo
	else
		gprintf "Starting %s: " "$PROGRAM"
		echo_failure
		echo
		return $RETVAL
	fi

	# Generates a new index.html and creates PC LAN counters (if needed)
	/usr/sbin/monitorix.pl init
	# Creates RRDs files (if needed)
	/usr/sbin/monitorix.pl create
	/bin/mv /etc/cron.d/.monitorix /etc/cron.d/monitorix
}

stop() {
	if [ -e $LOCK ] ; then
		rm -f $LOCK
		/bin/mv /etc/cron.d/monitorix /etc/cron.d/.monitorix
		gprintf "Stopping %s: " "$PROGRAM"
		echo_success
	else
		echo
		gprintf "WARNING: You has selected to stop Monitorix AGAIN!\n"
		gprintf "WARNING: This may destroy all your IP counters!.\n"
		echo
		gprintf "If you only want to upgrade a new version, while mantaining Monitorix up\n"
		gprintf "and running, simply type 'stop' and then 'start' or 'restart'.\n"
		echo
		gprintf "Do you still want to continue? (N/y): "
		read option
		if [ "$option" != "Y" ] && [ "$option" != "y" ] ; then
			return 1
		fi
		gprintf "In a near future in this case all your iptables counters will be deleted.\n"
		gprintf "Stay tunned when this option changes.\n"
		gprintf "At this moment you can use iptables command like this:\n"
		gprintf "iptables -X ; iptables -t nat -X\n"
	fi
	echo
}

status() {
        if [ -e $LOCK ] ; then
                gprintf "%s is active.\n" "$PROGRAM"
        else
                gprintf "%s is down.\n" "$PROGRAM"
        fi
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status
		;;
	restart)
		stop
		sleep 1
		start
		;;
	*)
		gprintf "Usage: %s {start|stop|status|restart}\n" "$0"
		exit 1
esac

exit $RETVAL

