#!/bin/sh
#
SCPTARGET="$1"
LOGINPORT="$2"
LOGINKEY="$3"
SCPCMD="scp"

if [ -n "$LOGINKEY" ]
then
	SCPCMD="$SCPCMD -i $LOGINKEY"
fi

if [ -n "$LOGINPORT" ]
then
	SCPCMD="$SCPCMD -P $LOGINPORT"
fi

MAXFILESPERSCP=50
MYHOME=/home/smc/roots/200_PPPHost
CALLFILE="$MYHOME/callinTime"
FILEDIR="/mnt/XDATA/MAM/pending"
FILEDONE="/mnt/XDATA/MAM/sent"
TMPFILEDIR="$MYHOME/workspace"
DOEXIT=0

# plan to call back sooner in case of error
echo 600 > "$CALLFILE"

# calls repeatedly until successful with all files or an
# error occurs
while [ $DOEXIT -eq 0 ]
do
	# get the next file to send back
	FILENAME=`( cd $FILEDIR ; ls -A *bz2 | head --lines 1 )`

	if [ -z "$FILENAME" ]
	then
		DOEXIT=1
	else
		# copy the next file to the target
		echo "$SCPCMD $FILEDIR/$FILENAME $SCPTARGET"
		$SCPCMD "$FILEDIR/$FILENAME" "$SCPTARGET"

		# save the return code from the scp operation and
		# delete the temporary archive file
		RETCODE="$?"

		# if the scp was successful, remove the files
		# that went into the archive (this could be
		# modified to move the files to long term storage);
		# otherwise, exit with an error (tries again later)
		if [ "$RETCODE" -eq 0 ]
		then
			mv "$FILEDIR/$FILENAME" "$FILEDONE/$FILENAME"
		else
			echo "reportGPS: scp returned code $RETCODE"
			exit $RETCODE
		fi
	fi
done

rm "$CALLFILE"
echo "reportGPS: all files transferred"
exit 0

