/bin/sh

FTPLS=/usr/bin/ncftpls
TMPDIR=/home/tmp
PORT=${ftp_port}

EXPR=/usr/bin/expr
if [ ! -e $EXPR ]; then
	EXPR=/bin/expr
fi

if [ "$PORT" = "" ]; then
	PORT=21
fi

if [ ! -e $FTPLS ]; then
        echo "";
        echo "*** Unable to get list ***";
        echo "Please install $FTPLS by running:";
        echo "";
        echo "cd /usr/local/directadmin/scripts";
        echo "./ncftp.sh";
        echo "";
        exit 10;
fi

RANDNUM=`/usr/local/bin/php -r 'echo rand(0,10000);'`
#we need some level of uniqueness, this is an unlikely fallback.
if [ "$RANDNUM" = "" ]; then
        RANDNUM=$ftp_ip;
fi

#man ncftpls lists:
#If you want to use absolute pathnames, you need to include a literal slash, using the "%2F" code for a "/" character.
#use expr to replace /path to /%2Fpath, if needed.
CHAR1=`$EXPR substr "${ftp_path}" 1 1`
if [ "$CHAR1" = "/" ]; then
	new_path="/%2F`$EXPR substr ${ftp_path} 2 1000`"
	ftp_path=${new_path}
fi

CFG=$TMPDIR/$RANDNUM.cfg
rm -f $CFG
touch $CFG
chmod 600 $CFG
echo "host $ftp_ip" >> $CFG
echo "user $ftp_username" >> $CFG
echo "pass $ftp_password" >> $CFG

DUMP=$TMPDIR/$RANDNUM.dump
rm -f $DUMP
touch $DUMP
chmod 600 $DUMP

$FTPLS -l -f $CFG -P ${PORT} -r 1 -t 10 "ftp://${ftp_ip}${ftp_path}" 2>&1 > $DUMP
RET=$?

if [ "$RET" -ne 0 ]; then
	cat $DUMP

	if [ "$RET" -eq 3 ]; then
		echo "Transfer failed. Check the path value. (error=$RET)";
	else
		echo "${FTPLS} returned error code $RET";
	fi

else
	cat $DUMP | grep -v -e '^d' | awk '{ print $9; }'
fi

rm -f $CFG
rm -f $DUMP

exit $RET
