#! /bin/sh
### BEGIN INIT INFO
# Provides:          qemu-system-x86
# Required-Start:    mountkernfs
# Required-Stop:     
# Should-Start:      udev devfsd
# Should-Stop:       
# Default-Start:     S
# Default-Stop:      
# Short-Description: QEMU KVM module loading script
# Description:       This script loads the kernel modules needed by QEMU KVM
### END INIT INFO

case "$1" in
    start|restart|force-reload)

	[ ! -e /dev/kvm ] || exit 0	# nothing to do

	# kernel 3.4+ autoloads modules
	case "$(uname -r 2>/dev/null)" in
	    3.[4-9]* | 3.[1-9][0-9]* | [4-9].*) exit 0 ;;
	esac

	# check if we're running inside an (lxc) container
	# (we may copy or move this to the postinst script too, to skip installing it)
	grep -zqs ^container= /proc/1/environ && exit 0

	. /lib/lsb/init-functions

	if grep -q '^flags.*\<vmx\>' /proc/cpuinfo; then
	    module=kvm_intel
	elif grep -q '^flags.*\<svm\>' /proc/cpuinfo; then
	    module=kvm_amd
	else
	    log_warning_msg "Your system does not have support for KVM"
	    exit 0
	fi
	if ! which modprobe >/dev/null; then
	    log_warning_msg "modprobe isn't installed, not loading kvm modules."
	    exit 0
	fi
	if modprobe -b $module ; then
	    log_success_msg "Loading kvm module $module"
	else
	    log_failure_msg "Module $module failed to load"
	    exit 1
	fi
	if modprobe -b vhost-net ; then
	    log_warning_msg "Module vhost-net failed to load"
	fi
	;;
  stop)
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac

:
