#!/bin/sh

set -e

absolute_parent_of_current_script() {
	show_physical_path "$(dirname "$0" | sed -e "s|^\./|$(pwd)/|")"
}

remove_ourselves_from_path() {
	PATH="$(remove_dir_from_path "${PATH}" $(absolute_parent_of_current_script))"
}

remove_dir_from_path() {
	local path dir trailing_colon
	path="$1"; shift
	dir="$1"; shift
	trailing_colon=$(echo "${path}" \
		| tr ':' '\n' \
		| grep -v "^${dir}\$" \
		| tr '\n' ':')
	echo "${trailing_colon%:*}"
}

show_physical_path() {
	local path
	path="$1"; shift
	if ( command -v readlink >/dev/null 2>&1 ); then
		readlink -f "${path}"
	elif ( command -v realpath >/dev/null 2>&1 ); then
		realpath "${path}"
	else
		echo >&2 "don't know how to canonicalize physical path"
		exit 5
	fi
}

cvs_latest_patchset() {
	cvsps | grep ^PatchSet | tail -1 | awk '{print $2}'
}

cvs_carets_before_head() {
	sed -e 's|^HEAD||g' | fold -w 1 | uniq -c | head -1 | awk '{print $1}'
}

cvs_tilde_before_head() {
	sed -e 's|^HEAD~||g'
}

cvs_show() {
	local patchset

	if [ "$#" -gt 0 ]; then
		case "$1" in
			HEAD^*)	patchset="$(expr $(cvs_latest_patchset) - $(echo $1 | cvs_carets_before_head))" ;;
			HEAD~)	patchset="$(expr $(cvs_latest_patchset) - 1)" ;;
			HEAD~*)	patchset="$(expr $(cvs_latest_patchset) - $(echo $1 | cvs_tilde_before_head))" ;;
			HEAD)	patchset="$(cvs_latest_patchset)" ;;
			*)	patchset="$1";;
		esac
	else
		patchset="$(cvs_latest_patchset)"
	fi

	exec cvsps -g -s "${patchset}"
}

run_adjusted_command_line() {
	if [ "$#" -gt 0 ]; then
		case "$1" in
			diff)		exec cvs "$@" | colordiff | less -F ;;
			plaindiff)	shift; exec cvs diff "$@" ;;
			show)		shift; cvs_show "$@" | colordiff | less -F ;;
			gitlog)		shift; exec cvsps "$@" | less -F +G ;;
			*)		exec cvs "$@" ;;
		esac
	else
		exec cvs "$@"
	fi
}

main() {
	case "$(basename $0)" in
		cvs)	remove_ourselves_from_path ;;
		*)	;;
	esac

	run_adjusted_command_line "$@"
}

main "$@"
exit $?
