#!/bin/bash
################################################################################
# Filename: ./src/base/bin/qrm-filesystem-image
# 
# The contents of this file are subject to the Qlusters Public License
# Version 1.1 (the License); you may not use this file except in compliance
# with the License.
# You may obtain a copy of the License at
# http://www.openqrm.org/content/view/33/69/.
# 
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
# 
# The Original Code is openQRM.
# 
# The Initial Developer of the Original Code is Qlusters Corporation. Portions
# created by Qlusters Corporation are Copyright (C) 2003-2005. All Rights
# Reserved.
# 
# Contributor(s):
# 
# Description:
# 
# Comments:
################################################################################
# Qrm filesystem-image script

QRM_SERVER_BASE_DIR=${QRM_SERVER_BASE_DIR:-`readlink /etc/init.d/qrm-server | sed -e "s#/qrm/etc/init.d/qrm-server##g"`}
QRM_FILESYSTEM_IMAGE_LOCATION=/
COMMON_DIRS="bin etc lib usr sbin"
QRM_KEEP_NETWORKING=0
PRIVATE_LIST_BASIC="/var /tmp"
PRIVATE_LIST_EXCLUDES_DEFAULT="/var/lib/rpm"

# include common Qrm functions
. $QRM_SERVER_BASE_DIR/qrm/include/qrm-functions
. $QRM_SERVER_BASE_DIR/qrm/include/qrm-server-functions
qrm_get_server_config 1>/dev/null


function usage() {
	echo "Usage $0 <create/remove/validate>"
	echo
	echo "      $0 create"
	echo "                   -s/--filesystem-image <image-name>"
	echo "                   -i/--ip <ip-address-of-source-system>"
	echo "                   -n/--nfs-storage <ip-address:path-to-images>"
	echo "                   --storage-server <storage-server-name>"
	echo "                   [-l/--location <rootfs-location>]"
	echo "                   [--private-exclude <private-excludes>]"
	echo "                   [--private-add <private-adds>]"
	echo "                   [-e/--exclude <exclude-directory>]"
	echo "                   [-a/--arch <Opteron|Any|Xeon|i686>]"
	echo "                   [--keep-services]"
	echo "                   [--remove-services]"
	echo "                   [--keep-network]"
	echo "                   [--remove-network]"
	echo "                   [--hostname <hostname>]"
	echo "                   [-o/--only-physical]"
	echo
	echo "      $0 remove"
	echo "                   -s/--filesystem-image <image-name>"
	echo "                   -n/--nfs-storage <ip-address:path-to-images>"
	echo 
	echo "      $0 validate"
	echo "                   -s/--filesystem-image <image-name>"
	echo "                   -n/--nfs-storage <ip-address:path-to-images>"
	echo "                   [-i/--ip <ip-address-of-source-system>]"
	echo "                   [-l/--location <rootfs-location>]"
	echo "                   [-f/--fix]"
	echo "                   [--keep-services]"
	echo "                   [--remove-services]"
	echo "                   [--keep-network]"
	echo "                   [--remove-network]"
	echo "                   [--hostname <hostname>]"
	echo 
}


function qrm_check_filesystem_image_content() {
	local filesystem_image_dir=$1
	for DIR in `echo $COMMON_DIRS`; do
		if [ ! -d $filesystem_image_dir/$QRM_FILESYSTEM_IMAGE_NAME/$DIR ]; then
			return 1
		fi
	done
	return 0
}


# function qrm_prepare_private : creates private configuration file and placed
# it into private directory on image. linuxrc will then perform apropriate
# mounts according to this data
function qrm_prepare_private() {
	local root=$1;shift
	local excludes="$1";shift
	local additions="$1"; shift

	#Setting the default values we always want to use
	if [[ ! -z "$QRM_NODES_LOG_DIR" && "$QRM_NODES_LOG_DIR" != "syslog" ]]; then
		local already_there=
		for dir in $PRIVATE_LIST_BASIC; do # not going over $additions to have right perms
			if [ -z "${QRM_NODES_LOG_DIR##$dir*}" ]; then
				already_there=1
			fi
		done
		if [ -z "$already_there" ]; then
			PRIVATE_LIST_BASIC="$PRIVATE_LIST_BASIC $QRM_NODES_LOG_DIR"	
		fi
		
	fi
	

	#Testing for duplicated enteries in default conf and user provided
	excludes=$(echo "$PRIVATE_LIST_EXCLUDES_DEFAULT ${excludes[*]}" | tr ' ' '\n' | sort -u | tr '\n' ' ') 
	#Now for each directory we want to make private we need to determine
	#its mode for future mount 
	local add_conf
	for dir in $additions; do
                local mode=755
                if [ -d ${root}/${dir} ]; then
                        mode=`/usr/bin/stat ${root}/${dir} | grep Uid | awk '{print $2}' | sed s'/[a-zA-Z\/\(\)-]//g'`
                fi
                add_conf="$add_conf $dir|0:0|$mode"
        done


	if [ ! -d $root/custom ]; then
		mkdir -p $root/custom/node $root/custom/ve
	fi
	if [ ! -d $root/private ]; then
		mkdir $root/private
	fi

	echo "private_list_basic=\"$PRIVATE_LIST_BASIC\""		>$root/private/shared.conf
	echo "private_list_additional=\"$add_conf\""			>> $root/private/shared.conf
	echo "private_list_excludes=\"$excludes\""			>> $root/private/shared.conf

}


# creates an filesystem-image from a running server
function qrm_filesystem_image_create() {
	if ! qrm_validate_input "$QRM_FILESYSTEM_IMAGE_NAME"; then
		usage
		return 1
	fi
	echo "Creating filesystem-image $QRM_FILESYSTEM_IMAGE_NAME from $QRM_SOURCE_SYSTEM_IP_ADDRESS"
	# mount storage
	echo "Mounting nfs-storage $QRM_NFS_SERVER_STORAGE"
	export QRM_FILESYSTEM_IMAGE_STORAGE=`mktemp -q -d $QRM_TEMP/XXXXXX`
	export QRM_FILESYSTEM_IMAGE_ROOT_FS="$QRM_FILESYSTEM_IMAGE_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME"
	if ! mount -t nfs $QRM_NFS_SERVER_STORAGE $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "ERROR: Could not mount nfs-storage $QRM_NFS_SERVER_STORAGE"
		return 1		
	fi
	
	if qrm_check_filesystem_image_content $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "WARNING: It seems the filesystem $QRM_FILESYSTEM_IMAGE_NAME is already existing on the storage-server!"
		echo
		echo -n "Do you want to update/overwrite the filesystem on $QRM_NFS_SERVER_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME ? (y/n)"
		read CONFIRM
		if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
			echo "WARNING: Filesystem creation canceled."
			umount $QRM_FILESYSTEM_IMAGE_STORAGE
			exit 1
		fi
	fi

	# Prepare exclude list
	for i in ${QRM_USER_EXCLUDE_LIST[*]}; do
		exclude_list="${exclude_list[*]} --exclude $i"
	done
	# exclude the automounts
	exclude_list="${exclude_list[*]} --exclude /media/cdrom --exclude /media/cdrom1 --exclude /media/floppy"

	# copy
	echo "Transfering the image content from $QRM_SOURCE_SYSTEM_IP_ADDRESS:/$QRM_ROOTFS_LOCATION"
	echo "(this procedure may take time)"
	
	mkdir -p $QRM_FILESYSTEM_IMAGE_ROOT_FS
	PROGRESS=`mktemp -q $QRM_TEMP/XXXXXX`
	touch $PROGRESS
	tail -F $PROGRESS | while read LINE; do	\
		if [ "$loop" == 1000 ]; then	\
			echo -n ".";	\
			loop=0;	\
		fi;		\
		loop=$(( loop +1 ));	\
	done &
	TAIL_PID=`ps ax | grep "tail -F $PROGRESS" | grep -v grep | awk {' print $1 '}`
	if ! nice -n 19 $QRM_SERVER_BASE_DIR/qrm/bin/rsync -aHvS --numeric-ids --rsh=ssh --exclude /proc --exclude /sys --exclude /sysfs --exclude $QRM_FILESYSTEM_IMAGE_STORAGE $exclude_list root@$QRM_SOURCE_SYSTEM_IP_ADDRESS:/$QRM_ROOTFS_LOCATION $QRM_FILESYSTEM_IMAGE_ROOT_FS/ 1>$PROGRESS; then
		echo
		echo "ERROR: Could not transfer the filesystem-image content"
		umount $QRM_FILESYSTEM_IMAGE_STORAGE
		kill $TAIL_PID 1>/dev/null 2>&1
		/bin/rm -f $PROGRESS
		return 1
	fi
	kill $TAIL_PID 1>/dev/null 2>&1
	/bin/rm -f $PROGRESS
	echo


	if ! qrm_check_filesystem_image_content $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "ERROR: Could not find common directories for a linux filesystem."
		echo "       Please check the filesystem-image content on the storage-server"
		umount $QRM_FILESYSTEM_IMAGE_STORAGE
		return 1
	else
		echo "Tranfer of the filesystem-image completed. Now preparing the image"
	fi
	
	# prepare
	if ! qrm_filesystem_image_prepare; then
		echo "ERROR: System-image preparation failed"
		umount $QRM_FILESYSTEM_IMAGE_STORAGE
		return 1
	fi
	
	# umount storage
	umount $QRM_FILESYSTEM_IMAGE_STORAGE
}



# configures the filesystem-image services
function qrm_filesystem_image_configure_services() {
	DISTRIBUTION=`get_linux_distribution`
	if [ -f "$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/$DISTRIBUTION" ]; then
		DISTRIBUTION_SPECIFIC_FUNCTIONS=$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/$DISTRIBUTION
	else
		DISTRIBUTION_SPECIFIC_FUNCTIONS=$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/generic
	fi
	. $DISTRIBUTION_SPECIFIC_FUNCTIONS
	echo "starting service configuration"
	if [ "$QRM_KEEP_SERVICES" == "0" ]; then
		echo "Applying default base-services configuration"
		ALLSERVICES=`_services_list | awk {' print $1 '} | grep -v : | grep -v qrm`
		mkdir -p $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/
		echo ". $QRM_SERVER_BASE_DIR/qrm/include/qrm-functions" >> $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/services-backup.conf
		echo ". $DISTRIBUTION_SPECIFIC_FUNCTIONS" >> $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/services-backup.conf
		for SERVICE in $ALLSERVICES; do
			if ! _image_base_services | grep $SERVICE 1>/dev/null; then
				# switch off
				_services_disable $SERVICE
				# backup
				echo "_services_enable $SERVICE" >> $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/services-backup.conf
			fi
		done
		chmod +x $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/services-backup.conf
		echo "Configured the filesystem-image with the base-services"
		echo "Original service configuration for $QRM_FILESYSTEM_IMAGE_NAME backed up in $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/"
	else
		echo "Staying with the current service configuration"
	fi

	if typeset -f __mandatory_image_services__ > /dev/null ; then
		echo "Setting mandatory services"
		for SERVICE in $(__mandatory_image_services__); do
			if ! _services_enable ${SERVICE}; then 
				echo "Failed to enable mandatory service ${SERVICE}"
				exit 1
			fi
		done
	fi	
	
	# remove the qrm-server service in any way from the filesystem-image
	_services_remove qrm-server 1>/dev/null 2>&1
	return 0
}


# configures the filesystem-image network
function qrm_filesystem_image_configure_network() {
	DISTRIBUTION=`get_linux_distribution`
	if [ -f "$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/$DISTRIBUTION" ]; then
		DISTRIBUTION_SPECIFIC_FUNCTIONS=$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/$DISTRIBUTION
	else
		DISTRIBUTION_SPECIFIC_FUNCTIONS=$QRM_SERVER_BASE_DIR/qrm/include/dist_specific.d/generic
	fi
	. $DISTRIBUTION_SPECIFIC_FUNCTIONS

	if [ "$QRM_KEEP_NETWORKING" == "0" ]; then
		echo "Removing current network interface configuration"
		mkdir -p $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/
	 	for INTERFACECONF in `_image_list_network_interfaces`; do
			INTERFACE=`echo $INTERFACECONF | sed -e "s/\/.*ifcfg-//"`
			echo "Removing configuration for $INTERFACE (backed up in $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/)"
			/bin/mv $INTERFACECONF $QRM_SERVER_LOG_DIR/backup/$QRM_FILESYSTEM_IMAGE_NAME/
		done
	else
		echo "Keeping network configuration for filesystem-image $QRM_FILESYSTEM_IMAGE_NAME"
	fi
	if [ ! -z "$QRM_FILESYSTEM_IMAGE_HOSTNAME" ]; then
		echo "Setting hostname to $QRM_FILESYSTEM_IMAGE_HOSTNAME for filesystem-image $QRM_FILESYSTEM_IMAGE_NAME"
		_image_set_hostname
	fi
	return 0
}


function qrm_filesystem_image_fix_devices() {
	local tmpdist=${QRM_FILESYSTEM_IMAGE_ROOT_FS}
	QRM_FILESYSTEM_IMAGE_ROOT_FS=/
	local distribution=$(get_linux_distribution)
	QRM_FILESYSTEM_IMAGE_ROOT_FS=${tmpdist}

	case ${distribution} in
		# dev fix need only on nfs clients running RHEL3.0
		"redhat_el3")
			# validate without fix wiil check if devs exists
			if [[ ${ACTION} == "validate" ]] && [[ -z "${QRM_FILESYSTEM_IMAGE_FIX}" ]]; then
				if [ -s ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar ]; then
					echo "devs found"
					return 0
				else	
					echo "devs not found"
					return 1
				fi
			fi
		
			# run only if we run validate (fix) or create image
			if [[ "${QRM_FILESYSTEM_IMAGE_FIX}" ]] || [[ ${ACTION} == "create" ]]; then
				# if we run validate (fix), we require ip and rootfs
				if [[ "${QRM_FILESYSTEM_IMAGE_FIX}" ]]; then
					if [[ -z ${QRM_SOURCE_SYSTEM_IP_ADDRESS} ]] || \
					   [[ -z ${QRM_ROOTFS_LOCATION} ]] ; then
						echo "please provide -i <source node> and -l <remote location> to update/fix /dev"
						return 1
					fi
				fi
				if [ -f ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar ]; then
					echo "dev file found"
					mv ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar \
						${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar.bck
				else
					echo "dev file not found"
				fi
				
				echo "Creating local dev file. Relogin to remote node ${QRM_SOURCE_SYSTEM_IP_ADDRESS}"
				echo "(you will be prompted for the password of root@${QRM_SOURCE_SYSTEM_IP_ADDRESS})"
				ssh root@${QRM_SOURCE_SYSTEM_IP_ADDRESS} tar -C /${QRM_ROOTFS_LOCATION} -cf - dev 2> /dev/null | \
					dd of=${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar
				if 	[[ ${PIPESTATUS[0]} -ne  0 ]] || \
					[[ ${PIPESTATUS[1]} -ne  0 ]] || \
					[[ ! -s ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar ]]; then
						echo "Error creating device file"
						rm -f ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar
						if [ -f ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar.bck ]; then
							echo "restoring old dev file"
							mv ${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar.bck \
								${QRM_FILESYSTEM_IMAGE_ROOT_FS}/private/dev.tar
						fi
						return 1
				fi
			fi
		;;
	esac
	
}


# prepares a filesystem-image
function qrm_filesystem_image_prepare() {
	if [ -z "$QRM_FILESYSTEM_IMAGE_ROOT_FS" ]; then
		echo "Usage :  export QRM_FILESYSTEM_IMAGE_ROOT_FS && qrm_filesystem_image_prepare"
		return 1
	fi
	export QRM_FILESYSTEM_IMAGE_ROOT_FS
	CURRENT=`pwd`
	# prepare the directories
	cd $QRM_FILESYSTEM_IMAGE_ROOT_FS
 	mkdir -p proc sys
	mkdir -p mnt/floppy
	mkdir -p mnt/cdrom
	mkdir -p tmp
	chmod -R 777 tmp
	chmod +t /tmp
	cd etc
	/bin/rm -f mtab qrm/easymigration.conf
	ln -sf ../proc/mounts mtab
	cd $QRM_FILESYSTEM_IMAGE_ROOT_FS
	chroot $QRM_FILESYSTEM_IMAGE_ROOT_FS chkconfig --del kudzu 1>/dev/null 2>&1
	# create private/shared dirs
	qrm_prepare_private `pwd` "$QRM_PRIVATE_EXCLUDES" "$QRM_PRIVATE_ADDITIONS"
	
	# create the excluded directories in case we want to use them as  mount points
	for dir in ${QRM_USER_EXCLUDE_LIST[*]}; do
		echo "Creating excluded directory $dir as an empty entry"
		mkdir -p ${QRM_FILESYSTEM_IMAGE_ROOT_FS}${dir}
	done
	
	# service config
	if ! qrm_filesystem_image_configure_services; then
		echo "ERROR: The service configuration on the filesystem-image failed"
		return 1
	fi
	
	# network config
	if ! qrm_filesystem_image_configure_network; then
		echo "ERROR: The network configuration on the filesystem-image failed"
		return 1
	fi

	if ! qrm_filesystem_image_fix_devices; then
		echo "ERROR: The device fix function failed"
		return 1
	fi
	
	cd $CURRENT
}





# removes a filesystem-image
function qrm_filesystem_image_remove() {
	if ! qrm_validate_input "$QRM_FILESYSTEM_IMAGE_NAME"; then
		echo "Usage : export QRM_FILESYSTEM_IMAGE_NAME=<filesystem-image-name> && qrm_filesystem_image_remove"
		return 1
	fi

	echo "Removing filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
	# mount storage
	echo "Mounting nfs-storage $QRM_NFS_SERVER_STORAGE"
	export QRM_FILESYSTEM_IMAGE_STORAGE=`mktemp -q -d $QRM_TEMP/XXXXXX`
	if ! mount -t nfs $QRM_NFS_SERVER_STORAGE $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "ERROR: Could not mount nfs-storage $QRM_NFS_SERVER_STORAGE"
		return 1		
	fi

	if [ ! -d "$QRM_FILESYSTEM_IMAGE_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME" ]; then
		echo "ERROR: The filesystem-image $QRM_FILESYSTEM_IMAGE_NAME does not exist on $QRM_NFS_SERVER_STORAGE"
		umount $QRM_FILESYSTEM_IMAGE_STORAGE
		return 1
	fi

	/bin/rm -rf $QRM_FILESYSTEM_IMAGE_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME
	umount $QRM_FILESYSTEM_IMAGE_STORAGE
}





# validates and fixes a filesystem-image
function qrm_filesystem_image_validate() {
	if ! qrm_validate_input "$QRM_FILESYSTEM_IMAGE_NAME"; then
		echo "Usage : export QRM_FILESYSTEM_IMAGE_NAME=<image-name> && qrm_filesystem_image_validate"
		return 6
	fi

	# mount storage
	echo "Mounting nfs-storage $QRM_NFS_SERVER_STORAGE"
	export QRM_FILESYSTEM_IMAGE_STORAGE=`mktemp -q -d $QRM_TEMP/XXXXXX`
	export QRM_FILESYSTEM_IMAGE_ROOT_FS="$QRM_FILESYSTEM_IMAGE_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME"
	if ! mount -t nfs $QRM_NFS_SERVER_STORAGE $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "ERROR: Could not mount nfs-storage $QRM_NFS_SERVER_STORAGE"
		return 1		
	fi

	# check it
	echo "validating filesystem image"
	if ! qrm_check_filesystem_image_content $QRM_FILESYSTEM_IMAGE_STORAGE; then
		echo "ERROR: Could not find common directories for a linux filesystem."
		echo "       Please check the filesystem-image content on the storage-server"
		umount $QRM_FILESYSTEM_IMAGE_STORAGE
		return 1
	fi


	# fix it 
	if [ "$QRM_FILESYSTEM_IMAGE_FIX" == "1" ]; then
		echo "Fixing filesystem-image $QRM_FILESYSTEM_IMAGE_NAME"
		qrm_filesystem_image_prepare
		RET=$?
	 fi
	 umount $QRM_FILESYSTEM_IMAGE_STORAGE	 
	 return $RET
}


function set_filesystm_image_log_end_time() {
	sync
	END_TIME=`date +"%m.%d.%Y_%H.%M.%S"`
	echo "$0 finished at $END_TIME" >> $1
}

# check if only sourced
if [ -z "$IS_SOURCED" ]; then

QRM_FILESYSTEM_IMAGE_LOGFILE=$QRM_SERVER_LOG_DIR/`basename $0`.log
mkdir -p $QRM_SERVER_LOG_DIR
exec 1> >(tee -a $QRM_FILESYSTEM_IMAGE_LOGFILE) 2> >(tee -a $QRM_FILESYSTEM_IMAGE_LOGFILE)
START_TIME=`date +"%m.%d.%Y_%H.%M.%S"`
echo "$0 started at $START_TIME" >> $QRM_FILESYSTEM_IMAGE_LOGFILE
trap "set_filesystm_image_log_end_time $QRM_FILESYSTEM_IMAGE_LOGFILE" SIGKILL
trap "set_filesystm_image_log_end_time $QRM_FILESYSTEM_IMAGE_LOGFILE" EXIT

export ACTION=$1
QRM_ROOTFS_LOCATION=/

# main
case "$1" in
	create)
		
		shift
		while [ $# -ne 0 ]; do
			case "$1" in
				-s | --filesystem-image)
					QRM_FILESYSTEM_IMAGE_NAME=$2
					shift
					;;
				-i | --ip)
					QRM_SOURCE_SYSTEM_IP_ADDRESS=$2
					shift
					;;
				-n | --nfs-storage)
					QRM_NFS_SERVER_STORAGE=$2
					shift
					;;
				--storage-server)
					STORAGE_SERVER_NAME=$2
					shift
					;;
				-l | --location)
					QRM_ROOTFS_LOCATION=$2/
					shift
					;;
				--private-exclude)
					QRM_PRIVATE_EXCLUDES="$QRM_PRIVATE_EXCLUDES $2"
					shift
					;;
				--private-add)
					QRM_PRIVATE_ADDITIONS="$QRM_PRIVATE_ADDITIONS $2"
					shift
					;;
				-e | --exclude)
				    if [ -z ${QRM_USER_EXCLUDE_LIST[0]} ]; then
						index=0
				    fi
				    QRM_USER_EXCLUDE_LIST[$index]=`echo $2 | sed 's/\/$//'`
				    if [ "${2:0:1}" != "/" ]; then
                                    	echo "Please use absolute paths for -e $2"
                                    	exit 1
                                    fi
				    ((index++))
				    shift
					;;
				-a | --arch)
					QRM_FILESYSTEM_IMAGE_ARCH=$2
					shift
					;;
				--remove-services)
					QRM_KEEP_SERVICES=0
					;;
				--keep-services)
					QRM_KEEP_SERVICES=1
					;;
				--remove-network)
					QRM_KEEP_NETWORKING=0
					;;
				--keep-network)
					QRM_KEEP_NETWORKING=1
					;;
				--hostname)
					QRM_FILESYSTEM_IMAGE_HOSTNAME=$2
					shift
					;;
				-o | --only-physical)
					QRM_ONLY_PHYSICAL=true
					;;
				-h | --help)
					usage
					exit 0
					;;
				*)
					echo "Invalid option $1"
					usage
					exit 1
					;;
			esac
			shift
		done
		if [ -z "$QRM_FILESYSTEM_IMAGE_ARCH" ];then
			QRM_FILESYSTEM_IMAGE_ARCH=i686
		fi
		if [ -z "$QRM_FILESYSTEM_IMAGE_NAME" ] || [ -z "$QRM_SOURCE_SYSTEM_IP_ADDRESS" ] || [ -z "$QRM_NFS_SERVER_STORAGE" ] || [ -z "$STORAGE_SERVER_NAME" ]; then
			usage
		else
			echo
			echo "The next step will create a Qrm-image from the system $QRM_SOURCE_SYSTEM_IP_ADDRESS"
			echo "(you will be prompted for the password of root@$QRM_SOURCE_SYSTEM_IP_ADDRESS)"
			echo "Press <ENTER> to continue"
			read
			if qrm_filesystem_image_create; then
				RET=0
				if [ -z "$QRM_ONLY_PHYSICAL" ]; then
					TARGET_LOCATION=`echo $QRM_NFS_SERVER_STORAGE |cut -d : -f2`
					$QRM_SERVER_BASE_DIR/qrm/bin/qrm-cli filesystem add -n $QRM_FILESYSTEM_IMAGE_NAME -s $STORAGE_SERVER_NAME -i $TARGET_LOCATION/$QRM_FILESYSTEM_IMAGE_NAME -a $QRM_FILESYSTEM_IMAGE_ARCH
					RET=$?
				fi
				# check return code
				case "$RET" in
					0)
						echo "Successfully created the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
						;;
					6)
						echo "Successfully created the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
						echo "but could not create the filesystem's meta data."
						;;
					7)
						echo "Successfully created the filesystem image $QRM_FILESYSTEM_IMAGE_NAME but could"
						echo "not add it to the QRM-server database because it already exists."
						;;
					*)
						echo "ERROR: Could not create the filesystem image $QRM_FILESYSTEM_IMAGE_NAME. Error code is $RET"
				esac
				exit $RET
			else
				echo "ERROR: Could not create the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
				exit 1
			fi
		fi
		;;

	remove)
		shift
		while [ $# -ne 0 ]; do
			case "$1" in
				-s | --filesystem-image)
					QRM_FILESYSTEM_IMAGE_NAME=$2
					shift
					;;
				-n | --nfs-storage)
					QRM_NFS_SERVER_STORAGE=$2
					shift
					;;
				-h | --help)
					usage
					exit 0
					;;
				*)
					echo "Invalid option $1"
					usage
					exit 1
					;;					
			esac
			shift
		done
		if [ -z "$QRM_FILESYSTEM_IMAGE_NAME" ]; then
			usage
			exit 1
		else
			echo "The next step will remove/delete the filesystem-image at $QRM_NFS_SERVER_STORAGE/$QRM_FILESYSTEM_IMAGE_NAME"
			echo "Please press <ENTER> to continue (CTRL-C for cancel)"
			read
			if qrm_filesystem_image_remove; then
				$QRM_SERVER_BASE_DIR/qrm/bin/qrm-cli filesystem delete -n $QRM_FILESYSTEM_IMAGE_NAME
				RET=$?
				# check return code
				case "$RET" in
					0)
						echo "Successfully removed the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
						;;
					6)
						echo "Successfully removed the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
						echo "but could not remove the filesystem's meta data."
						;;
					8)
						echo "Successfully removed the filesystem image $QRM_FILESYSTEM_IMAGE_NAME but could"
						echo "not remove it to the QRM-server database because it is in use."
						;;
					*)
						echo "ERROR: Could not remove the filesystem image $QRM_FILESYSTEM_IMAGE_NAME. Error code is $RET"
				esac
				exit $RET
			else
				echo "ERROR: Could not remove the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
				exit 1
			fi
		fi
		;;

	validate)
		shift
		while [ $# -ne 0 ]; do
			case "$1" in
				-s | --filesystem-image)
					QRM_FILESYSTEM_IMAGE_NAME=$2
					shift
					;;
				-f | --fix)
					QRM_FILESYSTEM_IMAGE_FIX=1
					;;
				-n | --nfs-storage)
					QRM_NFS_SERVER_STORAGE=$2
					shift
					;;
				-i | --ip)
					QRM_SOURCE_SYSTEM_IP_ADDRESS=$2
					shift
					;;
				-l | --location)
					QRM_ROOTFS_LOCATION=$2/
					shift
					;;
				--remove-services)
					QRM_KEEP_SERVICES=0
					;;
				--keep-services)
					QRM_KEEP_SERVICES=1
					;;
				--remove-network)
					QRM_KEEP_NETWORKING=0
					;;
				--keep-network)
					QRM_KEEP_NETWORKING=1
					;;
				--hostname)
					QRM_FILESYSTEM_IMAGE_HOSTNAME=$2
					shift
					;;
				-h | --help)
					usage
					exit 0
					;;
				*)
					echo "Invalid option $1"
					usage
					exit 1
					;;					
			esac
			shift
		done
		if [ -z "$QRM_FILESYSTEM_IMAGE_NAME" ] || [ -z "$QRM_NFS_SERVER_STORAGE" ]; then
			usage
			exit 1
		else
			if qrm_filesystem_image_validate; then
				echo "Successfully validated the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"			
			else
				echo "ERROR: Could not validate the filesystem image $QRM_FILESYSTEM_IMAGE_NAME"
				exit 1
			fi
		fi
		;;

	'' | -h | --help)
		usage
		exit 0
		;;
	
	*)
		echo "Invalid option $1"
		usage
		exit 1
esac

fi

