#!/bin/bash
#
# /usr/sbin/kiwi-ltsp-aoe
#
# LTSP using AoE
#
# Copyright (c) 2009 IntelliAnt, Kolkata, India
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors:              Shrenik Bhura, 2009
#                       Alex Savin <alexqwesa@opensuse.org>, 2010
#
# Version       Date            Changes
# 0.1           2009-02-28      Initial release
# 0.2           2010-08-27      Replaced AOE_* variable to LTSP_*,
#                               (some AOE_* variable still used for compatibity
#                               with old config - TODO: drop this in next versions) 
# 0.3           2010-09-26      Use write_ltsp_config_files() from kiwi-ltsp-functions.sh 
#                               to sets up config files
# 0.4           2010-12-22      Support multiple networks($DHCP_IFACES instead $DHCP_IFACE)
#                               and minor changes
# 0.5           2012-08-13      Autorespawn vblade processes 
#
#################################################################################

#======================================
# Check to make we are running as root
#--------------------------------------
# TODO: rework this check
# if [ x"`whoami`" != x"root" ]; then
# 	echo "You have to be root to run this script"
# 	echo "If you did 'su' to become root, please redo it with 'su -'"
# 	exit 1
# fi
#======================================
# Load configs
#--------------------------------------
CONF_FILE="kiwi-ltsp"
if ! . /etc/sysconfig/$CONF_FILE  2>/dev/null; then
	if [ "$1" = "stop" ]; then 
		exit 0
	else 
		echo "Could not find $CONF_FILE in /etc/sysconfig "
		exit 6
	fi
	exit 1
fi
CONF_FILE_DATE=`stat --format=%Y /etc/sysconfig/$CONF_FILE`
#======================================
# Load shared library
#--------------------------------------
if [[ -L "$0" ]] ; then 
	KL_WRAPPER="`readlink -f "$0"`"
	KIWI_INCLUDE_NEW="`dirname "$KL_WRAPPER"`"
fi
if ! . $KIWI_INCLUDE/kiwi-ltsp-functions.sh 2>/dev/null; then
	echo "Could not find $KIWI_INCLUDE/kiwi-ltsp-functions.sh"
	echo "Check KIWI_INCLUDE variable in /etc/sysconfig/kiwi-ltsp file"
	echo "it standart value: /usr/share/kiwi-ltsp/ , current value: $KIWI_INCLUDE"
	exit 1
fi
#======================================
# Check variables
#--------------------------------------
if [[ -z "`echo $IMAGETYPE | grep AOE`" ]]; then 
	echo "KIWI-LTSP is configured for non-AoE setup."
	exit 6
fi
if [[ ! -e "$LTSP_IMG_DIR" ]] ; then
	check_variables           # this should init LTSP_IMG_DIR to default value
fi
if [[ -z "$DHCP_IFACES" || "$DHCP_IFACES" == "any" || "$DHCP_IFACES" == "ANY" ]] ; then
	init_network_variables    # this should init DHCP_IFACES to default value
fi
LTSP_PROFILES="`echo $LTSP_PROFILES | tr '[:space:]' ' '`"
if [[ -n "$AOE_IMG_ORDER" ]] ; then
	echo "Warning: AOE_IMG_ORDER is deprecated, delete it and use LTSP_PROFILES"
	echo "also, replace \$AOE_IMG_0n (n - number) to \$LTSP_MAC_FOR_name (name case sensitive) "
	#LTSP_PROFILES="$AOE_IMG_ORDER $LTSP_PROFILES"
fi
#======================================
# Sets variables to default value
#--------------------------------------
case "$1" in
	start)
		# to keep this process alive as required by startproc; does not seem to be an overkill, there may be a better way
		vbshelf=0
		vbslot=1
		for prfName in $LTSP_PROFILES
		do
			# check to prevent duplicate mounting of same image
			#lodev=`losetup -j $LTSP_IMG_DIR/$prfName | cut -d ":" -f 1`
			#if [ -z "$lodev" ]; then
			#	# determine the next free loop device
			#	lodev=`losetup -f`
				# Images mounted in default sorted order as returned by ls
			#	losetup $lodev $LTSP_IMG_DIR/$prfName
			#fi
			suffix=".img"
			[[ ! -f "$LTSP_IMG_DIR/$prfName.img" && -f "$LTSP_IMG_DIR/$prfName" ]] && \
				suffix=""
			if [[ -f $LTSP_IMG_DIR/$prfName$suffix ]] ; then
				if [[ -z $2 || $prfName == $2  ]] ; then
					if [[ -n $DHCP_IFACES ]] ; then
						for eth in $DHCP_IFACES
							do
							if [[ -z `ps --format args a -u root | grep -v ^grep | grep  "vblade $vbshelf $vbslot $eth $LTSP_IMG_DIR/$prfName$suffix"` ]] ; then
								vblade $vbshelf $vbslot $eth $LTSP_IMG_DIR/$prfName$suffix < /dev/null 2>&1 | logger -t vbladed &
							fi
						done
					else
						echo "Networks not found - Aborting!"
						exit 1
					fi
				fi
			else
				echo "Warning: Image $LTSP_IMG_DIR/$prfName$suffix - not found"
			fi
			((vbshelf++))
		done
		#======================================
		# Stop checking vblade processes if config file changed
		#--------------------------------------
		if [[ $CONF_FILE_DATE != `stat --format=%Y /etc/sysconfig/$CONF_FILE` ]] ; then
			echo "/etc/sysconfig/$CONF_FILE is changed, probably you should restart klaoe service"
			exit 0 
		fi
		;;
	stop)
		if [[ -z $2 ]] ; then
			killall vblade || true
		elif [[ -n `ps --format args a -u root | grep -v ^grep | grep  "vblade" | grep " $LTSP_IMG_DIR/$2$suffix"` ]] ; then
			kill `ps --format args a -u root | grep -v ^grep | grep  "vblade" | grep " $LTSP_IMG_DIR/$2$suffix"`
		else
			echo "$2 is not running, nothing to do."
		fi
		#for i in $images
		#do
			#determine the used loop devices for kiwi-ltsp-aoe and free each
			#lodev=`losetup -j $LTSP_IMG_DIR/$i | cut -d ":" -f 1`
			#losetup -d $lodev
		#done
		;;
	restart) 
		$0 stop
		$0 start
		;;
    	*)
        	## If no parameters are given, print which are avaiable.
	        echo "Usage: $0 {start|stop|restart}"
        	exit 1
        	;;
esac

exit 0
