#!/bin/ksh
#This shellscript is tcp_sender.
#Read input from the program named as a commmand line argument.
#The first character of the program's name is the program's "port number".
#Split the input input into "TCP segments" of at most 6 bytes each.
#The first three bytes will be decimal digits.
#The first byte is the length of the segment (at most 6).
#The second byte is the port number, taken from the command line argument.
#The third byte is the sequence number.
#This leaves at most 3 bytes for the data.  The Maximum Segment Size (MSS)
#is therefore 3.
#Sample use: tcp_sender 0_host/0_progname_tcp

if [[ $# -ne 1 ]]
then
	echo $0: requires program name as command line argument 1>&2
	exit 1
fi

if [[ ! -x $1 ]]
then
	echo $0: sorry, I have no permission to execute $1 1>&2
	exit 2
fi

if [[ ! ${1##*/} == [0-9]* ]]
then
	echo $0: program name $1 must begin with a digit 1>&2
	exit 3
fi

port=`echo ${1##*/} | sed 's/\(.\).*/\1/'`
$1 > /tmp/$$
let sequence_number=0

while [[ -s /tmp/$$ ]]
do
	if [[ $sequence_number -ge 10 ]]
	then
		echo $0: toy can send no more than 10 segments 1>&2
		exit 4
	fi

	chopoff 3 /tmp/$$ > /tmp/$$.data
	length=`wc -c < /tmp/$$.data | awk '{print $1}'`

	#Output the three-byte TCP header.
	#The '\c' tells echo not to output a newline.
	echo $((length + 3))'\c'
	echo $port'\c'
	echo $sequence_number'\c'

	cat /tmp/$$.data
	rm /tmp/$$.data
	let ++sequence_number
done

rm /tmp/$$
exit 0