#!/bin/sh -

# xwinid - interactively determine and print the ID of a selected X window
# Steve Kinzler, steve@kinzler.com, Aug 98
# https://kinzler.com/me/home.html#x11

case "$#,$1" in
0,*)	set \(\[\^\)\]\[\^\)\]\*\);;
*,-h)	echo "usage: $0 [ grep arguments ]" 1>&2; exit 1;;
esac

tmp="${TMPDIR:-/tmp}/wi$$"
trap "rm -fr '$tmp'; exit" 0 1 2 13 15

# WARNING: xlswins can run pretty slowly from a distant remote host,
#   may be best to not have xlswins installed so we default to xwininfo below
#   even though that only supports select by click

# NOTE: some ideas for fast xlswins alternatives, and for current win id:
#	xlsclients -l
#	wmctrl -l
#	wmctrl -v -r :ACTIVE: -e dummy
#	xdotool getmouselocation --shell
#	xdotool search ...
#	xdotool getwindowfocus
#	xwit -print -current
#	xprop -root -f _NET_ACTIVE_WINDOW 0x " \$0\\n" _NET_ACTIVE_WINDOW
# see http://www.ict.griffith.edu.au/anthony/info/X/WindowID.hints

(echo 'Select by mouse click in window'
 xlswins -l 2> /dev/null | sed 's/[0-9]*: *//' | grep "$@") |
awk '{ printf "%-2d %s\n", NR, $0 }' > "$tmp"

n=`wc -l < "$tmp"`; n=`echo $n`
case "$n" in
1)	ans=1;;
*)	cat < "$tmp"					 > /dev/tty
	awk 'BEGIN { printf "? ['"$n"'] " }' < /dev/null > /dev/tty
	read ans					 < /dev/tty
	case "$ans" in
	'')	ans="$n";;
	esac;;
esac

id=`sed -n "s/^$ans  *//p" < "$tmp" | sed 's/ .*//; 2q'`

case "$id" in
Select)	test -z "$XWINID_QUIET" &&
		echo 'Click mouse in desired window ...' > /dev/tty
	xwininfo | sed -n 's/.*[Ww]indow *[Ii][Dd]:*[ 	]*//p' |
		   sed 's/[ 	].*//';;
'')	;;
*)	echo "$id";;
esac
