#!/bin/bash
# chkconfig: 2345 40 40
# description: Cloud Management Init Script

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

RETVAL=0
CPNS="10.248.0.0/14/25* 10.244.0.0/14/25*"

start() {
	# Loading Kernel Module
	if [ -z "$(lsmod | grep ip_vzprivnet)" ]; then 
		modprobe ip_vzprivnet || RETVAL=2
	fi
	
	if [ "$(lsmod | grep ip_vzprivnet)" ]; then
		# Adding Private Networks
		for CPN in ${CPNS}; do
			echo "+${CPN}" > /proc/net/ip_vzprivnet
		done
	else
		RETVAL=2
	fi
	
	# Checking NFS Mount
	for MOUNT in $(cat /etc/fstab | egrep ".*:/.*/.*nfs" | awk '{print $2}'); do
		MOUNTS=$(mount | grep "on ${MOUNT} type nfs")
		if [ -z "${MOUNTS}" ]; then 
			mount ${MOUNT}
		fi
	done

	# Report Kernelversion to Backend
	KRN=$(uname -r)
	wget -q "http://install.intergenia.de:81/response.php?action=setKernelVersion&version=${KRN}"
	
	return ${RETVAL}
}	

stop() {
	# Unloading Kernel Module
	if [ "$(lsmod | grep ip_vzprivnet)" ]; then 
		# Removing Private Networks
		for CPN in ${CPNS}; do
			echo "-${CPN}" > /proc/net/ip_vzprivnet
		done

		rmmod ip_vzprivnet || RETVAL=2
	fi
	return ${RETVAL}
}

status() {
	CT_CPNS=0
	if [ "$(lsmod | grep ip_vzprivnet)" ]; then
		CT_CPNS=$(cat /proc/net/ip_vzprivnet | wc -l)
	fi
	CT_MOUNTS=$(mount | egrep ".*:.* on .* type nfs" | wc -l)

	echo "CPNs: ${CT_CPNS} active"
	echo "Mounts: ${CT_MOUNTS} active"
}

restart() {
	stop
	start
}	
reload()  {
	restart
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status
		;;
	restart)
		restart
		;;
	reload)
		reload
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart|reload}"
		exit 2
esac

exit $?

exit 0
