#! /bin/bash
#
# (C) 2003-13 - ntop.org
#
### BEGIN INIT INFO
# Provides:          ntopng
# Required-Start:    $local_fs $remote_fs $network $syslog $pf_ring
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop ntopng web
### END INIT INFO

start_ntopng() {
    FORCE=$1

    if [ ! -d "/etc/ntopng" ]; then
	echo "Configuration directory /etc/ntopng does not exist: quitting..."
	echo "This package is designed to be used from within the nBox package that"
	echo "configures ntopng using a web GUI. Please install the nBox package"
	echo "from http://packages.ntop.org"
	return 0
    fi

    NTOPNG_BINARY=/usr/local/bin/ntopng

    if [ -f /etc/ntopng/ntopng.start ] || [ $FORCE -eq 1 ]; then
	echo "Starting ntopng"

	PID_FILE=$(cat /etc/ntopng/ntopng.conf | grep '\-G='|cut -d '=' -f 2)
        if [ -f $PID_FILE ]; then
	    PID=$(cat $PID_FILE)
            if [ $PID -gt 0 ]; then
		IS_EXISTING=$(ps auxw | grep -v grep| grep $PID|wc -l)
		if [ $IS_EXISTING -gt 0 ]; then
		    echo "ntopng is already running [pid $PID]: not started"
		    return 0
		fi
	    fi
	fi
	$NTOPNG_BINARY /etc/ntopng/ntopng.conf > /dev/null &
    else
	echo "ntopng not started: missing /etc/ntopng/ntopng.start"
    fi
    return 1
}

stop_ntopng() {

    if [ ! -d "/etc/ntopng" ]; then
	echo "Configuration directory /etc/ntopng does not exist: quitting..."
	return 0
    fi

    if [ -f /etc/ntopng/ntopng.conf ]; then
	PID_FILE=$(cat /etc/ntopng/ntopng.conf | grep '\-G='|cut -d '=' -f 2)
	if [ -f $PID_FILE ]; then
	    PID=$(cat $PID_FILE)
	    if [ $PID -gt 0 ]; then
		echo "Stopping ntopng"
		kill -15 $PID > /dev/null
		/bin/rm $PID_FILE
	    else
		echo "Unable to stop ntopng: invalid pid [$PID][$PID_FILE]"
	    fi
	#else
	#    echo "Unable to stop ntopng: missing pid $PID_FILE"
	fi
    else
	echo "ntopng can't be stopped: missing /etc/ntopng/ntopng.conf"
    fi

    return 0
}

status_ntopng() {
    if [ ! -d "/etc/ntopng" ]; then
	echo "Configuration directory /etc/ntopng does not exist: quitting..."
	return 0
    fi

    PID_FILE=$(cat /etc/ntopng/ntopng.conf | grep '\-G='|cut -d '=' -f 2)
    if [ -f $PID_FILE ]; then
	PID=$(cat $PID_FILE)
	if [ $PID -gt 0 ]; then
	    echo "ntopng running as ${PID}"
	else
	    echo "No running ntopng pid [$PID] in [$PID_FILE]"
	fi
    fi
    
    return 0
}


########

logger "ntopng $1"

case "$1" in
  start)
	start_ntopng 0;
	;;

  force-start)	
	if [ ! -f /etc/ntopng/ntopng.conf ]; then
	    echo "ERROR: No configuration file found"
	    exit 1
	fi
	start_ntopng 1;
	;;

  stop)
       	stop_ntopng;
	;;

  status)
	status_ntopng;
	;;

  restart)
        stop_ntopng;
	echo "Waiting ntopng to shutdown and flush data..."
	sleep 10
	start_ntopng 0;
	;;

  *)
	echo "Usage: /etc/init.d/ntopng {start|force-start|stop|restart|status}]"
	exit 1
esac

exit 0
