#!/bin/bash

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

function usage {
	echo "$(basename "$0") [-x] [<path>]"
	echo
	echo "Print the canonical location of the 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."
}

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 $do_xclip; then
	# echo used to strip off newline
	echo -n "$(getrealpath "$1")" | xclip
else
	getrealpath "$1"
fi
