#! /bin/bash

configFile=NEWUDPSRVR.INI
tempFile=TEMP.INI
exeName=./UDPApp
StatsFile=UDP_STATISTICS.txt
procIdFile=PROCESS_ID.cfg
sleepTime=10
ret=0
checkProcess()
{
ps -uxh | grep $exeName | grep -v grep &>/dev/null
if [ $? -eq 0 ]
then
	echo "Cannot proceed, please stop all UDP Server first."
	echo "Press Enter key to go back to Main Menu..."
	read tempVar
	continue
fi
}

checkProcessForMod()
{
ps -uxh | grep "$exeName $1" | grep -v grep &>/dev/null
if [ $? -eq 0 ]
then
	echo ""
	echo "Cannot modify record no. $1, since UDP Server instance no. $1 is running."
	echo "Press Enter key to go back to Main Menu..."
	read tempVar
	continue
fi
}


formatDisplayConfig()
{
	COUNT=0
	HEADERREC=0
	DELIMITER=","
	CONF_FILE_LINE=""
	FIRST_LINE_TEXT="ID"
	OUT_STR=""

	while read CONF_FILE_LINE
	do 
		if [ -z ${CONF_FILE_LINE} ]
		then 
			continue
		fi

		if [ $HEADERREC -eq 0 ]
		then
			OUT_STR=$FIRST_LINE_TEXT$DELIMITER$CONF_FILE_LINE
			HEADERREC=$((HEADERREC+1))	
			echo $OUT_STR
			continue
		fi
		
		COUNT=$((COUNT+1))
		OUT_STR=$COUNT$DELIMITER$CONF_FILE_LINE
		echo $OUT_STR

	done < ${configFile}	
}

validateHeaderInConfig()
{
	clear
	formatDisplayConfig
	recordCount=`cat $configFile | wc -l`
	headerCount=`cat $configFile | egrep "MKT|RECEIVER_IP|RECEIVER_PORT|SENDER_IP|SENDER_PORT|LOCAL_IP_TO_HOST|LOCAL_IP_TO_NEAT|MKT_DATA_FLAG"| wc -l `

	if [ $recordCount -eq 1 -a $headerCount -eq 1 ]
	then
		echo ""
		echo "No config present in file, hence cannot proceed. Please Add configs first !"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue
	elif [ $headerCount -ne 1 ]
	then
		echo ""
		echo "Incorrect header in config file, delete the config file ($configFile) manually and then Add configs again from Main menu"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue		
	fi

}


dispStats()
{
	ps -uxh | grep $exeName | grep -v grep &>/dev/null
	if [ $? -ne 0 ]
	then
		echo ""
		echo "No UDP Servers running so cannot show statistics."
		echo "Press Enter key to go bak to Main Menu..."
		read tempvar
		continue	
	fi
		
        clear

while [ 1 ]
do
        > $StatsFile
	echo "INSTANCE_NO, RECEIVED_COUNT, SENT_COUNT, STATUS" >> $StatsFile
        echo ""
        echo ""
	ps -uxh | grep $exeName | grep -v grep &>/dev/null
        if [ $? -ne 0 ]
        then
                echo "No UDP Servers running currently !"
                echo ""
                echo "Press Enter key to go back to Main Menu..."
                read tempvar
                break
        fi
	trap 'break' SIGINT
	ps -uxh | grep $exeName | grep -v grep | tr -s " " | cut -d" " -f2 > $procIdFile

        for i in `cat $procIdFile`
        do
                #Sending SIGUSR1 to running instances
                kill -10 $i &>/dev/null
        done

	clear
        echo "UDP Server Statistics : "

        cat $StatsFile
        echo ""
        echo ""
        echo "Stats will keep on updating after every $sleepTime secs..."
        echo "Press Ctrl + C to go back to main menu..."
        rm $procIdFile
        sleep $sleepTime
done
}

mainMenu()
{
	break
}


startUDP()
{
        clear
        if [ -f $configFile ]
        then
                echo "Config file present..."   
        else
		echo "Configuration not present. Please add configuration first to start UDP Server."
                echo "Press Enter key to go back to Main Menu..."
                read tempvar
                continue
        fi

	clear
	recordCount=`cat $configFile| wc -l`
	recordCount=`expr $recordCount - 1`

	if [ $recordCount -le 0 ]
	then
		echo "No records present in Config file to start UDP Server."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi
	#first kill all exe's

	ps -uxh  | grep $exeName | grep -v grep &>/dev/null
	if [ $? -eq 0 ]
	then
		echo "Some UDP Servers already running. Stop and then Start again."
		echo ""
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi
	
	echo "Starting all UDP Servers, please wait..."
	for ((i = 1 ; i <= $recordCount ; i++))
	do
		$exeName $i & > /dev/null
	done
	
	for ((i = 1 ; i <= $recordCount ; i++))
	do
                ps -uxh | grep "$exeName $i" | grep -v grep &>/dev/null
                if [ $? -ne 0 ]
                then
                        echo ""
                        echo "UDP Server instance no. $i failed. Check Log file !"
			echo "Press Enter key to go back to Main Menu..."
			read tempVar
			break
                fi
	done
	clear
	echo "Started all UDP Servers Successfully !"
	echo ""
	echo "Press Enter key to go back to Main Menu..."
	read tempVar
}

startSingleUDP()
{
	if [ ! -f $configFile ]
        then
		echo "Configuration not present. Please add configuration first to start UDP Server."
                echo "Press Enter key to go back to Main Menu..."
                read tempvar
                continue
        fi
	
	validateHeaderInConfig
        recordCount=`cat $configFile | wc -l`
	recordCount=`expr $recordCount - 1`

	echo "Enter the UDP Server instance no. to be started:"
	read instanceNo
	
	if [[ ! $instanceNo =~ ^[1-9]*[0-9]$ ]]
	then
		echo "Not a valid UDP Server instance no. Allowed values [1-Max]"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	elif [ $instanceNo -le 0 ]
        then
                echo "Instance no cannot be less than or equal to 0"
                echo "Press Enter key to go back to Main Menu..."
                read tempVar
                continue
	elif [ $instanceNo -gt $recordCount ]
	then
		echo ""
		echo "Only ($recordCount) config records present in Config file ($configFile), so cannot proceed !"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

	ps -uxh | grep "$exeName $instanceNo" | grep -v grep &>/dev/null
	if [ $? -eq 0 ]
	then
		echo ""	
		echo "UDP Server instance no. $instanceNo already running."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi	

	#Starting single UDP
	$exeName $instanceNo > /dev/null &
	sleep 0.5
	ps -uxh | grep "$exeName $instanceNo" | grep -v grep &>/dev/null
	if [ $? -eq 0 ]
	then
		echo ""
		echo "UDP Server instance no. $instanceNo started successfully !"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	else
		echo ""
		echo "UDP Server instance no. $instanceNo startup failed !"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

}

stopSingleUDP()
{
	if [ ! -f $configFile ]
	then
		echo "Configuration not present. Please add configuration first to start UDP Server."
		echo "Press Enter key to go back to Main Menu..."
		read tempvar
		continue
	fi

	validateHeaderInConfig
	recordCount=`cat $configFile | wc -l`
	recordCount=`expr $recordCount - 1`
	echo "Enter the UDP Server instance no. to be stopped:"
	read instanceNo
	if [[ ! $instanceNo =~ ^[1-9]*[0-9]$ ]]
	then
		echo ""
		echo "Not a valid UDP Server instance no. Allowed values [1-Max]"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

	if [ $instanceNo -gt $recordCount ]
	then
		echo ""
		echo "Only ($recordCount) config records present in Config file ($configFile), so cannot proceed !"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
        fi
	
	ps -uxh | grep "$exeName $instanceNo" | grep -v grep &>/dev/null
	if [ $? -ne 0 ]
	then
		echo ""
		echo "UDP Server instance no. $instanceNo is not running."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

	#Stopping single UDP
	Id=`ps -uxh | grep "$exeName $instanceNo" | grep -v grep | tr -s " " | cut -d" " -f2`
	kill -15 $Id &>/dev/null
	ps -uxh | grep "$exeName $instanceNo" | grep -v grep &>/dev/null
	if [ $? -ne 0 ]
	then
		clear
		echo ""
		echo "Stopped instance no. $instanceNo successfully !"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	else
		echo ""
		echo "Stopping instance no. $instanceNo failed."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue		
	fi
}



stopUDP()
{
	clear
	ps -uxh | grep $exeName | grep -v grep &>/dev/null
	if [ $? -ne 0 ]
	then
		echo "Currently no UDP Servers are running."
		echo ""
		echo "Press Enter key to go back to Main Menu..."
		read tempvar
		continue
	fi
	
	ps -uxh | grep $exeName | grep -v grep | tr -s " " | cut -d" " -f2 > $procIdFile
	
	for i in `cat $procIdFile`
	do
		kill -15 $i & > /dev/null
	done
	
	sleep 1
	clear
	echo "Stopped all UDP Servers Successfully !"
	echo ""
	rm $procIdFile
	echo "Press Enter key to go back to Main Menu..."
	read tempVar
}


dispConfig()
{
	clear
        if [ -f $configFile ]
        then
                echo "Config file present..."
        else
		echo ""
		echo "Configuration not present. Please add new configuration first from Main Menu."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
        fi


	clear
	configCount=`cat $configFile | wc -l`
	formatDisplayConfig
	if [ $configCount -eq 1 ]
	then 
		echo ""
		echo "No records found in Config file (NEWUDPSRVR.INI)"
	fi
	echo "Press Enter key to go back to Main Menu..."
	read tempVar
}


validateIP()
{
	IP=$1
	if [[ ! $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]
	then
		echo "Incorrect IP format provided"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	else
		echo $IP > temp.txt
		        maxfields=`awk -F"." '{print NF}' temp.txt`
			for ((i = 1 ; i <= $maxfields ; i++))
			do
				ipValue=`awk -v var="$i" -F"." '{print $var}' temp.txt`
				if [ $ipValue -lt 0 -o $ipValue -gt 255 ]
				then
					ret=1
				fi
			done
	fi
	rm temp.txt
}

validateMarket()
{
	if [ ! "$1" = "CM" -a ! "$1" = "FO" -a ! "$1" = "CD" -a ! "$1" = "SLBM" -a ! "$1" = "CO" -a ! "$1" = "cm" -a ! "$1" = "fo" -a ! "$1" = "cd" -a ! "$1" = "slbm" -a ! "$1" = "co" ]
        then
                echo "Invalid Market segment provided !"
                echo "Press Enter key to go back to Main Menu..."
                read tempVar
		continue
        fi
}

validateFlag()
{
	if [ ! "$1" = "Y" -a ! "$1" = "N" -a ! "$1" = "y" -a ! "$1" = "n" ]
	then
		echo "Invalid MktData flag provided. MktData flag can be only Y or N"
		echo "Press Enter key to go back to Main Menu..."
                read tempVar
		continue
	fi
}

validatePort()
{
	if [[ ! $1 =~ ^[0-9]{1,5}$ ]]
	then
		echo "PORT ID entered is not correct. PORT ID can be a max of 5 digits [0-9]"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

	if [ $1 -le 0 ]
	then
		echo "PORT ID entered cannot be less than or equal to 0"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi
}

addConfig()
{
	if [ -f $configFile ]
	then
		echo "Config file present..."	
	else
		echo "Config File (NEWUDPSRVR.INI) not present, hence creating one..."
		touch $configFile
		echo "MKT,RECEIVER_IP,RECEIVER_PORT,SENDER_IP,SENDER_PORT,LOCAL_IP_TO_HOST,LOCAL_IP_TO_NEAT,MKT_DATA_FLAG" >> $configFile
	fi
	
	clear
	echo "Enter Market Segment (CM/FO/CD/SLBM/CO)"
	read mktSegment
	validateMarket $mktSegment
		
	echo "Enter Receiver IP <XXX.XXX.XXX.XXX>"
	read recvMulticastIP
	ret=0
	validateIP $recvMulticastIP
	if [ $ret -ne 0 ]
	then
		echo "Invalid data in IP address"
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
	fi

	echo "Enter Receiver Port (Max 5 digits)"
	read recvMulticastPort
	validatePort $recvMulticastPort	

	echo "Enter Sender IP <XXX.XXX.XXX.XXX>"
	read sendMulticastIP
	ret=0
	validateIP $sendMulticastIP
	if [ $ret -ne 0 ]
        then
                echo "Invalid data in IP address"
                echo "Press Enter key to go back to Main Menu..."
                read tempVar
                continue
        fi

	echo "Enter Sender Port (Max 5 digits)"
	read sendMulticastPort
	validatePort $sendMulticastPort

	echo "Enter Local IP Address towards Host  <XXX.XXX.XXX.XXX>"
	read localIPToHOST
	ret=0
	validateIP $localIPToHOST
	if [ $ret -ne 0 ]
        then
                echo "Invalid data in IP address"
                echo "Press Enter key to go back to Main Menu..."
                read tempVar
                continue
        fi

	echo "Enter Local IP Address towards NEAT  <XXX.XXX.XXX.XXX>"
	read localIPToNEAT
	ret=0
	validateIP $localIPToNEAT
	if [ $ret -ne 0 ]
        then
                echo "Invalid data in IP address"
                echo "Press Enter key to go back to Main Menu..."
                read tempVar
                continue
        fi	

	#Setting New Market Data Flag as N
	newMktDataFlag="N"
	validateFlag $newMktDataFlag
	
	# Convert MKT segment to upper case, to be stored in config file
	mktSegment=$(echo $mktSegment| tr 'a-z' 'A-Z')
	newMktDataFlag=$(echo $newMktDataFlag| tr 'a-z' 'A-Z')
	echo "$mktSegment,$recvMulticastIP,$recvMulticastPort,$sendMulticastIP,$sendMulticastPort,$localIPToHOST,$localIPToNEAT,$newMktDataFlag" >> $configFile
	echo "New configuration added successfully ... !!!"
        echo "Press Enter key to go back to Main Menu..."
	read tempVar
}

delConfig()
{
        if [ ! -f $configFile ]
        then
                echo "Configurations not present. Please add new configuration from Main Menu."
		echo "Press Enter key to go back to Main Menu..."
		read tempVar
		continue
        fi

	checkProcess	
	formatDisplayConfig
	echo ""
	recordCount=`cat $configFile | wc -l`
	if [ $recordCount -eq 1 ]
	then
		echo "Configuration record not present, hence cannot perform delete operation"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue
	fi
	echo "Enter the instance no. to be deleted from above"
	read delCount
	
	if [[ ! $delCount =~ ^[0-9]*[0-9]$ ]]
	then
		echo "Entered value is not valid, only numbers allowed [1-9] !"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue
	fi


	if [ $delCount -ge $recordCount ]
	then
		echo "Entered value ($delCount) exceeds max records (`expr $recordCount - 1`)"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue
	elif [ $delCount -lt 1 ]
	then
		echo "Entered value ($delCount) cannot be less than 1"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
		continue
	fi
	
	#Adjustment for header record
	delCount=`expr $delCount + 1`
	
	#Deleting the required config
	sed -i "${delCount}d" $configFile
        
        echo "Record Deleted Successfully."
	echo "Press Enter key to go back to menu..."
	read tempVar
	
}

modConfig()
{
	if [ ! -f $configFile ]
	then
		echo "Configurations not present. Please add new configuration from Main Menu."
		echo "Press Enter key to go back to Main Menu ..."
		read tempvar
		continue
	fi

	clear
	recordCount=`cat $configFile | wc -l`
	formatDisplayConfig
        if [ $recordCount -eq 1 ]
        then
		echo ""
		echo "Configuration Record not present, hence can not perform Modify operation."
                echo "Press Enter key to go back to Main Menu ..."
		read tempVar
		continue
        fi

	echo "Enter the instance no. to be modified from above"
	read modCount

        if [[ ! $modCount =~ ^[0-9]*[0-9]$ ]]
        then
		echo ""
                echo "Entered value is not valid, only numbers allowed [0-9] !"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
                continue
        fi

        if [ $modCount -ge $recordCount ]
        then
		echo ""
                echo "Entered value ($modCount) exceeds max records (`expr $recordCount - 1`)"
		echo "Press Enter key to go back to Main Menu...."
		read tempVar
                continue
        elif [ $modCount -lt 1 ]
        then
		echo ""
                echo "Entered value ($modCount) cannot be less than 1"
		echo "Press Enter key to go back to Main Menu...."
                read tempVar
                continue
        fi

		
	
	#check specific exe is up or not
	checkProcessForMod $modCount
	
	#Adjustment for header record
	modCount=`expr $modCount + 1`

while [ 1 ]
do	
	clear
	echo "*******************************"
	echo "      MODIFICATION MENU"
	echo "*******************************"
	echo "1. MARKET_SEGMENT"
	echo "2. RECV_MULTICAST_IP"
	echo "3. RECV_MULTICAST_PORT"
	echo "4. SEND_MULTICAST_IP"
	echo "5. SEND_MULTICAST_PORT"
	echo "6. LOCAL_IP_TO_HOST"
	echo "7. LOCAL_IP_TO_NEAT"
	echo "8. Back to Main Menu"
	echo "*******************************"
	echo "Enter which field is to be modified [1-9]"
	read updateField
	

	if [[ ! $updateField =~ ^[1-8]$ ]]
	then
		echo "Entered value is not valid, only numbers allowed [1-8] !"
		echo "Press Enter key to go back to Updation menu...."
                read tempVar
		continue
	fi
	
	if [ $updateField -lt 1 -o $updateField -gt 8 ]
	then
		echo "Wrong input provided. Allowed values [1-8]"
		echo "Press Enter key to go back to Updation menu...."
                read tempVar
		continue
	fi

	if [ $updateField -eq 8 ]
	then
		break
	fi
	
	echo "Enter new value for selected field"
	read updateValue

	if [ $updateField -eq 1 ]
	then
		validateMarket $updateValue
		updateValue=$(echo $updateValue| tr 'a-z' 'A-Z')
	elif [ $updateField -eq 2 -o $updateField -eq 4 -o $updateField -eq 6 -o $updateField -eq 7 ]
	then
		validateIP $updateValue	
	elif [ $updateField -eq 3 -o $updateField -eq 5 ]
	then
		validatePort $updateValue
	fi

	awk -v c="$updateField" -v r="$modCount" -v value="$updateValue" -F, 'BEGIN{OFS=","}; NR != r; NR == r {$c = value; print}' $configFile > $tempFile
	mv $tempFile $configFile
	echo "Modified record successfully !"
	echo "Press Enter key to go back to updation menu..."
	read tempVar	
done
}

#MAIN FUNCTION START
while [ 1 ]
do
	clear
	echo "******************************"
	echo "   UDP SERVER MAIN MENU	      "
	echo "******************************"
	echo "1.  Add New Configuration"
	echo "2.  Delete Configuration"
	echo "3.  Modify Configuration"
	echo "4.  Display All Configurations"
	echo "5.  Display Statistics"
	echo "6.  Start All UDP Server"
	echo "7.  Stop All UDP Server"
	echo "8.  Start Single UDP Server"
	echo "9.  Stop Single UDP Server"
	echo "10. Exit"
	echo "******************************"
	echo "Enter a value to continue [1-10]"
	read input
	i=$input

	case $input in
		1) addConfig
		;;
		2) delConfig
		;;
		3) modConfig
		;;
		4) dispConfig
		;;
		5) dispStats
		;;
		6) startUDP
		;;
		7) stopUDP
		;;
		8) startSingleUDP
		;;
		9) stopSingleUDP
		;;
		10)exit 0
		;;
		*)echo "Incorrect input"
		read tempvar
		;;
	esac
done
