#! /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"\
	  "\nUtility script to get files from sftp, for example, \"$script singularity/irods_v3.3.1.sif\""
fi

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

notice `which ${script:r}` ${1}
		
export WGET_MAX_ATTEMPTS=5

FILENAME=${1}
wget --no-check-certificate -q sftp.km3net.de/${FILENAME}.md5 -O ${FILENAME:t}.md5

if [ -s ${FILENAME:t}.md5 ]; then

	WGET_ATTEMPT=$WGET_MAX_ATTEMPTS
	while [[ $WGET_ATTEMPT != 0 ]]; do
		wget -q sftp.km3net.de/${FILENAME} -O ${FILENAME:t}
		if md5sum --status -c ${FILENAME:t}.md5; then
			WGET_ATTEMPT=0
		else
			echo "WARNING: download failed, retrying"
			cat ${FILENAME:t}.md5
			md5sum ${FILENAME:t}
			let WGET_ATTEMPT=WGET_ATTEMPT-1
		fi
	done

	if md5sum --status -c ${FILENAME:t}.md5; then
		echo "file download and check OK!"
		rm ${FILENAME:t}.md5
	fi

else
	echo "WARNING: MD5 file is not avilable or empty"
	rm ${FILENAME:t}.md5
	wget -q sftp.km3net.de/${FILENAME} -O ${FILENAME:t}
fi
