#!/bin/bash
# hpeilo_nagios_config -- The script aims to generate nagios 
#			 configuration file for discovering the
#                        HP ProLiant Servers.
#  (C) Copyright [2015] Hewlett-Packard Enterprise Development Company, L.P.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of version 2 of the GNU General Public License as
#  published by the Free Software Foundation.
#
#  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:
#   Free Software Foundation, Inc.
#   51 Franklin Street, Fifth Floor
#   Boston, MA 02110-1301, USA.
#
#  Written by Chandrakant Hugar <chandrakant.hugar@hp.com>.

CLEARSCREEN=$(/usr/bin/tput clear)
Nagios_iLO_Plugins_Path=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

HP_iLO_NAGIOS_INTRO="The \"hpeilo_nagios_config\" configuration script will help you to create HPE iLO nagios plugin configuration file which is later can used for active/passive HPE iLO host servers discovery and configure the nagios configuration file on monitoring host.\n\nFollowing are the parameters,user has to configur to get \"nagios-plugins-hpeilo\" to work efficiently.\n\n"
HP_iLO_NAGIOS_INTRO_1="\e[1mActive discovery: \e[0mActive discovery scans all reachable HPE iLO servers in the network of the monitoring server. This approach can discover all HPE iLO servers in a given network ip range or network subnet.\nNote: Active discovery is a time-consuming process and it depends on total number of hosts in a network subnet or IP range.\n\nYou have to enable to do active discovery in HPE iLO nagios plugin configuration file to scan all HPE iLO servers one time.\n\n"
HP_iLO_NAGIOS_INTRO_2="\e[1mPassive discovery: \e[0mPassive discovery discovers HPE iLO servers once receiving the cold start traps generated by those servers.\nThe traps are generated when those servers get booted successfully, so this approach cannot discover the up and running servers.\nAlso it is required to add \"traphandle\" command and community string in \"snmptrapd.conf\" file as mentioned in the below example.\n\t\"authCommunity log,execute,net <community string>\"\n\t\"traphandle 1.3.6.1.6.3.1.1.5.1 ${Nagios_iLO_Plugins_Path}/nagios_hpeilo_cfg_generator -m 2 \n\t${Nagios_iLO_Plugins_Path}/hpeilo_nagios_config.cfg\"\n\t\"traphandle 1.3.6.1.4.1.232.0.* ${Nagios_iLO_Plugins_Path}/nagios_hpeilo_traps\".\nThe \"snmptrapd\" service will be restarted once its configured.\n\nYou have to enable Passive discovery in  HPE iLO nagios plugin configuration file to add the HPE iLO server on receiving cold trap.\n"

HP_iLO_NAGIOS_INTRO_3="\e[1mHPE iLO server Host Group: \e[0mA HPE iLO server Host Group  is used to group one or more HPE iLO servers together under one group.\nIt consists of \"Group Name\",\"IP address range or Network subnet or IP address\" and \"Community string\".\nThese data are used to configure nagios \"Host Group\" Directives for simplifying configuration with display purposes.\nAn example of HPE iLO Host Group is as below\n\t\"HOSTGROUP:HPE_iLO_Group_1,192.1.10.20-192.1.10.200,public,public\"\n\nYou have to add at least one Host Group to discover the HPE iLO servers using any of the above mentioned discovery method.\nNote: Default generic host group will be created and the discovered HPE iLO servers will be added to this group if the discovered HPE iLO server IP does not belongs to any of the configured host groups.\n\n"
HP_iLO_NAGIOS_INTRO_4="\e[1mcheck_interval:\e[0m It is used to configure check interval of HPE iLO servers. Default value is set to 5 minute.\n\n"

HP_iLO_NAGIOS_INTRO_n="\e[1mYou may press <ctrl+c> now to exit if needed.\e[0m\n\n"
HP_iLO_NAGIOS_PASSIVE_DISC_INTRO="Configuring HPE iLO nagios plugin for passive discovery.\nPassive discovery enable monitoring host to add a HPE iLO host server to host group on receiving SNMP cold trap.it requires adding \"traphandle\" in \"snmptrapd\" configuration file for SNMP cold trap OID and system health trap OID\n"

HP_iLO_NAGIOS_ACTIVE_DISC_INTRO="Configuring HPE iLO nagios plugin for active discovery.\nActive discovery will do network scan for all the HPE iLO hosts which are configured in the host group and add to the nagios host group  with respective host group name.\nIt requires to executing the \"nagios_hpeilo_cfg_generator\" script at least one time to complete the network scan for the hosts.\n"

HP_iLO_NAGIOS_NET_INTERFACE_INTRO="Active discovery requires network interface to scan all HPE iLO host's over the network.\nYou can find the network interface by running the command \"ifconfig -a\".\nMake sure network interface is up and ip is mapped to the HPE iLO host group ip range specified while configuring HPE iLO host group.\n"

HP_iLO_NAGIOS_HOSTS_INTRO="HPE iLO host group configuration.\nHPE iLO host groups can be created with a range of IP address or a IP address.\nYou can also create host group based on SNMP read only community string.\nDefault generic host group will be created if host group is not configured or if HPE iLO host which are discoved and not in the configured host group\nIP range will be added with default \"public\" SNMP read-only community to the default host group name.\n"

HP_iLO_NAGIOS_HOSTGROUP_INTRO="HPE iLO host group configuration requires host group name, host group IP range address and SNMP read-only community string as example below.\nhost group name: Data_center-A,Note:no space allowed\nhost group valid IP range : 192.10.10.2/24  or 192.10.10.20-192.10.10.200 or 192.10.10.15 .\nValid SNMP read-only community string configured in the HPE iLO page, default value is \"public\" if not specified.\n"

HP_iLO_NAGIOS_HOSTIP_INTRO="\n\e[1mHPE iLO nagios monitoring server host ip:\e[0m\nExample:\n\t1: eth0 128.88.150.216\n\t2: eth1 192.168.1.10\n\t3: eth2 192.10.10.100\n\t.\n\t.\n\tn:\n\tYou have to enter valid option 1 or 2 or n to configure host ip.\n\n\n" 

HP_iLO_NAGIOS_CONTACTGROUP_INTRO="\nHPE iLO contact group  and contacts configuration requires contact group name, contact group alias and contact details as example below.\ncontactgroup_name: linuxAdminGroup\nalias : Linux admin group  \ncontact_name: iloAdmin\nalias : Ilo admin \nemail : iloadmin@hpe.com\n" 

DEFAULT_CONFIG_FILE_NAME="hpeilo_nagios_config.cfg"
CONFIG_FLAG=
iLO_CFGFILE="ilo/ilo.cfg"
ILOCFG=

function get_hpiLO_nagios_install_path {
local iLO_nagios_plugin="nagios_hpeilo_engine"
NAGIOS_INST_PATH="${Nagios_iLO_Plugins_Path}"
}

#Function to display configuration script info message
# $1 contains display message
# $2 contains the TTY device node
# $3 contains NOBLANK or CLSCR
#always return 0

function displayIntro()
{
	if [ "$3" != "NOCLSCR" ]; then
		echo "$CLEARSCREEN" > $2
	fi
	printf "$1"  2> $2 |grep -w  -oE '.{1,120}' 
	return 0
}


get_tty() 
{
	# $1 contains the ENV for tty
	# Return 0 when succeed
	TMP=/dev/tty
	<$TMP >/dev/null 2>&1
	if [ $? = 0 ]; then
		eval $1="$TMP"
		return 0
	fi
	eval $1=""
	return 1
}

get_installmode() 
{
	get_tty TMPTTY
	if [ ! -z "$TMPTTY" ]; then
		eval $1="$TMPTTY"
	fi
}

# $1 contains Data
# $2 contains NOBLANK or BLANKOK
# $3 contains NOSPACE or SPACEOK or YESNO
validate_data () 
{
	[ $2 = "NOBLANK" -a -z "$1" ] && return 1
	if [ $3 = "NOSPACE" ]; then
		echo $ANS | egrep ' |       ' >/dev/null 2>&1
		[ $? = 0 ] && return 2
	fi
	if [ $3 = "YESNO" ]; then
		if [ ! -z "`echo $ANS | tr -d 'yn'`" ]; then
			return 3
		fi
	fi
	return 0
}

# Verify an IP Address:
function is_IP() {
if [ `echo $1 | grep -o '\.' | wc -l` -ne 3 ]; then
	return 1;
elif [ `echo $1 | tr '.' ' ' | wc -w` -ne 4 ]; then
	return 1;
else
	for OCTET in `echo $1 | tr '.' ' '`; do
		if ! [[ $OCTET =~ ^[0-9]+$ ]]; then
			return 1;
		elif [[ $OCTET -lt 0 || $OCTET -gt 255 ]]; then
			return 1;
		fi
	done
fi

return 0;
}

function is_valid_range()
{
	local bool=0
	local ip1=
	local ip2=
	OIFS=$IFS
	IFS='.'
	ip1=($1)
	ip2=($2)
	IFS=$OIFS
	#check first octet
	if [[ ${ip1[0]} -ne ${ip2[0]} ]]; then
		bool=1
	elif [[ ${ip1[0]} -eq ${ip2[0]} ]] && [[ ${ip1[1]} -gt ${ip2[1]} ]]; then
		bool=1
	elif [[ ${ip1[1]} -eq ${ip2[1]} ]] && [[ ${ip1[2]} -gt ${ip2[2]} ]]; then
		bool=1
	elif [[ ${ip1[2]} -eq ${ip2[2]} ]] && [[ ${ip1[3]} -gt ${ip2[3]} ]]; then
		bool=1
	fi
	echo $bool
}


function getSubnetMask()
{
	local i
	local subnetmask=""
	local full_octets=$(($1/8))
	local partial_octet=$(($1%8))
	for ((i=0;i<4;i+=1)); do
		if [ $i -lt $full_octets ]; then
			subnetmask+=255
		elif [ $i -eq $full_octets ]; then
			subnetmask+=$((256 - 2**(8-$partial_octet)))
		else
			subnetmask+=0
		fi   
		[ $i -lt 3 ] && subnetmask+=.
	done

	echo $subnetmask
}

function valid_ip_range()
{
	local  ip_1=`echo $1 | awk -F '/' '{print $1}'`
	local ip_2=`echo $1 | awk -F '-' '{print $2}'`
	local subnet_mask_bits=`echo $1 | awk -F '/' '{print $2}'`
	local  stat=1
	local check_range=1
	local ip_addr[0]=`echo $ip_1 | awk -F '-' '{print $1}'`
	if [ "x${ip_2}" != "x" ];then
		ip_addr[1]=$ip_2
		check_range=0
	elif [ "x${subnet_mask_bits}" != "x" ];then
		num='^[0-9]+$'
		if ! [[ $subnet_mask_bits =~ $num ]] ; then
			return 1
		else
			ip_2=$(getSubnetMask $subnet_mask_bits)
		fi
		ip_addr[1]=$ip_2
	fi
	for((idx=0;idx<${#ip_addr[@]};idx++)); do
		local ip=${ip_addr[$idx]}
		if is_IP $ip; then
			stat=0
		else
			stat=1
		fi
	done

	if [[ $stat -eq 0 ]] &&  [[ $check_range -eq 0 ]]; then
		stat=$(is_valid_range ${ip_addr[0]} ${ip_addr[1]})
	fi

	return $stat
}

#$1 array of elements
function isduplicate_value()
{
	local stat=0
	local values=("$@")
	local num_ele=${#values[@]}
	if [ $num_ele -gt 1 ]; then
		num_ele=$(($num_ele-1))
		local key=${values[$num_ele]}
		stat=`echo  "${values[@]:0:$num_ele}" | grep -c -w "^$key"`
	fi
	return $stat
}
# $1 contains the user prompt
# $2 contains the TTY device node
# $3 contains NOBLANK or BLANKOK
# $4 contains NOSPACE or SPACEOK
# $5 contains ECHO or NOECHO
# $6 contains CLSCR or NOCLSCR
# Always return 0
get_userinput () 
{
	#	echo "" > $2
	if [ "$5" = NOECHO ]; then
		stty -F $2 -echo
		printf "\nNOTE: keyboard input echo has been turned off." > $2
	fi
	while true; do
		while true; do
			if [ "$6" != "NOCLSCR" ]; then
				echo "$CLEARSCREEN" > $2
			fi
			printf "$1" "" > $2
			read ANS < $2
			[ "$5" = NOECHO ] && echo "" > $2
			validate_data "$ANS" "$3" "$4"
			case "$?" in
				1)
				continue
				;;
				2)
				echo -n "ERROR: Space and tab are not allowed, press ENTER to continue ..." > $2
				read ANS < $2
				[ "$5" = NOECHO ] && echo "" > $2
				continue
				;;
				3)
				echo -n "ERROR: You must type 'y' or 'n', press ENTER to continue ..." > $2
				read ANS < $2
				[ "$5" = NOECHO ] && echo "" > $2
				continue
			esac
			break
		done
		[ ! "$5" = NOECHO ] && break
		[ -z "$ANS" ] && break
		printf "Re-enter the same input to confirm: " > $2
		read ANS1 < $2
		echo "" > $2
		if [ "$ANS1" = "$ANS" ]; then
			printf "ACCEPTED: inputs match!\n\n" > $2
			break
		fi
		printf "ERROR: inputs mismatch! Press ENTER to try again." > $2
		read ANS < $2
	done
	if [ "$5" = NOECHO ]; then
		stty -F $2 echo
	fi
	echo $ANS
	return 0
}



function cfg_passive_enable_value()
{
	local temp=$(get_userinput "\nDo you wish to enable passive HPE iLO host discovery (y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
	if [ "$temp" = "n" ]; then
		PASSIVE_DISCOVERY=0
	else
		PASSIVE_DISCOVERY=1
	fi
}


function cfg_active_enable_value() {
local temp=$(get_userinput "\nDo you wish to enable active discovery (y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
if [ "$temp" = "n" ]; then
	ACTIVE_DISCOVERY=0
else
	ACTIVE_DISCOVERY=1
fi


}

function cfg_monitor_host_ip() {
	echo
	displayIntro "\n$HP_iLO_NAGIOS_HOSTIP_INTRO" $TTY NOCLSCR
	echo
	echo
	displayIntro "HPE iLO Nagios Monitoring Server Host IP" $TTY NOCLSCR
	while true; do
		oldifs="$IFS"
		IFS=$'\n'
		array=($(ip -o -4 addr show | awk -F '[ /]+' '/global/ {print $2,$4}'))
		num_arr_ele=`ip -o -4 addr show | awk -F '[ /]+' '/global/ {print $2,$4}' | wc -l`
		for ((idx=0;idx<$num_arr_ele;idx++)); do
			echo "$((idx + 1)): ${array[$idx]}"
		done
		hostip_array=($(ip -o -4 addr show | awk -F '[ /]+' '/global/ {print $4}'))
		while true; do
		local	ip_opt=$(get_userinput "\nEnter valid option to configure nagios monitoring server host ip:" $TTY NOBLANK NOSPACE ECHO NOCLSCR)
			
			if [ "$ip_opt" -ge "1" ] && [ "$ip_opt" -le "$num_arr_ele" ]; then 
				break
			fi
		done
		ip_opt=$((ip_opt - 1))
		nagios_hostip=${hostip_array[$ip_opt]}
		IFS="$oldifs"
		
		stat=$(is_valid_range $nagios_hostip $nagios_hostip )
		
		
		if  [ "$stat" -eq "0" ]; then 
			break
		fi
	done
}

function cfg_hostgroup()
{
	local host_entries=0
	local flag=
	hostgreoup_name=()
	local arr_tmp_ele=
	local temp=$(get_userinput "\nDo you wish to configure host groups (y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
	if [ "$temp" != "n"  ]; then
		displayIntro "\n$HP_iLO_NAGIOS_HOSTGROUP_INTRO" $TTY NOCLSCR
		while true; do
			while true;do
				hostgreoup_name[$host_entries]=$(get_userinput "\nEnter host group name: " $TTY NOBLANK NOSPACE ECHO NOCLSCR)
				arr_tmp_ele=${hostgreoup_name[$host_entries]}
				if isduplicate_value ${hostgreoup_name[@]}; then
					break
				else
					displayIntro "\n\t\"$arr_tmp_ele\" is already exists" $TTY NOCLSCR
				fi
			done
			while true; do
				hostgroup_ip[$host_entries]=$(get_userinput "\nEnter host group \"${hostgreoup_name[$host_entries]}\" IP range: " $TTY NOBLANK NOSPACE ECHO NOCLSCR)
				if valid_ip_range $hostgroup_ip; then
					arr_tmp_ele=${hostgroup_ip[$host_entries]}
					if isduplicate_value ${hostgroup_ip[@]}; then
						break;
					else
						displayIntro "\n\t\"$arr_tmp_ele\" is already exists" $TTY NOCLSCR
					fi

				else
					displayIntro "\n\t\"${hostgroup_ip[$host_entries]}\" is not valide IP or IP range" $TTY NOCLSCR
				fi
			done 
			hostgrp_read_comm[$host_entries]=$(get_userinput "\nEnter host group \"${hostgreoup_name[$host_entries]}\" SNMP read-only community string (Blank default value  public): " $TTY BLANKOK NOSPACE NOECHO NOCLSCR)
			hostgrp_trap_comm[$host_entries]=$(get_userinput "\nEnter host group \"${hostgreoup_name[$host_entries]}\" SNMP Trap community string (Blank default value  public): " $TTY BLANKOK NOSPACE NOECHO NOCLSCR)

			if [ "x${hostgrp_read_comm[$host_entries]}" = "x" ]; then
				hostgrp_read_comm[$host_entries]="public"
			fi

			if [ "x${hostgrp_trap_comm[$host_entries]}" = "x" ]; then
                                hostgrp_trap_comm[$host_entries]="public"
                        fi

			temp=$(get_userinput "\nDo you wish to add one more host group (y/n) (Blank is n): " $TTY BLANKOK YESNO ECHO NOCLSCR)
			if [ "$temp" != "y"  ]; then
				break
			fi
			host_entries=$(($host_entries+1))
		done
	fi

}

function cfg_contactgroup()
{
        local contactgroup_entries=0
        local flag=
        contactgroup_name=()
        local arr_tmp_ele=
        local temp=$(get_userinput "\nDo you wish to configure Contact group (y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
        if [ "$temp" != "n"  ]; then
                displayIntro "\n$HP_iLO_NAGIOS_CONTACTGROUP_INTRO" $TTY NOCLSCR
                        while true;do
                                contactgroup_name[$contactgroup_entries]=$(get_userinput "\nEnter Contact group name : " $TTY NOBLANK NOSPACE ECHO NOCLSCR)
                                arr_tmp_ele=${contactgroup_name[$contactgroup_entries]}
                                if isduplicate_value ${contactgroup_name[@]}; then
                                        break
                                else
                                        displayIntro "\n\t\"$arr_tmp_ele\" is already exists" $TTY NOCLSCR
                                fi
                        done
                        while true; do
                                contactgroup_alias[$contactgroup_entries]=$(get_userinput "\nEnter Contact group alias : " $TTY NOBLANK SPACEOK ECHO NOCLSCR)
                                arr_tmp_ele=${contactgroup_alias[$contactgroup_entries]}
                                if isduplicate_value ${contactgroup_alias[@]}; then
                                        break;
                                else
                                        displayIntro "\n\t\"$arr_tmp_ele\" is already exists" $TTY NOCLSCR
                                fi
                        done
        local contact_entries=0
        local cflag=
        contact_name=()
        local arr_tmp_cele=
        local temp="y"
        
	if [ "$temp" != "n"  ]; then
                while true; do
                        while true;do
                                contact_name[$contact_entries]=$(get_userinput "\nEnter Contact name (No Spaces in between) : " $TTY NOBLANK NOSPACE ECHO NOCLSCR)
                                arr_tmp_cele=${contact_name[$contact_entries]}
                                if isduplicate_value ${contact_name[@]}; then
                                        break
                                else
                                        displayIntro "\n\t\"$arr_tmp_cele\" is already exists" $TTY NOCLSCR
                                fi
                        done
                        while true; do
                                contact_alias[$contact_entries]=$(get_userinput "\nEnter Contact alias : " $TTY NOBLANK SPACEOK ECHO NOCLSCR)
                                arr_tmp_cele=${contact_alias[$contact_entries]}
                                if isduplicate_value ${contact_alias[@]}; then
                                        break;
                                else
                                        displayIntro "\n\t\"$arr_tmp_cele\" is already exists" $TTY NOCLSCR
                                fi
                        done
                        while true;do
                                contact_email[$contact_entries]=$(get_userinput "\nEnter Contact email ID (No Spaces in between) : " $TTY NOBLANK NOSPACE ECHO NOCLSCR)
                                arr_tmp_cele=${contact_email[$contact_entries]}
                                if isduplicate_value ${contact_email[@]}; then
                                        break
                                else
                                        displayIntro "\n\t\"$arr_tmp_cele\" is already exists" $TTY NOCLSCR
                                fi
                        done

                        temp=$(get_userinput "\nDo you wish to add one more contact to contact group (y/n) (Blank is n): " $TTY BLANKOK YESNO ECHO NOCLSCR)
                        if [ "$temp" != "y"  ]; then
                                break
                        fi
                        contact_entries=$(($contact_entries+1))
                done
        fi


			while true;do
				contactgroup_members[$contactgroup_entries]=${contact_name[@]}
                                arr_tmp_ele=${contact_members[$contactgroup_entries]}
                                if isduplicate_value ${contactgroup_members[@]}; then
                                        break
                                else
                                        displayIntro "\n\t\"$arr_tmp_ele\" is already exists" $TTY NOCLSCR
                                fi
                        done

                        #temp=$(get_userinput "\nDo you wish to add one more Contact group (y/n) (Blank is n): " $TTY BLANKOK YESNO ECHO NOCLSCR)
                        #if [ "$temp" != "y"  ]; then
                        #        break
                        #fi
                        contactgroup_entries=$(($contactgroup_entries+1))
                #done
        fi

}

function cfg_check_interval()
{
	while true; do
		temp=$(get_userinput "\nEnter host group check interval time in minutes (Blank default value - 5 minutes ): " $TTY BLANKOK NOSPACE ECHO NOCLSCR)
		if [ "y$temp" = "y" ]; then
			check_interval=5
			break
		else
			if [[ $temp =~ ^[0-9]+$ ]]; then
				check_interval=5
				break;
			else
				displayIntro "\n\t\"$temp\" is not number" $TTY NOCLSCR
			fi
		fi
	done

}

function write_config_file {
local config_gen_file="nagios_hpeilo_cfg_generator"
get_hpiLO_nagios_install_path
if [ -f $NAGIOS_INST_PATH/$config_gen_file ]; then
	if [ "$1" = "" ]; then
		nagios_hpilo_cfg_file=$NAGIOS_INST_PATH/$DEFAULT_CONFIG_FILE_NAME
	else
		if [[ $CONFIG_FLAG == "1" ]]; then
			nagios_hpilo_cfg_file=$NAGIOS_INST_PATH/$USER_CONFIG_FILE_NAME.cfg
		else
			nagios_hpilo_cfg_file=$NAGIOS_INST_PATH/$USER_CONFIG_FILE_NAME
		fi
	fi
	
	echo -e "\n"
	echo -e "\t\t**************Configured Data****************"
 	echo -e "\t\t PASSIVE_DISCOVERY $PASSIVE_DISCOVERY" 
        echo -e "\t\t ACTIVE_DISCOVERY  $ACTIVE_DISCOVERY" 
        for((idx=0;idx<${#hostgreoup_name[@]};idx++)); do
               	echo -e "\t\t HOSTGROUP: ${hostgreoup_name[$idx]},${hostgroup_ip[$idx]},${hostgrp_read_comm[$idx]},${hostgrp_trap_comm[$idx]}" 
        done
        for((idx=0;idx<${#contactgroup_name[@]};idx++)); do
        	echo -e "\t\t CONTACTGROUP: ${contactgroup_name[$idx]},${contactgroup_alias[$idx]},${contactgroup_members[$idx]}"
        done
        for((idx=0;idx<${#contact_name[@]};idx++)); do
                echo -e "\t\t CONTACT: ${contact_name[$idx]},${contact_alias[$idx]},${contact_email[$idx]}"
        done
	echo -e "\t\t CHECK_INTERVAL $check_interval"
        echo -e "\t\t NAGIOS_HOSTIP $nagios_hostip"
	echo -e "\t\t*********************************************"
        local tmp=$(get_userinput "\nDo you wish to write above configured data to host-group configuration file. (y/n) (Blank is y):" $TTY BLANKOK YESNO ECHO NOCLSCR)
	
	if [ "$tmp" != "n" ]; then	
		touch $nagios_hpilo_cfg_file
 		echo "PASSIVE_DISCOVERY $PASSIVE_DISCOVERY" > $nagios_hpilo_cfg_file
        	echo "ACTIVE_DISCOVERY  $ACTIVE_DISCOVERY" >> $nagios_hpilo_cfg_file
        	for((idx=0;idx<${#hostgreoup_name[@]};idx++)); do
                	echo "HOSTGROUP: ${hostgreoup_name[$idx]},${hostgroup_ip[$idx]},${hostgrp_read_comm[$idx]},${hostgrp_trap_comm[$idx]}" >> $nagios_hpilo_cfg_file
        	done
        	for((idx=0;idx<${#contactgroup_name[@]};idx++)); do
                	echo  "CONTACTGROUP: ${contactgroup_name[$idx]},${contactgroup_alias[$idx]},${contactgroup_members[$idx]}" >> $nagios_hpilo_cfg_file
        	done
        	for((idx=0;idx<${#contact_name[@]};idx++)); do
                	echo "CONTACT: ${contact_name[$idx]},${contact_alias[$idx]},${contact_email[$idx]}" >> $nagios_hpilo_cfg_file
        	done
        	echo "CHECK_INTERVAL $check_interval" >> $nagios_hpilo_cfg_file
        	echo "NAGIOS_HOSTIP $nagios_hostip" >> $nagios_hpilo_cfg_file
        	displayIntro "\nHPE iLO host-group configuration file saved at $nagios_hpilo_cfg_file.\n" $TTY NOCLSCR
	else
		echo "Run configuration 'hpeilo_nagios_config'  script to setup passive/active discovery"
		exit 1
	fi
	#Check status of ilo.cfg 
	Chk_iLOCfgFile
        local temp=$(get_userinput "\nDo you wish to run configuration file to complete the process (y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
        if [ "$temp" != "n"  ]; then
                displayIntro "\nRunning configuration  file ....\n" $TTY NOCLSCR
		if [ "$ILOCFG" = "1" ]; then
                $NAGIOS_INST_PATH/$config_gen_file -m 3 -s $nagios_hpilo_cfg_file
		else 
		    $NAGIOS_INST_PATH/$config_gen_file -m 3 -s $nagios_hpilo_cfg_file -o
		fi
        else
		if [ "$ILOCFG" = "1" ]; then
                printf "\nPlease run \"$NAGIOS_INST_PATH/$config_gen_file -m 3 -s $nagios_hpilo_cfg_file \" \nscript manualy to complete the configuration\n" 2>$TTY
		else
		printf "\nPlease run \"$NAGIOS_INST_PATH/$config_gen_file -m 3 -s $nagios_hpilo_cfg_file -o\" \nscript manualy to complete the configuration\n" 2>$TTY
		fi
        fi
else
	echo
        echo "HPE iLO nagios plugin not installed.Please install and configure."
fi
}
function display_all_intru()
{
	displayIntro "$HP_iLO_NAGIOS_INTRO" $TTY CLSCR
	echo 
	displayIntro "$HP_iLO_NAGIOS_INTRO_1" $TTY NOCLSCR
	echo
	displayIntro "$HP_iLO_NAGIOS_INTRO_2" $TTY NOCLSCR
	echo
	displayIntro "$HP_iLO_NAGIOS_INTRO_3" $TTY NOCLSCR
	echo
	displayIntro "$HP_iLO_NAGIOS_INTRO_4" $TTY NOCLSCR
	echo
	displayIntro "$HP_iLO_NAGIOS_INTRO_n" $TTY NOCLSCR

}

function get_nagios_cfg_file() {
        local   nagios_cfg=


        # The format might be like:
        #       1)  NagiosIloCfgFile=${prefix}/etc/nagios.cfg
        #       2)  NAGIOSCFG="/etc/nagios3/nagios.cfg"
        nagios_cfg=`grep -E "=.*etc.*nagios.cfg" /etc/init.d/nagios* | \
                        cut -d '=' -f 2`

        # trim double quotes
        nagios_cfg=`echo $nagios_cfg | tr -d '"'`

        if [[ $nagios_cfg = *prefix* ]]; then
                # The /etc/init.d/nagios* has the fomrat like this:
                #       NagiosIloCfgFile=${prefix}/etc/nagios.cfg
                # So, we need to replace ${prefix} with the actual value

                # Find the nagios prefix path
                local nagios_prefix=`grep -i "^prefix=" /etc/init.d/nagios* | \
                                cut -d '=' -f 2`

                # ${prefix}/etc/nagios.cfg -> will be etc/nagios.cfg
                local nagios_suffix=`echo $nagios_cfg | cut -d '/' -f 2-`

                nagios_cfg="${nagios_prefix}/$nagios_suffix"
		nagios_cfg=`echo $nagios_cfg | sed -r  's/\/\//\//g'`
        fi

        echo "$nagios_cfg"

}

#Check ilo.cfg file exist or not
function Chk_iLOCfgFile()
{
	local   nagios_cfg=$(get_nagios_cfg_file)

        nagios_conf_path=`dirname $nagios_cfg`

	if [ -f $nagios_conf_path/$iLO_CFGFILE ]; then
	local tmp=$(get_userinput "\nHPE iLO Hosts/Services discovered configuration file is existing:$nagios_conf_path/$iLO_CFGFILE\nDo you wish to replace it?(y/n) (Blank is y): " $TTY BLANKOK YESNO ECHO NOCLSCR)
	fi	
	if [ "$tmp" = "n" ]; then
                ILOCFG=1        #update the ilo.cfg file
        fi
}

function chk_cfg_file()
{
local iLO_nagios_cfg_plugin="nagios_hpeilo_cfg_generator"
get_hpiLO_nagios_install_path
if [ -f $NAGIOS_INST_PATH/$DEFAULT_CONFIG_FILE_NAME ]; then
	local temp=$(get_userinput "\nDefault: \"$DEFAULT_CONFIG_FILE_NAME\" Already Exists.\nDo you wish to replace it? (y/n)(Blank is n): " $TTY BLANKOK YESNO ECHO NOCLSCR)
 	if [ "$temp" != "y"  ]; then
		echo "Enter new config file name [Note: No space allowed]"

		while read USER_CONFIG_FILE_NAME
		do
        		# ignore the space line
        		if [ "x${USER_CONFIG_FILE_NAME}" = "x" ]; then
                		continue
        		fi

        		# ignore the comment lines
        		if [ "x$(echo -n $USER_CONFIG_FILE_NAME | grep -E \"^#\")" != "x" ]; then
				echo "Special characters are not allowed "
                		continue
        		fi

			if [ -f "$USER_CONFIG_FILE_NAME" ] 
			then
				echo "The file '$USER_CONFIG_FILE_NAME' exists.Try another name"
				continue
			else
				break
			fi
		done
		if [[ $USER_CONFIG_FILE_NAME != "*.cfg" ]]; then
			CONFIG_FLAG=1
		fi
		main_func
		write_config_file $USER_CONFIG_FILE_NAME
		
	else
		cat /dev/null > $NAGIOS_INST_PATH/$DEFAULT_CONFIG_FILE_NAME
		main_func
		write_config_file
	fi
else 
	main_func
        write_config_file
fi
}

function main_func()
{
	cfg_passive_enable_value
        cfg_active_enable_value
        cfg_hostgroup
        cfg_contactgroup
        cfg_check_interval
}

#main
echo $COLUMNS
get_installmode TTY
display_all_intru
cfg_monitor_host_ip
chk_cfg_file
