#!/bin/bash
#
# cagefs        Startup script for CageFS
#
# chkconfig: 2345 29 89
# description: CageFS Startup Script

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

prog="CageFS"
cagefs_bin="/usr/sbin/cagefsctl"
lvectl_bin="/usr/sbin/lvectl"
SKELETON=/usr/share/cagefs-skeleton

RETVAL=0

print_status() {
	if [ $RETVAL -ne 0 ]; then
	#	echo -e "\e[31;40m[FAILED]\e[00m"
		failure
	else
	#	echo -e "\e[32;40m[OK]\e[00m"
		success
	fi
	echo
}

start() {
	$cagefs_bin --mount-skel
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		print_status
		return $RETVAL
	fi

	$lvectl_bin destroy all --force
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		print_status
		return $RETVAL
	fi

	sleep 1

	$cagefs_bin --remove-unused-mount-points

	$lvectl_bin apply all --force
	RETVAL=$?
	rm -f /usr/share/cagefs/need.remount
	print_status
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/cagefs
	return $RETVAL
}

restart() {
	echo -n $"Restarting $prog: "
	# stop
	start
}

stop() {
	echo -n $"Stopping $prog: "

	$cagefs_bin --unmount-skel
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		print_status
		return $RETVAL
	fi

	$lvectl_bin destroy all
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		print_status
		return $RETVAL
	fi

	sleep 1

	$cagefs_bin --remove-unused-mount-points

	$lvectl_bin apply all
	RETVAL=$?
	print_status
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/cagefs
	return $RETVAL
}


print_cagefs_status() {
	if [ -e /var/lock/subsys/cagefs ]; then
		if [ -e $SKELETON/proc/cpuinfo ]; then
			echo "cagefs is running."
			return 0
		fi
		echo "cagefs is dead but subsys is locked."
		return 1
	else
		if [ ! -e $SKELETON/proc/cpuinfo ]; then
			echo "cagefs is stopped."
			return 0
		fi
		echo "cagefs is running but subsys is unlocked."
		return 1
	fi
}


# See how we were called.
case "$1" in
	start)
		echo -n $"Starting $prog: "
		start
		;;
	restart)
		if [ -e /usr/share/cagefs/skip.cagefs.restart ]; then
			rm -f /usr/share/cagefs/skip.cagefs.restart
			exit 0
		fi
		restart
		;;
	stop)
		stop
		;;
	status)
		print_cagefs_status
	;;
	*)
		echo $"Usage: $0 {start|restart|stop|status}"
		exit 1
esac

exit $RETVAL
