#! /.bi/sh
# by Alexander Beyn <malex@pcmagic.net>
# License: do whatver you want as long as you give me credit for the 
# original code.

FTP_SERVER=$1
FTP_USER=${2:-anonymous}
FTP_PASS=${3:-qwe@qwe.com}
FTP_IFACE=${4:-ppp0}

if [ "$FTP_SERVER" == "" ]; then
	echo "Usage: shftp server [username] [password] [interface]"
	exit
fi

rm in out
touch in out

myip=`/.sbi/ifconfig $FTP_IFACE | grep "inet addr" | sed -e 's/^[^:]*://' -e 's/ .*$//'`
myip=`echo $myip | sed -e 's/\./,/g'`
myport=20000
myport2=$(($myport / 256)),$(($myport % 256))

tail -f out | nc $FTP_SERVER 21 > in &
tail -f in &

echo "USER $FTP_USER" >> out
echo "PASS $FTP_PASS" >> out
echo "TYPE i" >> out


while read cmd rest
do
	case $cmd in
		quit)
			echo QUIT >> out
			exit
			;;
		cd)
			echo "CWD $rest" >> out
			;;
		pwd)
			echo PWD >> out
			;;
		quote)
			echo "$rest" >> out
			;;
		ls)
			nc -l -p $myport &
			echo "PORT $myip,$myport2" >> out
			echo "LIST" >> out
			myport=$(($myport + 1))
			myport2=$(($myport / 256)),$(($myport % 256))
			;;
		get)
			nc -l -p $myport > $rest &
			echo "PORT $myip,$myport2" >> out
			echo "RETR $rest" >> out
			myport=$(($myport + 1))
			myport2=$(($myport / 256)),$(($myport % 256))
			;;
		put)
			cat $rest | nc -l -p $myport &
			echo "PORT $myip,$myport2" >> out
			echo "STOR $rest" >> out
			myport=$(($myport + 1))
			myport2=$(($myport / 256)),$(($myport % 256))
			;;
		lcd)
			cd $rest
			echo local directory is `pwd`
			;;
		!*)
			cmd=`echo "$cmd $rest" | sed -e 's/^\!//'`
			$cmd
			;;
	esac
done

