#!/bin/sh

# Take note of our name as invoked
this_script=$(basename $0)

# -----------------------------------------------------------------------------
print_usage_and_exit() {
    echo "Usage: $this_script [OPTIONS] HOST REMOTE_FILE LOCAL_FILE"
    echo
    echo -e "Retrieve a remote file via SFTP"
    echo
    echo "Options:"
    echo -e "\t-v,--verbose    Verbose"
    echo -e "\t-u,--username   Username"
    echo -e "\t-p,--password   Password (if omitted user will be prompted)"
    echo
    exit 1
}

# -----------------------------------------------------------------------------
# Main script

# handle options
while :; do
    case "$1" in
        "--help"|"-h"|"-?"|"help") print_usage_and_exit ;;
        "--verbose"|"-v") verbose="--verbose" ; shift ;;
        "--username"|"-u") username=$2; shift 2;;
        "--password"|"-p") password=$2; shift 2;;
        *) break ;;
    esac
done

if [ $# -lt 2 -o $# -gt 3 ] ; then
    echo "ERROR: wrong number of parameters"
    print_usage_and_exit
fi

host=$1
remotefile=$2
localfile=$3

if [ -z ${username} ] ; then
    echo "ERROR: username must be provided"
    print_usage_and_exit
fi

if [ -z ${localfile} ] ; then
    localfile=${remotefile}
fi

if [ -z ${password} ] ; then
    user="-u ${username}"
else
    user="-u ${username}:${password}"
fi

curl ${verbose} ${user} -k sftp://${host}/${remotefile} > ${localfile}
