#!/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="$MYHOME/NewFiles/2011"
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 up to nn files to be returned back, exit successfully if there are no files
	NUMFILES=`( cd $FILEDIR ; ls -A | wc -l )`
	FILELIST=`( cd $FILEDIR ; ls -A | head --lines $MAXFILESPERSCP )`

	if [ -z "$FILELIST" ]
	then
		DOEXIT=1
	else
	
		# name the archive that the files will be
		# compressed into
		TRANSFILE=PDR78Data`date '+%Y%m%d%H%M%S'`.bz2
		FULLTRANS="$TMPFILEDIR/$TRANSFILE"

		# compress the files into an archive
		( cd "$FILEDIR" ; cat $FILELIST ) | bzip2 > "$FULLTRANS"

		# copy the archive to the target
		echo "$SCPCMD $FULLTRANS $SCPTARGET"
		$SCPCMD "$FULLTRANS" "$SCPTARGET"

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

		# 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
			( cd "$FILEDIR" ; rm $FILELIST )
		else
			exit $RETCODE
		fi

		# exit if the number of files that were available
		# to copy is less than the capacity
		if [ $NUMFILES -le $MAXFILESPERSCP ]
		then
			DOEXIT=1
		fi

	fi
done

rm "$CALLFILE"
exit 0

