#!/bin/bash
################################################################################
# Filename: ./src/base/bin/easymigration/qrm-configure-node-monitor
# 
# 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-configure-node-monitor                                              ##
##                                                                          ##
##  configures a server for phase 1 (easymigration)                         ##
##                                                                          ##
##                                                                          ##
### ====================================================================== ###

######################### VARIABLE PART #################################
export QRM_NODES_BASE_DIR=${QRM_NODES_BASE_DIR:-"/usr"}
export QRM_NODES_LOG_DIR=${QRM_NODES_LOG_DIR:-$QRM_NODES_BASE_DIR/qrm/logs}
CUR_DIR=`dirname $0`
QRM_CLI=$CUR_DIR/qrm-cli
QRM_CONF_DIR=/etc/qrm
QRM_CONF_FILE=${QRM_CONF_DIR}/easymigration.conf
QRM_NODES_PARAMETER="/var/qrm/conf/node-parameter.conf"
WGET=/usr/bin/wget
FORCE=0
export PORT=8080
SEND_REMOVE_EVENT=0
MODE=local

# check requirements
REQUIRED_FILES="qrm-cli qrm-runlevel qrm-functions qrm-nodes-functions"
for RFILE in $REQUIRED_FILES; do
	if [ ! -f $CUR_DIR/$RFILE ]; then
		echo "ERROR: Missing required easymigration file $CUR_DIR/$RFILE."
		exit 1
	fi
done

# source function files
. $CUR_DIR/qrm-functions
. $CUR_DIR/qrm-nodes-functions

######################### FUNCTIONAL PART ###############################

function usage() {
	echo "Usage :"
	echo
	echo "$0        -o/--config-option <install-node>"
	echo "                                    -q/--qrm-server-ip <qrm-ip>"
	echo "                                    -n/--network-card <interface-name>"
	echo "                                    -i/--ip <reserved ip>"
	echo "                                    [-v/--virtual-environment-name <name>] or [-p/--part_tech <partition tech.>]"
	echo "                                    [-h/--help]"
	echo
	echo "$0        -o/--config-option <install-partition>"
	echo "                                    -q/--qrm-server-ip <qrm-ip>"
	echo "                                    -n/--network-card <interface-name>"
	echo "                                    -i/--ip <reserved ip>"
	echo "                                    -e/--node-ext-id <hosting node external id>"
	echo "                                    -v/--virtual-environment-name <name> "
	echo "                                    [-h/--help]"
	echo
	echo "$0        -o/--config-option <uninstall>"
	echo "                                    -q/--qrm-server-ip <qrm-ip>"
	echo "                                    [-f/--force]"
	echo "                                    [-h/--help]"
	echo	
	echo "$0        [-h/--help]"
	echo
}


function start_log() {
	mkdir -p $QRM_NODES_LOG_DIR
	local QRM_EASYMIGRATION_LOGFILE=$QRM_NODES_LOG_DIR/qrm-easymigration.log
	exec 2> >(tee -a $QRM_EASYMIGRATION_LOGFILE 1>&2) 1> >(tee -a $QRM_EASYMIGRATION_LOGFILE)
	echo "$(basename $0) started at $(date +"%m.%d.%Y_%H.%M.%S"). Logging to $QRM_EASYMIGRATION_LOGFILE"
}


###########################################################
# function qmessg()                                         #
# parameter 1 : QRM-script which executed qmessg            #
# parameter 2 : text to log                               #
# logic : puts text to log in common QRM-logfile          #
###########################################################
function qmessg() {
	if (( $# != 2 )); then
		echo "USAGE: qmessg notice/warning/error <text-to-log>"
		return 6
	fi
	IMPORTANCE=$1
	TXT2LOG=$2

	case "$IMPORTANCE" in
		notice)
			MSGSTATE="NOTICE"
			tput setf 2
			echo -en "NOTICE  : "
			tput op
			echo "$TXT2LOG"
			;;
		warning)
			MSGSTATE="WARNING"
			tput setf 6
			echo -en "WARNING : "
			tput op
			echo "$TXT2LOG"
			;;
		error)
			MSGSTATE="ERROR"
			tput setf 4
			echo -en "ERROR   : "
			tput op
			echo "$TXT2LOG"
			;;

		*)
			echo "USAGE: qmessg notice/warning/error/log <text-to-log>"
			return 6
	esac 
	return 0
}



##########################################################
#detecting our boot device                               #
##########################################################
function qrm_find-bootdev() {
	mount | grep -w "on /" | awk {' print $1 '}
}

##########################################################
#detecting our boot file system                          #
##########################################################
function qrm_find-bootfs() {
	mount | grep -w "on /" | sed -e "s/.*type//" | awk {' print $1 '}
}

##########################################################
#detecting our boot file system                          #
##########################################################
function qrm_find-mac() {
	ifconfig $CS_NIC | grep -w $CS_NIC | awk {' print $5 '}
}

##########################################################
# Testing whether we can communicate through interface   #
# provided by user                                       #
##########################################################
function test_qrm_interface() {

	QRM_INTERFACE=""
	#Testing whether we have such interface
	NICS="`ifconfig -a|grep eth|cut -f1 -d ' '`"
	for INTERFACE in $NICS; do
		if [ "$CS_NIC" == "$INTERFACE" ]; then
			#Bringing up virtual interface we will use 
			#for installation and testing connection
			/sbin/ifconfig ${INTERFACE}:qrm down 1>/dev/null 2>&1
			/sbin/ifconfig ${INTERFACE}:qrm $CS_IP up 1>/dev/null 2>&1
			if /sbin/arping  -w 0 -c 4 -I $INTERFACE $QRM_SERVER_IP 2>&1 | grep reply 2>&1 >/dev/null; then
				QRM_INTERFACE=$INTERFACE
				break
			else
				#We have interface but can not communicate through it
				#than remove it
				/sbin/ifconfig ${INTERFACE}:qrm down 1>/dev/null 2>&1
			fi
		fi
	done
	echo "$QRM_INTERFACE"
}


####################################################################
#Trying to find network card through which can communicate with qrm#
####################################################################
function qrm_find-networkcard() {
    QRM_INTERFACE=""
    NICS="`ifconfig -a|grep eth|cut -f1 -d ' '`"
    if ! echo "$NICS" | grep . 1>/dev/null 2>&1; then
		echo No network cards found
		exit 6
    fi
    NODEINTERFACE=""
    for INTERFACE in $NICS; do
		/sbin/ifconfig ${INTERFACE}:qrm down 1>/dev/null 2>&1
		/sbin/ifconfig ${INTERFACE}:qrm $CS_IP up 1>/dev/null 2>&1
		if /sbin/arping  -w 0 -c 4 -I ${INTERFACE}:qrm $QRM_SERVER_IP 2>&1 | grep reply 2>&1 >/dev/null; then
		    QRM_INTERFACE=$INTERFACE
		    break
		fi
		/sbin/ifconfig ${INTERFACE}:qrm down 1>/dev/null 2>&1
	done
	echo "$QRM_INTERFACE"
}


################################################################
# detecting what ip we are using. For this purpose we can use  #
################################################################
function qrm_get-boot-ip() {
	if [ "$QRM_BOOT_IP" == "" ]; then 
		IPADDR=`ifconfig | grep -A 1 -w eth.*:qrm | grep -v eth.*qrm | cut -d':' -f 2 | awk {' print $1 '} | head -n1`
		echo "$IPADDR"
	else
		echo $QRM_BOOT_IP
	fi
}

################################################################
# Trying to detect interface the right interface               #
################################################################
function qrm_get-boot-interface() {

	while (true); do 
		if [ ! -z $CS_NIC ]; then
			QINT=$CS_NIC
			break
		fi
		if [ ! -z $QRM_INTERFACE ]; then
			QINT=$QRM_INTERFACE
			break
		fi
		if [ "$FORCE" != 1 ]; then
			QINT=`qrm_find-networkcard`
			if [ ! -z $QINT ]; then
				break
			fi
		fi
		QINT=`ifconfig | grep ":qrm " | awk {' print $1 '} | cut -d':' -f 1`
		if [ ! -z $QINT ]; then
			break
		fi
		break

	done
	echo "$QINT"
}

############################################################
#Sending new node even to QRM server                       #
############################################################
function qrm_send-new-node-event() {
	mkdir -p `dirname $QRM_NODES_PARAMETER`
	FAILED_TO_SEND=""
	if [ ! -z $QRMV_VE_NAME ]; then	
		VE_NAME_ARG="-v $QRMV_VE_NAME"
	fi
	if [  ! -z $PART_TECH ]; then
		PART_TECH_ARG="-p $PART_TECH"
	fi
	
	if [ $OPTION == "install-node" ] ; then 
		MIGRATION_TYPE="new-node"
	fi
	if [ $OPTION == "install-partition" ] ; then 
		MIGRATION_TYPE="new-partition"
#   CS_IDENT_ARG - id of node owner of vm		
		CS_IDENT_ARG=" -n $NODE_EXT_ID ";
	fi
	
	CLI_ARGS="-q $QRM_SERVER_IP easy-migration $MIGRATION_TYPE -i $CS_IP -m  $CS_MAC_ADDRESS -b $CS_BOOT_FS://127.0.0.1/$CS_BOOT_DEV $PART_TECH_ARG  $VE_NAME_ARG $CS_IDENT_ARG"
#	echo $CLI_ARGS
	if ! $QRM_CLI $CLI_ARGS  > $QRM_NODES_PARAMETER; then
		qmessg error "Could not send event to the QRM-server. Qrm-cli failed."
		exit 1
	fi
}

############################################################
# We failed to install. Cleaning up the leftovers          #
############################################################
function uninstall_node_monitor() {
	local level=$1
	qmessg notice "Cleaning up after failed installation"
	qrm_uninstall_failed_installation $level
	qmessg notice "Finished cleaning up after failed installation"
}

##################################################################
#Creating here configuration file we will store qrm configuration#
#data                                                            #
##################################################################
function qrm_create-config-file() {
	#Creating qrm parameter directory
	if [ ! -d $QRM_CONF_DIR ]; then
		qmessg notice "Creating $QRM_CONF_DIR"
		mkdir -p $QRM_CONF_DIR
	fi
	#Loading data into configuration file
	echo "QRM_SERVER_IP=$QRM_SERVER_IP"                     >  $QRM_CONF_FILE
	echo "QRM_CS_ID=$CS_ID"                     >> $QRM_CONF_FILE
	echo "QRM_CS_IP=$CS_IP"                      >> $QRM_CONF_FILE
	echo "QRM_CS_NIC=$CS_NIC"                  >> $QRM_CONF_FILE
	echo "QRM_CS_SUBNET=$QRM_SERVER_SUBNET_MASK"          >> $QRM_CONF_FILE
	echo "QRM_CS_BROADCAST=$QRM_SERVER_BROADCAST_ADDRESS" >> $QRM_CONF_FILE
	echo "QRM_NODES_BASE_DIR=$QRM_NODES_BASE_DIR"             >> $QRM_CONF_FILE
	echo "QRM_CS_MAC_ADDRESS=$CS_MAC_ADDRESS"		  >> $QRM_CONF_FILE
	echo "VE_ID=$VE_ID"                           >> $QRM_CONF_FILE
	echo "MODE=$MODE"                             >> $QRM_CONF_FILE
}
    

###############################################################
# sending remove node event to qrm                            # 
###############################################################
function qrm_send-remove-node-event() {
	LOOP=0
	if [ -z $QRM_BOOT_IP ]; then
		QRM_BOOT_IP=$CS_IP
	fi

	if ! $QRM_CLI easy-migration remove-node -i $QRM_BOOT_IP; then
		qmessg error "Could not send event to the QRM-server. Qrm-cli failed."
		exit 1
	fi
}


##############################################################
#Stopping qrm interface                                      #
##############################################################
function qrm_shutdown-boot-interface() {
    sleep 1
    if [ "$MODE" == "local" ]; then
		qmessg notice "Local run detected !!! Remove $QRM_NODES_BASE_DIR/qrm directory Y/N ?"
		read opt
		if [ "$opt" == "y" ]; then
			echo -n "Removing /etc/qrm now "
			rm -Rf $QRM_NODES_BASE_DIR/qrm/* &
			PID=$!
			while ps -p $PID 1>/dev/null 2>&1; do
				sleep 1
				echo -n "."
			done
			echo " ... DONE"
		else
			echo "$QRM_NODES_BASE_DIR/qrm directory will be left unchanged"
		fi
	else
		#Before unmounting we want to make sure that there is no ps
		#locking the mount point
		if [ -f /usr/sbin/lsof ]; then
			res=(`/usr/sbin/lsof $QRM_NODES_BASE_DIR/qrm/ | awk '/[0-9].*/ {print $2}'`)
			if [ "$res" != "" ]; then
				qmessg warning "The processes $res are seems to be running on $QRM_NODES_BASE_DIR/qrm/ directory !!!"
				qmessg warning "Will try to perform [ umount -l ] but it will be better if you will kill this processes first !!!"
				qmessg warning "Press ENTER to continue : "
				read
			fi
		fi
		if ! umount -l $QRM_NODES_BASE_DIR/qrm/ 1>/dev/null 2>&1; then
			if [ "$FORCE" != "1" ]; then
				qmessg error "Could not umount $QRM_NODES_BASE_DIR/qrm/"
				return 2
			else
				qmessg notice "Emergency uninstall : unmounting $QRM_NODES_BASE_DIR/qrm - not mounted"
			fi
		fi
	fi
	sleep 1
    
	#Bringing interface down
	if ! ifconfig ${QRM_INTERFACE}:qrm down 1>/dev/null 2>&1; then
		qmessg warning "Could not bring down interface ${QRM_INTERFACE}:qrm"
		if [ "$FORCE" != "1" ]; then
			qmessg error "Could not bring down interface ${QRM_INTERFACE}:qrm"
			return 2
		else
			qmessg notice "Emergency uninstall : bringing down interface $QRM_INTERFACE:qrm - already down"
		fi
	fi
	return 0
}

############################################################
#Copy $QRM_NODES_BASE_DIR/qrm data localy                            #
############################################################
function qrm_make_local() {

	# prepare basedir
	mkdir -p $QRM_NODES_BASE_DIR/qrm/include $QRM_NODES_BASE_DIR/qrm/sbin
	/bin/cp -f qrm-functions qrm-nodes-functions $QRM_NODES_BASE_DIR/qrm/include/
	/bin/cp -f qrm-runlevel $QRM_NODES_BASE_DIR/qrm/sbin/

	# add qrm to inittab
	cp -f /etc/inittab /etc/inittab.org
	if grep -q ^qrm /etc/inittab; then
		TMP_FILE=`mktemp -q /tmp/XXXXXX`
		cat /etc/inittab | sed -e "s#^qrm.*#qrm:123456:once:$QRM_NODES_BASE_DIR/qrm/sbin/qrm-runlevel#g" > $TMP_FILE
		mv $TMP_FILE /etc/inittab
	else
		echo "qrm:123456:once:$QRM_NODES_BASE_DIR/qrm/sbin/qrm-runlevel" >> /etc/inittab
	fi

	# start the nodes-services
	cd $QRM_NODES_BASE_DIR/qrm/
	run_services 3
	cd -

	# link the qrm init script
	ln -sf $QRM_NODES_BASE_DIR/qrm/etc/init.d/qrm /etc/init.d/qrm
	qrm_chkconfig add qrm
	return $?

}

#################################################################
#Installing qrm-monitor on client                               #
#################################################################
function qrm_install_node_monitor() {
 
	################################
	#STEP 0: Initialisations

	#setting default operation mode
	if [ "$MODE" != "local" ]; then
		if [ "$MODE" != "nfs" ]; then
			qmessg notice "Unknown mode - $MODE. The default nfs mode will be used instead"
		fi
		MODE="nfs"
	fi

	############################################
	#STEP I : testing user provided input
	#Testing input for missing parameters
	if [ -z "$QRM_SERVER_IP" ] || [ -z "$CS_IP" ] || [ -z "$CS_NIC" ] || [ -z "$OPTION" ]; then
		qmessg error "Missing parameter in commandline"
		usage
		exit 6
	fi

	if [ "$OPTION" == "install-node" ]; then
		if [ -z "$QRMV_VE_NAME" ] && [ -z "$PART_TECH" ]; then
			qmessg error "Parameter -v or -p is missing."
			usage
			exit 6		
		fi
	elif [ "$OPTION" == "install-partition" ]; then
		if [ -z "$QRMV_VE_NAME" ] || [ -z "$NODE_EXT_ID" ]; then
			qmessg error "Parameter -v or -e is missing (both are needed to install a partition)."
			usage
			exit 6		
		fi
	fi


	#Testing previuos instances of qrm-infod
	if ps -C qrm-infod 1>/dev/null 2>&1; then
		qmessg error "This system is already integrated into QRM!"
		qmessg error "Please remove first before re-integrating"
		exit 6
	fi
 
	#Testing for ip conflict
	if ping -c 1 -w 1 $CS_IP 1>/dev/null 2>&1; then
		qmessg error "$CS_IP is already active in the QRM-network!"
		qmessg error "Please choose a free/unused ip-address for QRM-integration"
		exit 6
	fi

	#Testing for QRM ip to be of the right format
	if ! qrm_validate_ipaddress $QRM_SERVER_IP; then
		qmessg error "$QRM_SERVER_IP is not a valid QRM-server ip-address!"
		exit 6
	fi

	#Testing for NODE ip to be of the right format
	if ! qrm_validate_ipaddress $CS_IP; then
		qmessg error "$CS_IP is not a valid node ip-address!"
		exit 6
	fi

	qmessg notice "Gathering configuration parameters"
	#We test if we can communicate with qrm upon the user provided 
	#interace
	CS_NIC=`test_qrm_interface`
	if [ -z "$CS_NIC" ]; then
		qmessg error "Could not get a connection to the QRM-server $QRM_SERVER_IP"
		exit 4
	fi

	# Looking for our boot device
	CS_BOOT_DEV=`qrm_find-bootdev`
	if [ -z "$CS_BOOT_DEV" ]; then
		qmessg error "Could not find the bootdevice"
		exit 4
	fi

	# Looking for our boot file system
	CS_BOOT_FS=`qrm_find-bootfs`
	if [ -z "$CS_BOOT_FS" ]; then
		qmessg error "Could not get the bootdevice filesystem-type"
		exit 4
	fi

	# Looking for our mac address
	CS_MAC_ADDRESS=`qrm_find-mac`
	if [ -z "$CS_MAC_ADDRESS" ]; then
		qmessg error "Could not find the mac-address for network interface $CS_NIC"
		exit 4
	fi

	qmessg notice "Found the following configuration parameters"
	echo
	echo "  Network interface to connect to the QRM-server   : $CS_NIC"
	echo "  MAC address of the network interface             : $CS_MAC_ADDRESS"
	echo "  Boot device                                      : $CS_BOOT_DEV"
	echo "  Filesystem type of the boot device               : $CS_BOOT_FS"
	echo "  QRM run mode                                     : $MODE"
	echo 
	qmessg notice "Press <ENTER> to go on"
	read

	##########################################################
	#STEP II: Send new node event

	#Sending to qrm event about new node
	qmessg notice "Sending new-node event to the QRM-server"
	level=1
	if qrm_send-new-node-event; then
		qmessg notice "New-node event sent successfully"
	else
		qmessg error "QRM server reported an error : $msg"
		/sbin/ifconfig $CS_NIC:qrm down
		uninstall_node_monitor $level
		exit 2
	fi
	
	###########################################################
	#STEP III: loading node parameters. The node param file should 
	#already be loaded to the system as a result of previous step     

	#Loading nodes_parameter file
	level=2
	if [ ! -f "$QRM_NODES_PARAMETER" ]; then
		qmessg error "Nodes parameter file $QRM_NODES_PARAMETER not found"
		/sbin/ifconfig $CS_NIC:qrm down
		uninstall_node_monitor $level
		exit 4
	fi
	. $QRM_NODES_PARAMETER

	#Testing if we have all required parameters
	level=3
	if [ -z "$ROOT_MOUNT" ]; then
		qmessg error "Failed to aquire a mandatory parameters from the server"
		/sbin/ifconfig $CS_NIC:qrm down
		uninstall_node_monitor $level
		exit 4
	fi

	#################################################################
	#STEP IV: Creating configuration file where we will keep our data
	level=4
	qrm_create-config-file

	###################################################################
	#STEP V : If mode set to local than we need to copy the content of
	#/usr/qrm directory to the local hard disk
	level=5
	if [ "$MODE" == "local" ]; then
		if ! qrm_make_local; then
			qmessg error "Failed to copy $QRM_NODES_BASE_DIR/qrm files to local disk"
			uninstall_node_monitor $level
			exit 2
		else 
			qmessg notice "The appropriate qrm files were copied to $QRM_NODES_BASE_DIR/qrm successfully"
		fi
	fi


	qmessg notice "Finished QRM-node easy-migration"
	echo
	qmessg notice "Enjoy managing your datacenter by QRM"
	qmessg notice "Qlusters Inc."
	echo

}

###################################################################
#Here we roll back failed installation. We assume that we already #
#have all nessesary checkes performed when tryied to install      #
##################################################################
function qrm_uninstall_failed_installation() {
	local level=$1
	if [ -f $QRM_CONF_FILE ]; then
		. $QRM_CONF_FILE
	fi

	#For each level we perform nessesary rollback operation than
	#reduce level by one
	while [ $level -gt 1 ]; do

		case $level in
			1)
				echo  #Nothing to do here. We failed to send new_node_event 
				;;
			2|3|4)
				if [ -z "$FAILED_TO_SEND" ]; then
					#Send remove event only if we succeded in sending new node event	
					qmessg notice "Sending remove-node event"
					ifconfig ${QRM_INTERFACE}:qrm up 1>/dev/null 2>&1;
					if qrm_send-remove-node-event; then
						qmessg notice "remove-node event sent successfully"
					else
						qmessg error "failed to send remove-node event" 
					fi
					qmessg notice "Bringing install interface down"
					ifconfig ${QRM_INTERFACE}:qrm down 1>/dev/null 2>&1;
				fi
				if [ -f $QRM_CONF_FILE ]; then
					rm -f $QRM_CONF_FILE
				fi
				level=1
	     		;;
			5)
				if [ "$mode" == "local" ]; then
					echo -n "Removing /etc/qrm now "
					rm -Rf /usr/qrm/* &
					PID=$!
					while ps -p $PID 1>/dev/null 2>&1; do
						sleep 1
						echo -n "."
					done
					echo " ... DONE"		  
					level=1
				fi
	      		;;
			*)
				qmessg error "Unknown uninstall level"
				;;
		esac
		((level--))
	done
}

#################################################################
#Un-installing qrm-monitor on client. We do uninstall in two    #
#possible way. One - regular uninstall and emergency uninstall  #
#due to failed installation                                     #
#################################################################
function qrm_uninstall_node_monitor() {

	#Testing parameters for mandatory values
	if [ -z "$QRM_SERVER_IP" ]; then
		usage
		exit 6
	elif ! qrm_validate_ipaddress $QRM_SERVER_IP; then
		qmessg error "$QRM_SERVER_IP is not a valid QRM-server ip-address!"
		exit 6
	fi

	#First of all we need to load the value of QRM_NODES_BASE_DIR or use
	#the default value
	if [ -f $QRM_NODES_PARAMETER ]; then
		. $QRM_NODES_PARAMETER
	else 
		qmessg warning "Failed to load $QRM_NODES_PARAMETER"
		if [ "$FORCE" != "1" ]; then
			exit 1		
		else
			qmessg warning "Setting QRM_NODES_BASE_DIR=/usr"
			QRM_NODES_BASE_DIR=/usr
		fi
	fi
	#Loading interface data from config file
	if [ ! -f $QRM_CONF_FILE ]; then
		if [ "$FORCE" != "1" ]; then
			qmessg error "No such file $QRM_CONF_FILE"
			exit 4
		else
			qmessg warning "Force uninstall : There is no config file $QRM_CONF_FILE"
		fi
	else
		. $QRM_CONF_FILE
	fi 
	export QRM_NODES_BASE_DIR

	# find the nic
	if [ ! -z $QRM_CS_NIC ]; then
		export QRM_INTERFACE=$QRM_CS_NIC
	else
		export QRM_INTERFACE=`qrm_get-boot-interface`
	fi
	if [ -z "$QRM_INTERFACE" ]; then
		if [ "$FORCE" != "1" ]; then
			qmessg error "Nodes QRM boot interface configuration cannot be found"
			exit 4
		else
			qmessg warning "Force uninstall : Couldn't find QRM boot interface"
		fi
	fi

	#Testing aquired parameters from node_param file
	if [ -z "$QRM_SERVER_IP_ADDRESS" ]; then
		if [ "$FORCE" != "1" ]; then
			qmessg error "Could not get valid Nodes parameters"
			exit 4
		else
			qmessg warning "Trying to find the QRM boot-interface + ip"
			if [ ! -z "$QRM_CS_IP" ]; then
				export QRM_BOOT_IP=$QRM_CS_IP 
			else
				qmessg error "Could not get the ip to connect to the QRM-server"
				qmessg error "Maybe the boot-interface is not up/online?"
				qmessg warning "Force remove! Trying to continue anyways"
			fi
		fi
	else
		export QRM_BOOT_IP="$CS_QRM_IP"
	fi

	if [ "$FORCE" != 1 ]; then
		#When doing force uninstall after failed installation no questions
		#should be asked
		echo 
		qmessg notice "This procedure will remove the QRM-node-monitor from this system!"
		if [ ! -z "$QRM_INTERFACE" ]; then
			qmessg notice "QRM boot interface $QRM_INTERFACE"
		else
			SEND_REMOVE_EVENT=1
		fi

		if [ ! -z "$QRM_BOOT_IP" ]; then
			qmessg notice "QRM boot ip-address : $QRM_BOOT_IP"
		fi

		qmessg notice "Press <ENTER> to go on"
		read
	fi

	# stop the nodes-services
	cd $QRM_NODES_BASE_DIR/qrm/
	run_services 6
	cd -

	# remove the qrm init script
	qrm_chkconfig del qrm 1>/dev/null 2>&1
	rm -f /etc/init.d/qrm

	# remove inittab entry
	if grep -q ^qrm /etc/inittab; then
		cp -f /etc/inittab /etc/inittab.org
		TMP_FILE=`mktemp -q /tmp/XXXXXX`
		cat /etc/inittab | sed -e "s#^qrm.*##g" > $TMP_FILE
		mv $TMP_FILE /etc/inittab
	fi

	# bring up the interface if needed
	if [ ! -z "$QRM_BOOT_IP" ] && [ ! -z "$QRM_INTERFACE" ]; then
		if ! ip add show | grep -w "$QRM_BOOT_IP" | grep -w "$QRM_INTERFACE" 1>/dev/null 2>&1; then
			if [ "$FORCE" != "1" ]; then
				qmessg error "$QRM_BOOT_IP not active."
				exit 2
			fi
			qmessg warning "Trying to bring up $QRM_BOOT_IP on $QRM_INTERFACE"
			if ! ifconfig ${QRM_INTERFACE}:qrm $QRM_BOOT_IP up  1>/dev/null 2>&1; then
				qmessg error "Cannot bring up $QRM_BOOT_IP on ${QRM_INTERFACE}:qrm"
				if [ "$FORCE" != "1" ]; then
					exit 2
				else
					qmessg warning "Force uninstall : Failed to bring up $QRM_BOOT_IP on $QRM_INTERFACE" 
				fi
				SEND_REMOVE_EVENT=1
			fi
		fi
	elif [ -z "$QRM_BOOT_IP" ]; then
		SEND_REMOVE_EVENT=1
	fi

	#Sending remove node event to qrm
	if [ "$SEND_REMOVE_EVENT" == "0" ]; then
		qmessg notice "Sending remove-node event to the QRM-server (this may take some time)"
		if qrm_send-remove-node-event; then
			qmessg notice "remove-node event sent successfully"
		else
			qmessg error "QRM server reported an error"
			if [ "$FORCE" != "1" ]; then
				exit 2
			fi
		fi
	else
		qmessg error "No QRM boot interface configuration could be detected"
		qmessg error "QRM-server cannot be contacted for sending remove event"
		if [ "$FORCE" != "1" ]; then
			exit 2
		else
			qmessg warning "Force remove! (not sending remove event to the QRM-server)"
		fi
	fi
	
	#Here we need to destinguish between nfs mounted data and local mouinted data.
	#In the last case we need to remove this data from the disk
	if [ ! -f $QRM_CONF_FILE ]; then
		qmessg warning "Could not find the $QRM_CONF_FILE configuration file. Assuming the mode to be NFS"
		MODE="nfs"
	else
		rm -f $QRM_CONF_FILE
	fi

	qmessg notice "Removing $QRM_NODES_BASE_DIR/qrm and shutting down the QRM-interface"
	if ! qrm_shutdown-boot-interface; then
		if [ "$FORCE" != "1" ]; then
			qmessg error "Could not shutdown the QRM-interface"
			exit 2
		fi
	fi
	qmessg notice "Finished removing the QRM-node-monitor"
}

########################### MAIN PART ###################################

#Parsing the input command line
while [ $# -ne 0 ]; do
	case "$1" in
		-v | --virtual-environment-name)
			QRMV_VE_NAME=$2
			;;
		-q | --qrm-server-ip)
			QRM_SERVER_IP=$2
			export QRM_SERVER_IP
			;;
		-i | --ip)
			CS_IP=$2
			;;
		-e | --node-ext-id)
			NODE_EXT_ID=$2
			;;	
		-n | --network-card)
			CS_NIC=$2
			;;
		-h | --help)
			usage
			exit 0
			;;
		-o | --config-option)
			OPTION=$2
			;;
		-f | --force)
			FORCE=1
			;;
		-p | --part_tech)
			PART_TECH=$2
			;; 
	esac
	shift
done
if [ "$OPTION" == "install-node" ] || [ "$OPTION" == "install-partition" ]; then
	start_log
	qrm_install_node_monitor
elif [ "$OPTION" == "uninstall" ]; then
	start_log
	qrm_uninstall_node_monitor
else
	usage
	exit 0
fi
