#! /usr/bin/env zsh
## ------------------------------------------------------------------------------------------
##
##                         Utils to get and upload files on sftp
##
## ------------------------------------------------------------------------------------------

#!/bin/zsh
script=${0##*/}

source ${0%${script}}ulib.sh

if do_usage $*; then
    usage "$script  file_path/filename sftp_path"\
	  "\nUtility script to upload files on sftp, for example, \"$script data.root user/tmp\""
fi

case $# in
    2)  ;;
    *)  fatal "Wrong number of arguments."
esac

notice `which ${script:r}` ${1} ${2}
		
FILENAME=${1}
SFTPPATH=${2}
wget -q sftp.km3net.de/${SFTPPATH}/${FILENAME:t} -O ${FILENAME:t}_tmp

if [ -s ${FILENAME:t}_tmp ]; then
	rm ${FILENAME:t}_tmp
	fatal "File ${FILENAME:t} is already on sftp server, quitting."
fi
rm ${FILENAME:t}_tmp

if [ -f ${FILENAME} ]; then
	md5sum ${FILENAME} > ${FILENAME:t}.md5
	echo "Enter KM3NeT SFTP password"
	lftp sftp://km3net@sftp.km3net.de -e "mkdir $SFTPPATH; cd $SFTPPATH; put $FILENAME ${FILENAME:t}.md5; bye"
	rm ${FILENAME:t}.md5
	echo "Checking the uploaded file"
	mkdir _sftpgettmp
	cd _sftpgettmp
	sftpget $SFTPPATH/${FILENAME:t}
	cd ../
	rm -rf _sftpgettmp
else
	fatal "File ${FILENAME} not found locally"
fi
