#!/bin/bash
#
# vzeventd	This shell script takes care of starting and stopping
#               vzeventd daemon for OpenVZ.
#
# chkconfig: - 95 89
# description: vzeventd is OpenVZ events daemon. \
# It takes care of events sent by the OpenVZ kernel and performs required \
# actions associated with those events.

### BEGIN INIT INFO
# Provides: vzeventd
# Required-start: $remote_fs
# Required-stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Start-Before: vz
# X-Stop-After: vz
# Short-Description: start and stop vzeventd
# Description: vzeventd is the OpenVZ events daemon.
#              It takes care of events sent by the OpenVZ kernel
#              and performs required actions associated with those events.
### END INIT INFO

WITHOUT_RC_COMPAT=1

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

prog=vzeventd
LOCKFILE=/var/lock/subsys/$prog

load_module() {
	action "Loading module vzevent:" modprobe vzevent reboot_event=1
}

unload_module() {
	local mod rc=0
	for mod in vzevent; do
		lsmod |grep -qs "^$mod[[:space:]]" || continue
		printf %s "Unloading module $mod: "
		modprobe -r "$mod" >/dev/null 2>&1 &&
			success "$STRING" || passed "$STRING"
		[ "$rc" = 0 ] || rc=$?
		echo
	done
	return $rc
}

check() {

	echo -n "Checking vzevent kernel module ..."

	if ! lsmod | fgrep -qw vzevent; then
		echo_failure
		echo
		return 1
	fi
	if ! cat /sys/module/vzevent/{,parameters/}reboot_event 2>/dev/null | fgrep -qw 1; then
		echo_failure
		echo
		echo "vzevent module should be loaded with reboot_event=1 parameter"
		return 1
	fi
	echo_success
	echo
	return 0
}

start() {
	[ "$EUID" != "0" ] && exit 4
	[ -x /usr/sbin/vzeventd ] || exit 5
	[ -r /etc/sysconfig/vzeventd ] && . /etc/sysconfig/vzeventd

	[ -f $LOCKFILE ] && exit 0 # Already running
	load_module
	check || exit 1

	start_daemon --lockfile "$LOCKFILE" --expect-user root -- $prog $OPTIONS
	RETVAL=$?
	return $RETVAL
}

stop() {
	[ "$EUID" != "0" ] && exit 4
	stop_daemon --lockfile "$LOCKFILE" --expect-user root -- $prog
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		unload_module
	fi
	return $RETVAL
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart|condreload)
		if [ -e "$LOCKFILE" ]; then
			stop
			start
		fi
		;;
	status)
		status --expect-user root -- $prog
		RETVAL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
