#!/bin/bash


function usage {
    echo "$(basename "$0") [-x] [<path>]"
    echo
    echo "Print an scp-able username@hostname:path specified (or \`.' if not"
    echo "specified. If \`-x' is passed, use xclip(1) to copy the path to"
    echo "the primary selection instead of printing it."
}

function getrealpath {
	local p=${1:-.}
	if command -v python &>/dev/null; then
		python -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$p"
	elif command -v perl &>/dev/null; then
		perl -MCwd -le 'print Cwd::realpath($ARGV[0])' "$p"
	else
		readlink -f "$p"
	fi
}

function getscppath {
    printf "%q\n" "$(id -un)@$(hostname -f):$(getrealpath "$1")"
}

do_xclip=false

case $1 in
    -h)
        usage
        exit 0
        ;;
    -x)
        if command -v xclip &> /dev/null; then
            do_xclip=true
            shift
        else
            echo "xclip not found" >&2
            exit 255
        fi
        ;;
    -*)
        echo "Invalid option \`$1'" >&2
        usage
        exit 2
        ;;
esac

if [[ ${0##*/} == scpxclip ]]; then
    do_xclip=true
fi

if $do_xclip; then
    # echo used to strip off newline
    echo -n "$(getscppath "$1")" | xclip
else
    getscppath "$1"
fi
