#!/bin/sh
#
#ident	"@(#)ftpstress.sh	1.7	04/12/15 SMI"
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# FTP stress test - creates and transfers files, checking for corruption

# Setup pid-specific directories
# allows multiple instances

Setup()
{
	total_bytes=0
        mkdir $local_ftpdir
	if [ $? -ne 0 ]; then
       		echo "!ERROR: Could not create local directory."
        	exit 1
	fi
}

# create 7 null files, each 10 times bigger than the last, from 0.5k up

Create_Files()
{
	fileset_size=0
	echo "Creating fileset for transfer."
        x=1
        y=1
        while [ $x -ne 8 ] ; do
		dd if=`df -k / | tail -1 | awk '{print $1}'` of=$local_ftpdir/file$x count=$y 2>/dev/null
		if [ $? -ne 0 ]; then
			echo "!ERROR: Could not create local file for FTP."
			Cleanup
			exit 1
		fi
		fileset_size=`expr $fileset_size + $y`
		x=`expr $x + 1`
		y=`expr $y \* 10`
        done
	# Convert blocks to bytes
	fileset_size=`expr $fileset_size \* 512`
}

Do_FTP()
{ 
	ftp -i -n $dest << __EOF__
        user anonymous anonymous 
        lcd $local_ftpdir
        mkdir $remote_ftpdir
	cd $remote_ftpdir
        bin
        put file1
        put file2
        put file3
        put file4
        put file5
        put file6
        put file7
        get file1 nfile1
        get file2 nfile2
        get file3 nfile3
        get file4 nfile4
        get file5 nfile5
        get file6 nfile6
        get file7 nfile7
	delete file1
	delete file2
	delete file3
	delete file4
	delete file5
	delete file6
	delete file7
	cd ..
	rmdir $remote_ftpdir
        bye
__EOF__
	if [ $? -ne 0 ]; then
        	echo "!ERROR: FTP failed."
		Cleanup
                exit 1
	fi

	total_bytes=`expr $total_bytes + $fileset_size`
	date
	echo "FTP succeeded: Transmitted $total_bytes bytes so far."
}

Check_For_Errors()
{
	echo "Checking files for corruption."
	x=1
        while [ $x -ne 8 ] ; do
 	       cmp $local_ftpdir/file$x $local_ftpdir/nfile$x >/dev/null 2>&1
               if [ $? -ne 0 ]; then
                        echo "!ERROR: Bad $1 checksum between file$x and nfile$x."
			Cleanup
                        exit 1
               fi
	       x=`expr $x + 1`
        done
}

Cleanup()
{
	rm -rf $local_ftpdir
}

# Main program

dest=$1

ping $dest > /dev/null 2>/dev/null

if [ $? -ne 0 ]; then
        echo "!ERROR: Ping error: Host \"$dest\" not found or not responding."
        exit 1
fi

echo "Beginning ftpstress"
echo "Running time: $RUNTIME seconds."
sleep $RUNTIME &
sleepid=$!

Setup
Create_Files

if [ ! -d /proc/$sleepid ]
then
	echo "!ERROR: RUNTIME is too short. Set longer RUNTIME."
        Cleanup
	 exit 1
fi

while [ -d /proc/$sleepid ] ; do
	starttime=`../../../../prgs/time_sec`

	echo "Initiating file transfer..."
	Do_FTP
	Check_For_Errors

        endtime=`../../../../prgs/time_sec`
        echo "LOOPTIME: `expr $endtime - $starttime`"
done

Cleanup 
echo "!PASS: No errors detected in FTP."

