#!/bin/sh

# This script is designed to be called as the -k command to
# the dnscap program.
#
# Note: it sort of assumes that files can be uploaded at least
# as fast as they are generated.  If uploading is too slow you
# will end up with multiple dnscap-submit-to-oarc.sh scripts
# running simultaneously.

SSH_ID=/root/.ssh/oarc_id_dsa
SSH_BIN=/usr/bin/ssh
OARC_MEMBER=%SET THIS%
NODE_ID=%SET THIS%
REMOTE=oarc-${OARC_MEMBER}@capture.ditl.dns-oarc.net
LOGGER="logger"

calc_md5()
{
	if test -f /sbin/md5 ; then
		MY_MD5=`/sbin/md5 -q $1`
		return $?
	elif test -f /usr/bin/md5sum ; then
		MY_MD5=`/usr/bin/md5sum $1 | awk '{print $1}'`
		return $?
	fi
	echo "Cannot calculate MD5 for $1" |$LOGGER
	return 1
}

ls -l $1 |$LOGGER
gzip -9v $1 2>&1 |$LOGGER
ls -l $1.gz |$LOGGER
calc_md5 $1.gz || exit 1
echo "Sending $1.gz with MD5 $MY_MD5 to OARC" |$LOGGER

output=$($SSH_BIN -oPasswordAuthentication=no -i $SSH_ID $REMOTE pcap $NODE_ID $MY_MD5 < $1.gz)
if [ $? -eq 0 ]; then
	echo "$SSH_BIN completed successfully" |$LOGGER
	if [ "$output" = "MD5 $MY_MD5" ]; then
		echo "Remote and local MD5s match, removing $1.gz" |$LOGGER
		rm $1.gz |$LOGGER
	else
		echo "Remote MD5 ($output) does not match local MD5 ($MY_MD5)" |$LOGGER
	fi
fi

exit 0
