#!/bin/bash
logfile=./NetCheck.log
logfile_tmp=./NetCheck_tmp.log

Help() {
	echo "NetCheck.sh -[M|A|C] Target(HostName or IP Address)"
	echo "  -[M|A|C]   Select TargetModule(Manager/Agent/Client)"
	echo "  Target     Set Target HostName or IP Address"
	exit 1
}

GetPortNum() {
	services=/etc/services
	# Read services file
	port=0
	if [ "$1" = "-M" ] || [ "$1" = "-m" ]; then
		port=4091
		PortName="esm-mdmserver"
	elif [ "$1" = "-A" ] || [ "$1" = "-a" ]; then
		port=4093
		PortName="esm-mdmadm"
	elif [ "$1" = "-C" ] || [ "$1" = "-c" ]; then
		port=4096
		PortName="esm-dmc-boot"
	elif [ "$1" = "-F" ] || [ "$1" = "-f" ]; then
		port=2000
		PortName="esm-ftapi"
	else
		Help
	fi

	while read line
	do
		a=($line)
		if [ "${a[0]}" != "$PortName" ]; then
			# Seach TargetModule
			continue
		fi
		port=${a[1]}
		break
	done < $services
	
	echo $port
	return 0
}

date -u >> $logfile
echo "$0" "$1" "$2" "$3" >> $logfile

if [ "$1" != "-M" ] && [ "$1" != "-A" ] && [ "$1" != "-C" ]; then
	if [ "$1" != "-m" ] && [ "$1" != "-a" ] && [ "$1" != "-c" ]; then
		Help
	fi
fi
 
if [ "$2" = "" ]; then
	Help
fi
HostName=$2
PortNum=0
ft=0
count=0

if [ "$3" = "" ]; then
	PortNum=`GetPortNum $1` 
#	GetPortNum
else
	PortNum=$3
fi
	
echo "port check process running." &>> $logfile
echo "port check process running."

echo "/usr/bin/ncat -4 -v -i 5 $HostName $PortNum" &>> $logfile
/usr/bin/ncat -4 -v -i 5 $HostName $PortNum &>> $logfile_tmp 2>&1

if [ "$1" = "-A" ] || [ "$1" = "-a" ]; then
	PortNum=`GetPortNum -F`
	ft=1
	/usr/bin/ncat -4 -v -i 5 $HostName $PortNum &>> $logfile_tmp 2>&1
fi

count=`grep -c "Idle timeout" ./NetCheck_tmp.log`
cat ./NetCheck_tmp.log &>> $logfile
rm -f ./NetCheck_tmp.log

#Check Status
if [ $count = 2 ] && [ $ft = 1 ]; then
	echo " connection success"
	echo " connection success" &>> $logfile

elif [ $count = 1 ] && [ $ft = 0 ]; then
	echo " connection success"
	echo " connection success" &>> $logfile

else
	echo " connection failed"
	echo " connection failed" &>> $logfile
fi

echo "" &>> $logfile
