#!/bin/sh
#
# imdc                Start/Stop the InterMapper DataCenter service
#
#                     Usually, you will copy this file into /etc/init.d and
#                     create links to this file in /etc/rc3.d/S97imdc
#                     and /etc/rc6.d/K03imdc.
#
# chkconfig:          345 97 3
# description:        InterMapper DataCenter is a collection of servers and \
#                     tools to augment InterMapper's capabilities
# processname:        imdc

### BEGIN INIT INFO
# Provides:           imdc
# Required-Start:     $remote_fs $syslog $named $time
# Required-Stop:      $remote_fs $syslog $named $time
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  Start InterMapper DataCenter at boot time
# Description:        InterMapper DataCenter is a collection of servers and
#                     tools to augment InterMapper capabilities.
### END INIT INFO

PREFIX="/usr/local"

PROGNAME="imdc"

PROGPATH="${PREFIX}/imdc/core/python/bin/${PROGNAME}"
MAINPATH="${PREFIX}/imdc/imdc/main.py"
LOCKPATH="/var/lock/subsys/${PROGNAME}"

if [ ! -x /usr/local/imdc/sbin/imdc ] && [ ! -x "${PROGPATH}" ] ; then
	exit 5
elif [ -f "${MAINPATH}" ] ; then
	:
else
	exit 5
fi

# Load RedHat's library of shell functions

. /etc/rc.d/init.d/functions

RETVAL=0


#
# This is a replacement "__pids_pidof()" for use by "killproc()" and "status()".
# Previously we had to guard against getting the wrong "imdc" (namely the one
# running the switches server).  Now we need to allow for the "imdc" running
# the IMDC service having changed its name to "imdatacenter".
#
__pids_pidof() {
	pid=`ps -A -oppid=,pid=,args= | sed -n -e 's@^[ 	]*1[ 	][ 	]*\([1-9][0-9]*\)[ 	][ 	]*imdatacenter *$@\1@p'`
	if [ -n "${pid}" ] ; then
		printf '%s\n' "${pid}"
	else
		ps -A -oppid=,pid=,args= | sed -n -e "s@^[     ]*1[    ][  ]*\\([1-9][0-9]*\\)[  ]${PROGPATH}.*\$@\\1@p"
	fi
}

# replacement killproc, does not wait the full timeout if daemon exits early
killproc() {

	local RC killlevel= base pid pid_file= delay delayseconds

	RC=0; delay=3

	if [ "$#" -eq 0 ]; then
		echo $"Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]"
		return 1
	fi
	if [ "$1" = "-p" ]; then
		pid_file=$2
		shift 2
	fi
	if [ "$1" = "-d" ]; then
		delay=$2
		shift 2
	fi

	# Check for second arg to be kill level

	if [ -n "${2:-}" ] ; then
		killlevel=$2
	fi

	base=${1##*/}

	# Find pid

	__pids_var_run "$1" "$pid_file"
	if [ -z "$pid_file" -a -z "$pid" ]; then
		pid="$(__pids_pidof "$1")"
	fi

	# Kill it.

	if [ -n "$pid" ] ; then
		if [ "$BOOTUP" = "verbose" -a -z "${LSB:-}" ] ; then
			echo -n "$base "
		fi
		if [ -z "$killlevel" ]; then
			if checkpid $pid 2>&1; then

				# TERM first, then KILL if not dead

				kill -TERM $pid >/dev/null 2>&1
				usleep 100000
				delayseconds=0

				while [ $delayseconds -lt $delay ] && checkpid $pid ; do
					delayseconds=`expr $delayseconds + 1`
					sleep 1
				done

				if checkpid $pid ; then
					kill -KILL $pid >/dev/null 2>&1
					usleep 100000
				fi
			fi

			checkpid $pid
			RC=$?
			[ "$RC" -eq 0 ] && failure $"$base shutdown" || success $"$base shutdown"
			RC=$((! $RC))

		else
			if checkpid $pid; then
				kill $killlevel $pid >/dev/null 2>&1
				RC=$?
				[ "$RC" -eq 0 ] && success $"$base $killlevel" || failure $"$base $killlevel"
			elif [ -n "${LSB:-}" ]; then
				RC=7 # Program is not running
			fi
		fi
	else
		if [ -n "${LSB:-}" -a -n "$killlevel" ]; then
			RC=7 # Program is not running
		else
			failure $"$base shutdown"
			RC=0
		fi
	fi

	# Remove pid file if any.

	if [ -z "$killlevel" ]; then
		rm -f "${pid_file:-/var/run/$base.pid}"
	fi

	return $RC
}


getMountPoint() {
    df -P "${1:-.}" |
        sed -n -e '2s/^.*[%-][ 	][ 	]*\(\/.*\)$/\1/p'
}

isNoExec() {
    point=`getMountPoint "${1:-.}"`
    if [ -z "${point}" ] ; then
        return 1
    else
        point=`printf '%s\n' "${point}" | sed -e 's:/:\\\\/:g'`
        mountOption=""
        filter="/ on ${point} type/"
        extract='/^.*(\(.*\))$/\1/'
        delimiter=','
        flag="noexec"
        mount |
            sed -n -e "${filter}s${extract}p" |
            sed -e "s@${delimiter}[ 	][ 	]*@${delimiter}@g" |
            tr "${delimiter}" '\012' | grep "^${flag}\$" >/dev/null
        return $?
    fi
}

getSettings() {
    if [ -r /usr/local/etc/intermapperd.conf ] ; then
        sed -n -e 's@^[ 	]*SettingsFolder[ 	][ 	]*"\(.*\)"[ 	]*$@\1@p' \
               -e 's@^[ 	]*SettingsFolder[ 	][ 	]*\([^"].*\)$@\1@' \
            /usr/local/etc/intermapperd.conf
    fi
}

start() {
	echo -n "Starting InterMapper DataCenter: "
	if [ -x /usr/local/imdc/sbin/imdc ] ; then
		/usr/local/imdc/sbin/imdc start ; RETVAL=$?
	else
		if isNoExec "${TMPDIR:-/tmp}" ; then
			settings=`getSettings`
			if [ -z "${settings}" ] ; then
				settings="/var/local/InterMapper_Settings"
			fi
			if [ -d "${settings}/Temporary" ] ; then
				TMPDIR="${settings}/Temporary" ; export TMPDIR
			fi
		fi
		"$PROGPATH" -OO "$MAINPATH" setuid daemonize ; RETVAL=$?
	fi
	echo
	if [ $RETVAL -eq 0 ] ; then
		touch "$LOCKPATH"
	fi
	return $RETVAL
}

stop() {
	echo -n "Stopping InterMapper DataCenter: "
	killproc -d 600 "$PROGPATH"
	RETVAL=$?
	echo
	if [ $RETVAL -eq 0 ] ; then
		rm -f "$LOCKPATH"
	fi
	return $RETVAL
}

restart() {
	stop
	sleep 5
	start
}

condrestart() {
	if [ -e "$LOCKPATH" ] ; then
		restart
	fi
	return 0
}

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart)
	restart
	;;
condrestart)
	condrestart
	;;
status)
	status "$PROGPATH"
	RETVAL=$?
	;;
*)
	echo "Usage: $0 (start|stop|status|restart|condrestart)"
	RETVAL=1
esac

exit $RETVAL
