#!/bin/sh

# xtopen -- run command in xterm

abbr() {
	case "$1" in
        /home/$USER/*)	a='~'${1#/home/$USER} ;;
        /home/$USER)	a='~' ;;
        /home/*)	a='~'${1#/home/} ;;
	*)		a=$1 ;;
	esac
	printf '%s\n' "$a"
}

if [ $# -eq 0 ]; then
	xmessage -buttons sorry:0 -default sorry -nearmouse \
		"usage: $0 [-k] [-K] cmd ..."
	exit 1
fi

k=
K=
while getopts kK o; do
	case $o in
	K)	K=1 ;;
	k)	k=1 ;;
	?)	xmessage -buttons sorry:0 -default sorry -nearmouse \
			error: "unknown flag $1"
		exit 1 ;;
	esac
done
shift $((OPTIND-1))

if ! which "$1" >/dev/null; then
	xmessage -default okay -nearmouse \
		error: "program $1 not found"
	exit 1
fi

case "$k,$K" in
1,*)	exec xterm -title "$* (`abbr "$PWD"`)" -e with-shell "$@" ;;
*,1)	exec xterm -title "$* (`abbr "$PWD"`)" -e with-shell-on-error "$@" ;;
*,*)	exec xterm -title "$* (`abbr "$PWD"`)" -e "$@" ;;
esac