#!/bin/bash
#
# lve-kmod      Bring up/down lve kernel interface
#
# chkconfig: 2345 10 90
# description: load and unload lve module
#

# Source function library.
. /etc/init.d/functions
UNAME_MAJOR=$(uname -r | awk -F '-' '{print $1}')

if [ ! -f /etc/sysconfig/lve ]; then
    exit 0
fi

. /etc/sysconfig/lve

if [ "$UNAME_MAJOR" != "2.6.32" ] && [ ! -d /sys/fs/cgroup ]; then
    mkdir -p /sys/fs/cgroup
fi

if [ "$UNAME_MAJOR" != "2.6.32" ] && [ -e /sys/fs/cgroup ]; then
    mountpoint -q /sys/fs/cgroup || mount -t tmpfs cgroup_root /sys/fs/cgroup
    mount -o remount,rw /sys/fs/cgroup
    for item in freezer devices 'cpu,cpuacct' cpuset memory; do
        CGROUP_PATH="/sys/fs/cgroup/$item"
        if [ ! -d "$CGROUP_PATH" ]; then
            mkdir -p "$CGROUP_PATH"
        fi
        grep -q "$CGROUP_PATH" /proc/mounts
        if [ $? -ne 0 ]; then
            mount -t cgroup cgroup "$CGROUP_PATH" -o "$item"
        fi
    done
fi

# Check that lve is enabled.
[ "${LVE_ENABLE}" != "yes" ] && exit 0

KERNEL_UNAME=$(uname -r)

if [ ! -e "/lib/modules/$KERNEL_UNAME/extra/lve/kmodlve.ko" ] && \
[ ! -e "/lib/modules/$KERNEL_UNAME/kernel/kmodlve/kmodlve.ko" ] && \
[ ! -e "/lib/modules/$KERNEL_UNAME/extra/kmodlve.ko" ] && \
[ ! -e "/lib/modules/$KERNEL_UNAME/kernel/lve/lve.ko" ] && \
[ ! -e "/lib/modules/$KERNEL_UNAME/extra/lve/lve.ko" ]; then
    echo "LVE module is missing"
    exit 1
fi

if [ -f "/lib/modules/$KERNEL_UNAME/extra/lve/lve.ko" ] || \
[ -f "/lib/modules/$KERNEL_UNAME/kernel/lve/lve.ko" ]; then
    MODULE_NAME=lve
else
    MODULE_NAME=kmodlve
fi

# See how we were called.
case "$1" in
  start)
	echo $"loading LVE module"
    if [ ${MODULE_NAME} = "lve" ]; then
        if [ -f /etc/sysconfig/iolimits ]; then
            . /etc/sysconfig/iolimits
            if [ "${IOLIMITS_ENABLED}" = "yes" ]; then
                modprobe iolimits
                touch /var/lock/subsys/iolimits
            fi
       	fi
	fi
	modprobe ${MODULE_NAME}
        touch /var/lock/subsys/lve-kmod
        ;;
  stop)
	echo $"unloading LVE module"
	lvectl destroy all
	rmmod ${MODULE_NAME}
	rm -f /var/lock/subsys/lve-kmod
	if [ ${MODULE_NAME} = "lve" ]; then
		if [ -f /var/lock/subsys/iolimits ] ; then
            rmmod iolimits
            rm -f /var/lock/subsys/iolimits
       	fi
	fi
        ;;
  status)
	;;
  restart|reload)
	$0 stop
	$0 start
	;;
  *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
        exit 1
esac

exit 0
