#!/bin/sh

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

# -----------------------------------------------------------------------------
print_usage_and_exit() {
    echo "Usage: $this_script [OPTIONS] HOST LOCAL_FILE REMOTE_FILE"
    echo
    echo -e "Store a local file on a remote machine 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
localfile=$2
remotefile=$3

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

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

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

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