#!/bin/bash

. /etc/profile

NCPORT=34567

[ "$1" = "_check_netstat_" ] && {
	if ps -eo cmd | grep netcat | grep -q $NCPORT; then
		echo ACTIVE
		exit 0
	else
		echo DEAD
		exit 1
	fi
	exit 89
}

[ "$1" = "_fork_me_" ] && {
	PIPEFILE=/tmp/.nuc.stop-netcat-server.$$
	rm -f $PIPEFILE
	mkfifo $PIPEFILE
	#make it so that netcat does not stop
	exec 0<>$PIPEFILE
	#now start the netcat
	#OSFOURK-23573 V10R1.38 Prep fails from V10R1.37 on Duplex -> added -n to ignore strange DNS errors
	netcat -n -v -w 30 -p $NCPORT -l
	rm -f $PIPEFILE
	exit 0
}

[ -n "$2" ] && {
	#client
	[ -f "$1" ] || {
		echo "can not open $1"
		exit 1
	}
	netcat -v -w 2 $2 $NCPORT < "$1"
	exit $?
}

[ -n "$1" ] && {
	#start server in background
	exec 0</dev/null
	exec 1>"$1"
	exec 2>/dev/null
	setsid $0 _fork_me_ &
	#wait that processes are running
	i=0
	while [ 1 ]; do
		$0 _check_netstat_ | grep -q ACTIVE && break
		sleep 1
		i=$(($i + 1))
		#wait max 10 seconds not to block the SSHX interface
		[ $i -eq 10 ] && break
	done
	exit 0
}

echo "Error: unexpected situation."
exit 88
