#!/bin/sh
#
# vmware-guestd:   VMware Guest Tools
#
# chkconfig: - 98 02
# description: open-vm-tools starts vmware-guestd and loads appropriate modules
#
# servicename: open-vm-tools
#

# Source function library.
. /etc/init.d/functions

[ -f /etc/sysconfig/open-vm-tools ] && . /etc/sysconfig/open-vm-tools

# Make sure we're running in a VM
/usr/sbin/vmware-checkvm > /dev/null || exit 0

# so we can rearrange this easily
servicename=vmware-guestd

DND_TMPDIR="/tmp/VMwareDnD"
RETVAL=0

start() {
        if [[ -n "${LOAD_VMBLOCK}" && ${LOAD_VMBLOCK} ]] ; then
		echo -n $"Loading vmblock module: "

  		if [ ! -d "${DND_TMPDIR}" ]; then
			mkdir "${DND_TMPDIR}"
		fi
		chown root:root "${DND_TMPDIR}"
		chmod 1777 "${DND_TMPDIR}"
		modprobe vmblock && success || failure
                echo
	fi

        if [[ -n "${LOAD_VMMEMCTL}" && ${LOAD_VMMEMCTL} ]] ; then
		echo -n $"Loading vmmemctl module: "
		modprobe vmmemctl && success || failure
                echo
	fi

	echo -n $"Starting VMware guestd: "
	daemon $servicename --background /var/run/vmware-guestd.pid
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$servicename
}

stop() {
	echo -n $"Stopping VMware guestd: "

	killproc $servicename -TERM
	RETVAL=$?
	echo
	if [ $RETVAL -eq 0 ]; then
		rm -f /var/lock/subsys/$servicename
	fi

        if grep -q vmmemctl /proc/modules ; then
	        echo -n $"Removing vmmemctl module: "
		rmmod vmmemctl && success || failure
		echo
	fi

        if grep -q vmblock /proc/modules ; then
        	echo -n $"Removing vmblock module: "
		rmmod vmblock && success || failure
		echo
	fi
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status $servicename
		RETVAL=$?
		;;
	restart)
		stop
		start
		;;
	condrestart)
		if [ -f /var/lock/subsys/$servicename ]; then
			stop
			start
		fi
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart|condrestart}"
		;;
esac
exit $RETVAL
