#!/bin/sh

# em_sftp.sh script for using empty to copy files via sftp based on emssh.sh v.0.5
# Copyright (C) 2005, 2006 Mikhail E. Zakharov
# Modified by Sheer Pullen for sftp 2007

sftp="sftp"
target="10.10.2.11"			# target host
login="yourloginhere"				# username (Change it!)
password="yourpasswordhere"			# password (make sure this script is not world-readable ;-)
empty="/path/to/empty"
pidfile="/tmp/empty$$.pid"
logfile="/tmp/sftp-transfers.log"

targetfile=$1

fifo_in="/tmp/empty-sftp-$$.in"			# input fifo
fifo_out="/tmp/empty-sftp-$$.out"		# output

# -----------------------------------------------------------------------------
cmd="$sftp $login@$target"
tmp="/tmp/empty.tmp"			# tempfile to store results
date=`date`

echo "Transfer starting for $targetfile at $date" >> $logfile
echo "Starting empty" >> $logfile

$empty -f -L $tmp -i $fifo_in -o $fifo_out -p $pidfile $cmd 


if [ $? = 0 ]; then

	pid=`cat $pidfile`

	if [ -w $fifo_in -a -r $fifo_out ]; then
		echo "Sending Password" >> $logfile
		$empty -w -v -i $fifo_out -o $fifo_in -t 5 assword: "$password\n"
		echo "Sending commands" >> $logfile
		
# we allow 60 seconds for the files to copy. this may need tuning

		$empty -w -v -i $fifo_out -o $fifo_in -t 60 sftp\> "put $targetfile\n"

		echo "Sending exit" >> $logfile
		$empty -w -v -i $fifo_out -o $fifo_in -t 5 sftp\> "exit\n"
		echo "Killing empty ($pid)" >> $logfile
		kill $pid
#		echo "Check results:"
#		sleep 1
#		cat $tmp
		rm -f $tmp
		rm -f $fifo_in $fifo_out $pidfile
	else
		echo "Error: Can't find I/O fifos!" >> $logfile
		return 1
	fi
else
	echo "Error: Can't start empty in daemon mode" >> $logfile
	return 1
fi

echo "Done" >> $logfile

