#!/bin/bash

ATFTP=../atftp
ATFTPD=../atftpd
HOST=localhost
PORT=2001

# verify that atftp and atftpd are runnable
if [ ! -x $ATFTP ]; then
	echo "$ATFTP not found"
	exit 1
fi
if [ ! -x $ATFTPD ]; then
	echo "$ATFTPD not found"
	exit 1
fi

# start a server
if [ $PORT != 69 ]; then
    echo "Starting atftp server on port $PORT"
    $ATFTPD --daemon --no-fork --logfile=/dev/stdout --port=$PORT --verbose=6 >./atftpd.log &
    ATFTPD_PID=$!
    if [ $? != 0 ]; then
	echo "Error starting server"
	exit 1
    fi
fi

# make sure we have /tftpboot with some files
if [ ! -d /tftpboot ]; then
	echo "create /tftpboot before running this test"
	exit 1
fi
READ_0=READ_0.bin
READ_511=READ_511.bin
READ_512=READ_512.bin
READ_2K=READ_2K.bin
READ_BIG=READ_BIG.bin
WRITE=write.bin

echo -n "Creating test files ... "
touch /tftpboot/$READ_0
touch /tftpboot/$WRITE; chmod a+w /tftpboot/$WRITE
dd if=/dev/urandom of=/tftpboot/$READ_511 bs=1 count=511 2>/dev/null
dd if=/dev/urandom of=/tftpboot/$READ_512 bs=1 count=512 2>/dev/null
dd if=/dev/urandom of=/tftpboot/$READ_2K bs=1 count=2048 2>/dev/null
dd if=/dev/urandom of=/tftpboot/$READ_BIG bs=1 count=51111 2>/dev/null
echo "done"

function check_file() {
	if cmp $1 $2 ; then
		echo OK
	else
		echo ERROR
	fi
}

function test_get_put() {
    echo -n "Testing get, $1 ($2)... "
    $ATFTP $2 --get -r $1 -l out.bin $HOST $PORT 2>/dev/null
    check_file /tftpboot/$1 out.bin
    echo -n "Testing put, $1 ($2)... "
    $ATFTP $2 --put -r $WRITE -l out.bin $HOST $PORT 2>/dev/null
    # because in some case the server may not have time to close the file
    # before the file compare.
    sleep 1
    check_file /tftpboot/$WRITE out.bin
}

#
# test get and put
#

test_get_put $READ_0
test_get_put $READ_511
test_get_put $READ_512
test_get_put $READ_2K
test_get_put $READ_BIG

# testing for blocksize
echo ""
echo "Testing blksize option limit..."
echo -n " minimum ... "
$ATFTP --blksize=7 -d --get -r $READ_2K -l /dev/null $HOST $PORT 2> out
if grep -q "<Failure to negotiate RFC1782 options>" out; then
    echo OK
else
    echo ERROR
fi
echo -n " maximum ... "
$ATFTP --blksize=65465 -d --get -r $READ_2K -l /dev/null $HOST $PORT 2> out
if grep -q "<Failure to negotiate RFC1782 options>" out; then
    echo OK
else
    echo ERROR
fi
test_get_put $READ_BIG "-b 8"
test_get_put $READ_BIG "-b 1428"
test_get_put $READ_BIG "-b 65464"

# testing fot tsize
echo ""
echo -n "Testing tsize option... "
$ATFTP --tsize -d --get -r $READ_2K -l /dev/null $HOST $PORT 2> out
TSIZE=`grep "OACK <tsize:" out | sed -e "s/[^0-9]//g"`
if [ "$TSIZE" != "2048" ]; then
    echo "Server report $TSIZE bytes but it should be 2048"
else
    echo "OK"
fi

# testing timeout ????

# testing multicast
#echo ""
#echo -n "Testing multicast option  "
#for i in `seq 10`; do
#    echo -n "."
#    atftp --blksize=8 --multicast -d --get -r $READ_BIG -l out.$i.bin $HOST $PORT 2> /dev/null&
#done
#echo "OK"

if [ $PORT != 69 ]; then
    kill $ATFTPD_PID
fi

rm -f out*
