#!/bin/sh
#
# virtualbox	VirtualBox virtualizer for x86 hardware
#
# chkconfig:	345 83 26
#
# description:	Oracle VirtualBox is a general-purpose full virtualizer for x86 \
#		hardware. Targeted at server, desktop and embedded use.
#
# $Id$

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

VBOX_MODULE="vboxguest"
VBOX_GUEST_DEVICE="/dev/vboxguest"
VBOX_USER_DEVICE="/dev/vboxuser"

# Get service config - may override defaults
[ -f /etc/sysconfig/virtualbox ] && . /etc/sysconfig/virtualbox

setup() {
	local VBOX_MODULE=$1 VBOX_DEVICE=$2
	modprobe -s $VBOX_MODULE
	RETVAL=$?

	if [ -d /dev/.udev ] || [ -d /run/udev/rules.d ]; then
		return $RETVAL
	fi

	# set proper $VBOX_DEVICE for systems with static dev
	show "Setting $VBOX_DEVICE entry"; busy
	rm -f $VBOX_DEVICE
	VBOX_MAJOR=$(awk -vdevice="${VBOX_DEVICE#/dev/}" '$2 == device {print $1}' /proc/devices)
	if [ -n "$VBOX_MAJOR" ]; then
		VBOX_MINOR=0
	else
		VBOX_MINOR=$(awk -vdevice="${VBOX_DEVICE#/dev/}" '$2 == device {print $1}' /proc/misc)
		if [ -n "$VBOX_MINOR" ]; then
			VBOX_MAJOR=$(awk '$2 == "misc" {print $1}' /proc/devices)
		fi
	fi

	if [ -z "$VBOX_MAJOR" ]; then
		/sbin/rmmod $VBOX_MODULE
		RETVAL=1
	elif ! mknod -m 0660 $VBOX_DEVICE c $VBOX_MAJOR $VBOX_MINOR; then
		RETVAL=$?
		rmmod $VBOX_MODNAME
		fail
	elif ! chown root:vbox $VBOX_DEVICE; then
		RETVAL=$?
		fail
	else
		ok
	fi
	return $RETVAL
}

start() {
	if [ -f /var/lock/subsys/$VBOX_MODULE ]; then
		return
	fi

	setup $VBOX_MODULE $VBOX_GUEST_DEVICE || exit $?
	setup $VBOX_MODULE $VBOX_USER_DEVICE || exit $?
	touch /var/lock/subsys/$VBOX_MODULE
}

stop() {
	# NOTE: rmmod will wait if device is in use, so automatic rmmod probably is not the best idea
	/sbin/rmmod $VBOX_MODULE
	rm -f /var/lock/subsys/$VBOX_MODULE
}

condrestart() {
	if [ -f /var/lock/subsys/$VBOX_MODULE ]; then
		stop
		start
	else
		RETVAL=$1
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  setup)
	setup
	;;
  status)
	if ! is_module $VBOX_MODULE; then
		echo "$VBOX_MODULE module is loaded"
	else
		echo "$VBOX_MODULE module is not loaded"
		RETVAL=3
	fi
	if [ ! -c $VBOX_DEVICE ]; then
		echo "$VBOX_DEVICE does not exist"
		RETVAL=3
	else
		echo "$VBOX_DEVICE exists with major/minor $(ls -l $VBOX_DEVICE | awk '{print $5 $6}')"
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|setup|status}"
	exit 3
esac

exit $RETVAL
