#!/bin/bash
# Copyright (c) 2005 Heinlein Prof. Linux Support GmbH
#
# Author: Stefan Neben
#
#
### BEGIN INIT INFO
# Provides:       mailtraced
# Required-Start: $network $named $syslog $time $remote_fs memcached
# Required-Stop:  $network $named $syslog $time $remote_fs
# Default-Start:  3 5
# Default-Stop:   0 1 6
# Description:    Start mailtraced
### END INIT INFO

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

# Declarations
export LC_ALL="C"

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Mailtrace Daemon"
NAME=mailtraced
DAEMON=/usr/bin/$NAME
DAEMON_ARGS=""
SCRIPTNAME=/etc/init.d/mailtraced

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

do_start() {
	$DAEMON
	return $?
}

do_stop() {
	local TYPE=$1
	
	if [ "$TYPE" == "graceful" ] ; then
		for PROCESS in $(ls /var/run/mailtraced.*.pid) ; do
			# Check if the PID is an active process and send an SIGTERM
         	PID=$(cat $PROCESS)
         	CHECK=$(ps aux | awk {'print $2'} | egrep "^${PID}$")
         	if [ -n $CHECK ] ; then
         		kill $PID
         	
         	# Else, delete the pidfile
         	else
         		rm $PROCESS
         	fi
		done
		
		sleep 1
	else
		for PROCESS in $(ls /var/run/mailtraced.*.pid) ; do
			# Check if the PID is an active process and kill him hard
         	PID=$(cat $PROCESS)
         	CHECK=$(ps aux | awk {'print $2'} | egrep "^${PID}$")
         	if [ -n $CHECK ] ; then
         		kill -9 $PID
         	fi
		done
		
		# Delete every pidfile, which is left
		rm /var/run/mailtraced.*.pid
	fi
	
	return 0
}

do_restart() {
	do_stop force
	do_start
	
	return $?
}

do_status() {
	if [ -f /var/run/mailtraced.*.pid ] ; then
		echo "Currently running instances: $(ls -l /var/run/mailtraced.*.pid | wc -l)"
		return 0
	else
		echo "No instances are running"
		return 1
	fi
}

case "$1" in
  start)
	log_begin_msg "Starting $DESC" "$NAME"
	do_start
	case "$?" in
		0) log_end_msg 0
		   ;;
		1) log_end_msg 1
		   ;;
	esac
	;;
  stop)
	log_begin_msg "Stopping $DESC" "$NAME"
	do_stop graceful
	log_end_msg 0
	;;
  force-stop)
	log_begin_msg "Forced stop $DESC" "$NAME"
	do_stop force
	log_end_msg 0
	;;
  restart)
	log_begin_msg "Restarting $DESC" "$NAME"
	do_restart

	case "$?" in
		0) log_end_msg 0
		   ;;
		1) log_end_msg 1
		   ;;
	esac
	;;
  status)
  	# Count the active instances
  	do_status
  	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|force-stop|status|restart}" >&2
	exit 3
	;;
esac
