#!/bin/sh

OSNAME=`uname -s`
PREFIX='/usr/local/imdc'

##########################################################################
# This function is used to guarantee IMDC is dead, after unloading it.
##########################################################################

killIMDC()
{
	#
	# Note that this function looks for the IMDC process by keying "ps(1)"
	# output for its command line text.  Under Python-2 the IMDC application
	# attempts to change its command line to "imdatacenter" (and succeeds)
	# on macOS.  Under Python-3 it tries more generally.
	#
	# Note that "ps(1)" implementations differ in whether the "comm" field
	# gets the original (read-only) executable program name, or the first
	# word of the (mutable) command arguments.  The "args" field should
	# always be read from the command arguments.
	#
	# Note that we constrain the process match to processes with parent
	# process id "1"; that ensures we do not clobber an instance of "imdc"
	# which is running "switches", but it may cause a false negative in
	# containerized environments (e.g. Solaris zones).
	#
	systemdPid=$(ps -A -opid=,ppid=,comm= | sed -n -e 's/^[ 	]*\([1-9][0-9]*\)[ 	][ 	]*1[ 	][ 	]*systemd$/\1/p' | grep -v '^1$' | sed 1q)
	systemdPid="${systemdPid:-1}"
	onePid="1"
	pid=$(ps -A -oppid=,pid=,args= | \
		  sed "s/\\([ 	][ 	]*\\)${systemdPid}\\([ 	][ 	]*\\)/\\1${onePid}\\2/" | \
		  sed -n -e 's@^[ 	]*1[ 	][ 	]*\([1-9][0-9]*\)[ 	][ 	]*imdatacenter *$@\1@p')
	if [ -z "${pid}" ] ; then
		pid=$(ps -A -oppid=,pid=,args= | \
			  sed "s/\\([ 	][ 	]*\\)${systemdPid}\\([ 	][ 	]*\\)/\\1${onePid}\\2/" | \
			  sed -n -e "s@^[ 	]*1[ 	][ 	]*\\([1-9][0-9]*\\)[ 	].*/core/python.*/bin/imdc.*\$@\\1@p")
	fi
	if [ -n "${pid}" ] && kill "${pid}" ; then
		return 0
	else
		return 1
	fi

}

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} /"
		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
}

##########################################################################
# This function starts IMDC directly, without going through the
# OS-specific 'load daemon' process.  Any arguments to execIMDC are passed
# to IMDC, so this is used for, i.e. 'pwreset' or '--help'.
##########################################################################

execIMDC()
{
	if [ -r "${PREFIX}/imdc/main.py" ] ; then
		main="main.py"
	else
		echo 1>&2 "imdc: could not find main module \"${PREFIX}/imdc/main.py\""
		exit 1
	fi
	if isNoExec "${TMPDIR:-/tmp}" ; then
		settings=`getSettings`
		if [ -n "${settings}" ] ; then
			:
        elif [ "x`uname -s`" = "xDarwin" ] ; then
			settings="/Library/Application Support/InterMapper Settings"
		else
			settings="/var/local/InterMapper_Settings"
		fi
		if [ -d "${settings}/Temporary" ] ; then
			TMPDIR="${settings}/Temporary" ; export TMPDIR
		fi
	fi
	if [ -r "${PREFIX}/core/python3/venv/bin/activate" ] ; then
		. "${PREFIX}/core/python3/venv/bin/activate"
		exec python "${PREFIX}/imdc/${main}" ${1+"$@"}
	else
		exec "${PREFIX}/core/python/bin/imdc" -OO "${PREFIX}/imdc/${main}" ${1+"$@"}
	fi
}

##########################################################################
# This function starts IMDC through the proper OS-specific channel.
##########################################################################

startIMDC()
{
	if [ "x${OSNAME}" = "xDarwin" ] ; then
		printf 'Starting IMDC Service...'
		/bin/launchctl load -w /Library/LaunchDaemons/com.dartware.InterMapperDataCenter.plist >/dev/null 2>&1 &&
			printf 'done\n'
	else
		execIMDC ${1+"$@"} setuid daemonize
	fi
}

#
# This shell function is used downstream of the launchd "plist" on macOS.
# It is useful for debugging on non-macOS UNIX platforme too.  Therefore
# we give it an official sub-command "osxexec" for macOS, and an un-official
# one "exec" for more general debug use.
#
osxexecIMDC()
{
	if [ "x${OSNAME}" != "xDarwin" ] && [ "x${1}" = "xosxexec" ] ; then
		echo 1>&2 "imdc: sub-command \"osxexec\" is not available on non-Darwin platforms"
		exit 1
	else
		if [ -r /usr/local/imdc/imdc/main.py ] ; then
			main="main.py"
		else
			echo 1>&2 "imdc: could not find main program \"main.py\""
			exit 1
		fi
		if isNoExec "${TMPDIR:-/tmp}" ; then
			settings=`getSettings`
			if [ -z "${settings}" ] ; then
				settings="/Library/Application Support/InterMapper Settings"
			fi
			if [ -d "${settings}/Temporary" ] ; then
				TMPDIR="${settings}/Temporary" ; export TMPDIR
			fi
		fi
		shift # skip over "${action}" (i.e. either "exec" or "osxexec"), and interpose wrapper (if any)
		if [ -r "/usr/local/imdc/core/python3/venv/bin/activate" ] ; then
			. "/usr/local/imdc/core/python3/venv/bin/activate"
			exec ${1+"$@"} python "/usr/local/imdc/imdc/${main}" setuid
		else
			exec ${1+"$@"} "/usr/local/imdc/core/python/bin/imdc" -OO "/usr/local/imdc/imdc/${main}"
		fi
	fi
}

##########################################################################
# This function stops IMDC through the proper OS-specific channel, then
# checks whether the PID is still around, and really kills it if so.
##########################################################################

stopIMDC()
{
	printf 'Stopping IMDC Service...'

	if [ "x${OSNAME}" = "xDarwin" ] ; then
		/bin/launchctl unload -w /Library/LaunchDaemons/com.dartware.InterMapperDataCenter.plist >/dev/null 2>&1
	elif [ "x${OSNAME}" = "xSunOS" ] ; then
		pkill -x imdc >/dev/null 2>&1
	elif [ "x${OSNAME}" = "xLinux" ] ; then
		if [ -f /etc/SuSE-release ] ; then
			/sbin/killproc -TERM imdc >/dev/null 2>&1
		elif [ ! -f /etc/debian_version ] ; then
			# RedHat, and other Linux flavors
			killIMDC
		else
			major=$(set -- `sed -n -e '1s/\./ /gp' /etc/debian_version` ; echo $1)
			if [ "${major:-0}" -ge 10 ] 2>/dev/null ; then
				killIMDC
			else
				/sbin/start-stop-daemon --retry 15 --quiet --stop --name imdc >/dev/null 2>&1
			fi
		fi
	else
		killIMDC
	fi

	if [ $? -eq 0 ] ; then
		printf 'done\n'
	elif killIMDC ; then
		printf 'done\n'
	else
		printf 'not running\n'
	fi
}

##########################################################################
# Check for known arguments like 'start' or 'stop', and act on them by
# loading/unloading IMDC as necessary.  Any further arguments are passed
# through to IMDC itself, which has a more extensive command-line handler.
##########################################################################

if [ $# -eq 0 ] ; then
	execIMDC "--help"
else
	eval action=\$$#
	case "${action}" in
		start)
			startIMDC ${1+"$@"}
			;;
		stop)
			stopIMDC
			;;
		restart)
			stopIMDC
			sleep 5
			startIMDC ${1+"$@"}
			;;
		pwreset)
			stopIMDC
			execIMDC ${1+"$@"}
			;;
		osxexec|exec)
			# On Linux the following is good way to recover error messages that are going to "/dev/nulL"
			if false ; then
				osxexecIMDC "${action}" strace -e write -s 4096 -f
			else
				osxexecIMDC "${action}"
			fi
			;;
		*)
			execIMDC ${1+"$@"}
			;;
	esac
fi
