#! /bin/sh
#------------------------------------------------------------------------------
##
##
#------------------------------------------------------------------------------
### BEGIN INIT INFO
# Provides:          yadifad
# Required-Start:    $local_fs $network
# Required-Stop:
# Should-Start:      udev module-init-tools
# Should-Stop:		 $named
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Starts the YADIFAD name server
# Description:		Starts the YADIFAD name server 
### END INIT INFO


PATH=/sbin:/usr/sbin:/bin:/usr/bin
PREFIX="/usr"
NAME="yadifad"
DAEMON="/sbin/${NAME}"

SCRIPTNAME="/etc/init.d/${NAME}"
PIDFILE="$PREFIX/var/run/yadifa.pid"

CHROOTS=0
CHROOTDIR=$PREFIX
YADIFA_CHROOT=/var

if [ "$DEBUG" = "" ]
then
	DEBUG=0
fi

log()
{
	echo $*
	logger -t $NAME-init-script -- $*
}

debug()
{
	if [ $DEBUG -ne 0 ]
	then
		echo $*
		logger -t $NAME-init-script -- $*
	fi
}

if [ $CHROOTS -ne 0 ]
then
	PREFIX=
fi

VAR="$PREFIX/var"
CONF="$PREFIX/etc/yadifad.conf"

if [ "$MAX_STOP_WAIT" = "" ]
then
	MAX_STOP_WAIT=5
fi

# Inside the internal chroot

if [ "$CORE_PREFIX" = "" ]
then
	CORE_PREFIX=/log
fi

if [ "$DUMPS_CORE" = "" ]
then
	DUMPS_CORE=1
fi

if [ $DUMPS_CORE -ne 0 ]
then
	if [ ! -d $CHROOTDIR/$YADIFA_CHROOT/$CORE_PREFIX ]
	then
		log "Core dump enabled but '$CHROOTDIR/$YADIFA_CHROOT/$CORE_PREFIX' directory does not exists"
		exit 1
	fi
fi

# not yet:
#
# CHECK="/sbin/yadifa-checkconf"


# $? : supposed to be set
# 1  : message
# 2  : optional override code
# 3  : what to do in case of error (command)

die_on_error()
{
        ERR="$?"
        
        if [ ! "" = "$2" ]
        then
        	ERR="$2"
        fi
        
        
        if [ 0 -ne ${ERR} ]
        then
        	if [ ! "" = "$3" ]
	        then
        		$3
	        fi
	        
                log "error: '$1' ($ERR)"
                exit $err
        fi
}

#
# Function that checks if yadifa is running
#

do_status_internal()
{
	debug "checking for valid PIDFILE ${PIDFILE}"

	running=0

	if [ -f ${PIDFILE} ]
	then
		PID=$(cat ${PIDFILE})

		if [ "${PID}" != "" ]
		then
			PROC=$(ps -p ${PID} | tail -1| awk '{print $4}')

			if [ "$PROC" = "$NAME" ]
			then
				running=1
			else
				log "error : process with pid ${PID} is '$PROC' and not '$NAME' : deleting pid file"
				rm -f ${PIDFILE}
			fi
		else
			log "error: empty '${PIDFILE}' : deleting pid file"
			rm -f ${PIDFILE}
		fi
	fi

	return $running
}

do_status()
{
	do_status_internal

	running=$?
	
	if [ $running -eq 1 ]
	then
		log "${NAME} seems to be already running."
		exit 0
	else
		log "${NAME} does not seem to be running."
		exit 1
	fi
}

#
# Function that starts the daemon/service
#
do_start()
{
	log "Starting $NAME"

	debug "starting if no valid PIDFILE ${PIDFILE}"

	do_status_internal

	running=$?

	if [ $running -eq 1 ]
	then
		log "${NAME} seems to be already running."
		exit 1
	fi
	
	debug cd $CHROOTDIR
	cd $CHROOTDIR

	debug prefix = ${PREFIX}
	debug daemon = ${DAEMON}

	if [ $DUMPS_CORE -ne 0 ]
	then
		COREPATH="$CHROOTDIR/$YADIFA_CHROOT/$CORE_PREFIX/cores"

		log "enabling core dump in $COREPATH"

		ulimit -c unlimited


		mkdir -p $COREPATH
		chmod 0777 $COREPATH
		chmod +t $COREPATH

		log "core dump will be stored in '$COREPATH' ($CORE_PREFIX/cores)"

		echo "$CORE_PREFIX/cores/core.%e.%p.%h.%t" > /proc/sys/kernel/core_pattern
		echo 0x7 > /proc/self/coredump_filter
		echo -n 1 > /proc/sys/kernel/core_uses_pid
		echo -n 1 > /proc/sys/fs/suid_dumpable
	fi

	CMD="${PREFIX}${DAEMON} -c ${CONF} --daemon"
	
	if [ $CHROOTS -ne 0 ]
	then
		CMD="chroot $CHROOTDIR $CMD"
	fi

	debug $CMD

	$CMD

	die_on_error "${DAEMON} returned $?"

	exit 0
}


#
# Function that stops the daemon/service
#
do_stop()
{
	log "Stopping $NAME"

	debug "stopping if valid PIDFILE ${PIDFILE}"

	if [ -f ${PIDFILE} ]
	then
		while [ -f ${PIDFILE} ]
		do
			PID=$(cat ${PIDFILE})

			if [ "${PID}" = "" ]
			then
				log "error: empty '${PIDFILE}' : deleting pid file"
				rm -f ${PIDFILE}
				break
			fi

			PROC=$(ps -p ${PID} | tail -1| awk '{print $4}')

			if [ "$PROC" != "$NAME" ]
			then
				log "error : process with pid ${PID} is '$PROC' and not '$NAME' : deleting pid file"
				rm -f ${PIDFILE}
				break
			fi

			kill ${PID} > /dev/null 2>&1

			for count in $(seq 0 $MAX_STOP_WAIT)
			do
				if [ ! -f ${PIDFILE} ]
				then
					break
				fi

				kill -0 ${PID} > /dev/null 2>&1

				if [ $? -ne 0 ]
				then
					rm -f ${PIDFILE}
					break
				fi

				log "waiting for the process to stop (waited $count seconds)"

				sleep 1
			done
		done
	else
		log "${NAME} does not seem to be running ..."
		debug "reason: ${PIDFILE} not found"
	fi
}

debug called with $1

case "$1" in
  start)
	do_start
	;;
  stop)
	do_stop
	;;
  restart)
	do_stop
	do_start
	;;
  status)
  	do_status
	;;
  *)
	log "Usage: $SCRIPTNAME {start|stop|restart|status}" >&2
	exit 3
	;;
esac

:
