#! /usr/bin/bash

winNameToFind=${1}

printUsage()
{
	echo "${0}: <STRING:windowNameToFind>"
	exit 1
}

if [ "${winNameToFind}x" = "x" ]; then
	printUsage
fi

extractAllChildIdsFrom()
{
	echo $(echo "${1}" \
		| grep '^[[:space:]]*0x[0-9a-zA-Z]' \
		| awk '{print $1}')
	return 0
}

searchOneParentByName()
{
	local thisWinId=$1
	local winNameToFind=$2

	local thisWininfoStdout=$(xwininfo -id "${thisWinId}")
	local thisWinName=$(echo "${thisWininfoStdout}" \
		| grep '[Ww]indow[[:space:]]*[iI][dD]' \
		| grep -oP '[0-9a-zA-Z]*[[:space:]]*\".*\"$' \
		| sed 's/[0-9a-zA-Z]*[[:space:]]*//')
	echo "Searching win [ID=${thisWinId}, name=\"${thisWinName}\"] and its children..."
	if echo "${thisWinName}" | grep -q "${winNameToFind}"; then
		echo "${thisWininfoStdout}"
#		return 0
	fi

	local allChildrenUnparsedOutput=$(xwininfo -id "${thisWinId}" -children)
	for i in $(extractAllChildIdsFrom "${allChildrenUnparsedOutput}");
	do
		searchOneParentByName "${i}" "${winNameToFind}"
	done

	return 1;
}

rootChildWindowOutput=$(xwininfo -root -children)
for i in $(extractAllChildIdsFrom "${rootChildWindowOutput}");
do
	searchOneParentByName "${i}" "${winNameToFind}"
done

exit 1
