#!/bin/bash
# version_number=2.15.1.0001
# Resets the KNC card and brings it into ready state with MPSS service running

# Function to check whether MIC uOS is booted (i.e. online)
function is_uOS_booted() {
	# echo "Entered is_uOS_booted"
	# Check whether MIC card is online
	# verify that MIC card is online
	UOS_ONLINE=$(micctrl --status $MIC_ID | awk '/online/ {print "online";exit}')
	if [ -z $UOS_ONLINE ];
	then
		# echo "is_uOS_booted: uOS is NOT online"
		return 0
	else
		# echo "is_uOS_booted: uOS IS online"
		return 1
	fi
}
# Function to wait for the uOS boot to finish 
function wait_for_uOS_boot() {
	# echo "Entered wait_for_uOS_boot"
	# Wait for MIC to get to a steady state (ready or online)
	micctrl --wait $MIC_ID > /dev/null

	# Check whether MIC card is online
	# verify that MIC card is online
	UOS_ONLINE=$(micctrl --status $MIC_ID | awk '/online/ {print "online";exit}')
	if [ -z $UOS_ONLINE ];
	then
		# echo "wait_for_uOS_boot: uOS boot failed"
		FAILCODE=1
		return 0
	else
		# echo "wait_for_uOS_boot: uOS boot completed"
		FAILCODE=0
		return 1
	fi
}

# Function to Boot MIC uOS
# (Assumes MPSS service has already been started and uOS is not booted)
function boot_uOS() {
	# echo "Entered boot_uOS: "
	# Wait for MIC card to settle in case it is "booting" or "reseting"
	micctrl --wait $MIC_ID > /dev/null
	# Try to boot the MIC card
	micctrl --boot $MIC_ID > /dev/null
	wait_for_uOS_boot
	return $?
}

# Function to check whether MPSS service is running
function check_mpss () {
	# echo "check_mpss: Entered"
	# Check whether MPSS service has been started
	MPSS_STATUS=$(service mpss status | sed -n -e '/^mpss/s/mpss is //p')

	if [ $MPSS_STATUS != 'running' ];
	then
		# echo "check_mpss: mpss is NOT running"
		FAILCODE=2
		return 0
	else
		# echo "check_mpss: mpss is running"
		return 1
	fi
}

# Function to check whether MIC card is in ready state
function is_mic_ready () {
	# echo "is_mic_ready: Entered"
	# wait for MIC to be in a stable state (i.e. ready or online)
	micctrl --wait $MIC_ID > /dev/null
	# Verify that MIC card is 'ready'
	MIC_READY=$(micctrl --status $MIC_ID | awk '/ready/ {print "ready";exit}')
	# echo "is_mic_ready: MIC_READY: " $MIC_READY
	if [ -z $MIC_READY ];
	then
		# echo "mic_reset: MIC NOT READY"
		FAILCODE=3
		return 0
	else
		# echo "mic_reset: MIC IS READY"
		return 1
	fi
}

# Function to reset MIC card, to ready state
function mic_reset () {
	# echo "mic_reset: Entered"
	# Reset the MIC card
	micctrl --reset $MIC_ID > /dev/null
	sleep 1
	is_mic_ready
	return $?
}

# Function to start micrasd
function start_micrasd() {
	/etc/init.d/micras start > /dev/null
}

# Function to start mpss service
function start_mpss () {
	# echo "start_mpss: Entered"
	# check that mpss is already started
	check_mpss
	if [ $? != 1 ];
	then
		# Start MPSS service
		# echo "start_mpss: Start the MPSS service"
		service mpss start > /dev/null
		# Verify that MPSS service started
		check_mpss
		if [ $? != 1 ];
		then
			# echo "start_mpss: Unable to start MPSS service"
			return 0
		fi
	fi
	# After starting MPSS, start micrasd
	start_micrasd
	# MPSS Service has been started, or was already running
	return 1
}

# Function to check SELinux configuration
function check_selinux () {
	# echo "check_selinux: Entered"
	# check SELinux config file: /etc/selinux/config to see if
	# SELinux is disabled
	SELINUX_STATUS=$(getenforce)

	if [ $SELINUX_STATUS != 'Disabled' ];
	then
		# echo "check_selinux: SELinux is NOT Disabled"
		FAILCODE=4
		return 0
	else
		# echo "check_selinux: SELinux is Disabled"
		return 1
	fi
	
	return 1
}

# Function to report script success and exit
function exit_passed () {
	# echo "exit_passed: Entered"
	case $STDOUT_FLAG in
	[0]*)
		echo "PASSED" > $TEMP_FILE
		mv $TEMP_FILE $FLAG_FILE
		;;
	[1]*)
		echo "PASSED"
		;;
	esac
	exit

}

# Function to report script failure and exit
# FAILCODE values:
#	0	-> Not really a failure, just returning "false" status
#	1	-> uOS Boot failed
#	2	-> MPSS Service not started
#	3	-> MIC reset failed
#	4	-> SELinux is not disabled
#	5	-> MIC card does not exist

function exit_failed() {
	# echo "exit_failed: Entered"
	# echo "FAILCODE: " $FAILCODE
	case $FAILCODE in
	[0]*)
		FAIL_MSG="FAILED"
		;;
	[1]*)
		# echo "Fail Code is 1: uOS Boot failed"
		FAIL_MSG="FAILED: uOS Boot failed"
		;;
	[2]*)
		# echo "Fail Code is 2: MPSS Service not started"
		FAIL_MSG="FAILED: MPSS Service not started"
		;;
	[3]*)
		# echo "Fail Code is 3: MIC reset failed"
		FAIL_MSG="FAILED: MIC reset failed"
		;;
	[4]*)
		# echo "Fail Code is 4: SELinux is NOT disabled"
		FAIL_MSG="FAILED: SELinux is NOT disabled"
		;;
	[5]*)
		# echo "Fail Code is 5: MIC card does not exist"
		FAIL_MSG="FAILED: MIC card does not exist"
		;;
	esac

	case $STDOUT_FLAG in
	[0]*)
		echo $FAIL_MSG > $TEMP_FILE
		mv $TEMP_FILE $FLAG_FILE
		;;
	[1]*)
		echo $FAIL_MSG
		;;
	esac
	exit
}

PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/root/bin
export PATH
# echo "Main lxmicstart"

# Initialize Failure Env variable
FAILCODE=0

#for each argument passed check if flag/operation/MIC_ID
for Argument in "$@"
do 
	if [ "$Argument" = "-o"  ]|| [ "$Argument" = "-O" ]; 
	then
		# Turn out status output ot stdout	
		STDOUT_FLAG=1
	elif [ "$Argument" = "ssh" ]; 
	then
		MIC_STATE="ssh"
	elif [ "$Argument" = "online" ]; 
	then
		MIC_STATE="online"
	elif [ "$Argument" = "check" ]; 
	then
		MIC_STATE="check"
	elif [ "$Argument" = "ready" ]; 
	then
		MIC_STATE="ready"
	elif [ "$Argument" = "help" ]; 
	then
		MIC_STATE="help"
	#If phrase mic is found set it current MIC card	
	elif [ "${Argument:0:3}" = "mic" ];#{String:position:length} 
	then	
		MIC_ID="$Argument"	
		MIC_CUR_MODE="$(micctrl --wait $MIC_ID)"		 	
		
		if [[ $MIC_CUR_MODE != *online* && $MIC_CUR_MODE != *ready* ]];	
		then 
			#echo "Mic Card may not exist"
			FAILCODE=5
		fi
	fi
done

#if MIC_STATE wasnt defined default to online
if [ -z $MIC_STATE ]; then
	MIC_STATE="online"
fi
#if STDOUT_FLAG wasnt defined default status output not shown
if [ -z $STDOUT_FLAG ]; then
	STDOUT_FLAG=0
fi

#echo "STDOUT_FLAG: " $STDOUT_FLAG
#echo "MIC_STATE: " $MIC_STATE

# Create MIC specific flag file names:  uOS_Booted$(MIC_ID)
FLAG_FILE="uOS_Booted$MIC_ID"
TEMP_FILE="uOS_Temp$MIC_ID"
#echo "Flag file name is: $FLAG_FILE"
#echo "Temp file name is: $TEMP_FILE"

# Remove any old uOS boot results files for this flag file
rm -f $FLAG_FILE $TEMP_FILE

# Check for failure while parsing parameters
if [ $FAILCODE != 0 ];
then
	exit_failed
fi

# Put Mic uOS in target state i.e. $MIC_STATE

if [ $MIC_STATE == 'help' ];
then
        # Print list of lxmicstart commands
	echo
	echo "lxmicstart [-o] [operation]"
	echo "   if -o is specified status output is directed to stdout"
	echo "   if -o is NOT specified status output written to uOS_Booted"
	echo "operation:"
	echo "    ssh     -> Add current MIC to ssh known_hosts"
	echo "    online  -> Put MIC card in online state (uOS online)"
	echo "    check   -> Check whether MIC is already online"
	echo "    ready   -> Reset MIC to put it in ready state"
	echo "    help    -> print this message"
	echo
	echo " If operation is not specified the default online is used."
	echo
	echo "On success PASSED is written to stdout or uOS_Booted"
	echo "On failure FAILED is written to stdout or uOS_Booted"
	echo "Additional failure information may be added to FAILED message"
	exit_passed
fi

if [ $MIC_STATE == 'ssh' ];
then
	# Add current MIC boards fingerprint to ssh known_hosts file
	start_mpss
	if [ $? != 1 ];
	then
		# Unable to start MPSS service
		exit_failed
	fi

	# Since this action impacts all the MIC cards in the system, this
	# function ignores the $MIC_ID parameter and operates on all the
	# known MIC cards in the system.

	# For each possible MIC ID remove enty from known_hosts
	for HOST in mic0 mic1 mic2 mic3 mic4 mic5 mic6 mic7 mic8
	do
		# Filter out HOST's which are not online
		HSTATE=$(micctrl --status $HOST 2> /dev/null | awk '/online/ {print "online";exit}')
		if [ "$HSTATE" == "online" ];
		then
			echo "Update known_hosts for $HOST"
			# Remove $HOST entry from known_hosts
			sed -e "/^$HOST/d" /root/.ssh/known_hosts > /root/.ssh/known_hosts.save
			rm -rf /root/.ssh/known_hosts
			mv  /root/.ssh/known_hosts.save /root/.ssh/known_hosts

			# Reinitialize SSH fingerprint in known_hosts for HOST
			./lxmicssh $HOST
		fi
		HSTATE=""
	done
	exit_passed
fi

if [ $MIC_STATE == 'online' ];
then
	# echo "lxmicstart: Main->online"
	# Check SELinux config to verify SELinux is disabled.
	# MIC uOS boot is likely to fail is SELinux is enabled
	check_selinux
	if [ $? != 1 ];
	then
		# SELinux may be enabled.  Exit Failed so the user will be
		# notified and can check SELinux configuration
		exit_failed
	fi

	# Boot the MIC uOS if it isn't already booted
	start_mpss
	if [ $? != 1 ];
	then
		# Unable to start MPSS service
		exit_failed
	fi
	# MPSS service is running, start micrasd
	start_micrasd

	# MPSS service is running, check whether MIC uOS is booted
	is_uOS_booted
	if [ $? != 1 ];
	then
		# uOS is not online, so boot it
		boot_uOS
		if [ $? != 1 ];
		then
			# uOS boot failed
			FAILCODE=1
			exit_failed
		fi
	fi
	# uOS boot passed
	exit_passed
fi

if [ $MIC_STATE == 'ready' ];
then
	# Check whether MIC is already 'ready'
	# Make sure MPSS service is started. Since it is possible for
	# MIC to be "ready" when the MPSS service is stopped.
	start_mpss
	if [ $? != 1 ];
	then
		# Unable to start MPSS service
		exit_failed
	fi
	# Force a reset, regardless of current MIC state
	mic_reset
	if [ $? != 1 ];
	then
		# MIC reset failed to make MIC ready
		exit_failed
	fi
	# MIC is ready
	exit_passed
fi
	
if [ $MIC_STATE == 'check' ];
then
	# Check whether MIC is already 'online' but don't do anything if it isn't
	# echo "lxmicstart: Main->check"
	is_uOS_booted
	if [ $? != 1 ];
	then
		# uOS is not online
		exit_failed
	fi
	# uOS is online
	exit_passed
fi

# Unsupported parameter value from user, put fail message in flag file
echo "FAILED Unsupported parameter: " $MIC_STATE
echo "FAILED Unsupported parameter: " $MIC_STATE > $TEMP_FILE
mv $TEMP_FILE $FLAG_FILE
exit
