#!/bin/sh
port="-P 7822"
user=redantig
server=kuu.se

# If no args, show usage
if [ $# -lt 1 ];then
    echo "Usage: $0 localsrc [remotedst]"
    echo "Usage: $0 localsrc1 [localsrc2 ... ] remotedstdir"
    echo "Usage: $0 localsrc1 [localsrc2 ... ] . "'          ' \<--- Use '.' for remote '$HOME' dir
    exit
fi

# If only 1 arg, use same name for src (local) and dst (remote) (local filename have subdirectory path, which also is used on remote)
if [ $# -eq 1 ];then
    f="$1"
    echo scp -r ${port} "${f}" ${user}@${server}:"${f}"
    scp -r ${port} "${f}" ${user}@${server}:"${f}"
else
    if [ $# -eq 2 ];then
        # If 2 args, copy file to remote, using second arg as dst filename (both src and dst may include subdirectory paths)
        src="$1"
        dst="$2"
        echo scp -r ${port} "${src}" ${user}@${server}:"${dst}"
        scp -r ${port} "${src}" ${user}@${server}:"${dst}"
        shift
    else
        # If 3 or more args, copy files to remote, using last arg as dstdir (must be an existing remote directory)
        # Get last argument in $@ into a variable, and remove it from $@
        # http://www.unixguide.net/unix/faq/2.12.shtml
        # Get positional parameters ($@) as a variable list
        # ================================================================================
        N=1
        for i;do
            eval argv$N=\$i
            N=`expr $N + 1`
        done
        # Reverse $@
        argv=
        for i
        do
            eval argv$#=\$i
            argv="\"\$argv$#\" $argv"
            shift
        done
        eval set x "$argv"
        shift
        lastarg=$1
        shift
        # Reverse again
        argv=
        for i
        do
            eval argv$#=\$i
            argv="\"\$argv$#\" $argv"
            shift
        done
        eval set x "$argv"
        shift
        # ================================================================================
        # dstdir is now in ${lastarg}, and removed from $@
        # Add '/' if missing
        dstdir=`echo "${lastarg}"| sed 's=/*$=/='`
        # Check if dstdir exists
        exists=`ra "test -d ${dstdir} && echo EXISTS"`
        if [ -z "${exists}" ];then
            echo "Error: remote directory '${user}@${server}:${dstdir}' does not exist."
            exit
        fi
        echo scp -r ${port} "$@" ${user}@${server}:"${dstdir}"
        scp -r ${port} "$@" ${user}@${server}:"${dstdir}"
    fi
fi


echo
echo "Just copied local-to-remote by mistake? Try this:"
echo
printf "ra rm "
for i
do
    printf "%s " "${dstdir}$i"
done
echo
echo
