#!/bin/sh
# (C) 2007 Michael Meskes <meskes@debian.org>

### BEGIN INIT INFO
# Provides:          vboxguest virtualbox-ose-guest-utils
# Short-Description: VirtualBox Linux Additions
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

PATH=$PATH:/bin:/sbin:/usr/sbin

. /lib/lsb/init-functions

test -d /usr/share/doc/virtualbox-ose-guest-utils -a -x /usr/sbin/VBoxService || exit 0

in_virtual_machine()
{
	if [ -z "$(lspci -d 80ee:beef)" ]; then
		log_warning_msg "VirtualBox Additions disabled, not in a Virtual Machine"
		return 1
	fi

	return 0
}

running()
{
    lsmod | grep -q "$1[^_-]"
}

case "$1" in
  start)
	in_virtual_machine || exit 0
	log_begin_msg "Starting VirtualBox Additions"

	# should already be loaded automatically
	if ! running vboxguest; then
		if ! modprobe vboxguest > /dev/null 2>&1; then
			# vboxguest not installed, or has a problem
			log_failure_msg "Guest additions not available, kernel module not loadable (vboxguest)"
			log_end_msg 1
			exit 1
		fi
	fi

	if ! running vboxvfs; then
		if ! modprobe vboxvfs > /dev/null 2>&1; then
			# vboxvfs not installed, or has a problem
			log_failure_msg "Shared folders not available, kernel module not loadable (vboxvfs)"
			log_end_msg 1
			exit 1
		fi
	fi

	# Mount all shared folders from /etc/fstab. Normally this is done by some
	# other startup script but this requires the vboxvfs kernel module loaded.
	mount -a -t vboxsf

	start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/VBoxService
	if [ $? -ne 0 ]; then
		log_end_msg 1
		exit 1
	fi

	log_end_msg 0
	;;

  stop)
	in_virtual_machine || exit 0
	log_begin_msg "Stopping VirtualBox Additions"

	start-stop-daemon --stop --quiet --oknodo --exec /usr/sbin/VBoxService
	if [ $? -ne 0 ]; then
		log_end_msg 1
		exit 1
	fi

	umount -a -t vboxsf

	if running vboxvfs; then
		if ! rmmod vboxvfs 2>/dev/null; then
			log_failure_msg "Cannot unload shared folders kernel module (vboxvfs)"
			log_end_msg 1
			exit 1
		fi
	fi

	if running vboxguest; then
		if ! rmmod vboxguest 2>/dev/null; then
			log_failure_msg "Cannot unload guest additions kernel module (vboxguest)"
			log_end_msg 1
			exit 1
		fi
	fi

	log_end_msg 0
	;;

  restart|force-reload)
	$0 stop && $0 start
	;;

  status)
	status=0

	if ! running vboxguest; then
		echo "Guest additions kernel module (vboxguest) not loaded"
		status=3
	fi

	if ! running vboxvfs; then
		echo "Shared folders kernel module (vboxvfs) not loaded"
		status=3
	fi

	if ! pgrep -x VBoxService > /dev/null; then
		echo "VBoxService daemon isn't running"
		status=3
	fi

	exit $status
	;;

  *)
	echo "Usage: $0 {start|stop|restart|force-reload|status}"
	exit 1
	;;
esac
