#!/bin/sh

#	bargrab 1.0 - recognize on-screen barcodes with zbarimg
#
#	Copyright Mikko Rauhala <mjr@iki.fi>, 2011
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar at
# http://sam.zoy.org/wtfpl/COPYING and reproduced here:
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar
#  14 rue de Plaisance, 75014 Paris, France
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO. 

ohnoes()
{
	echo "$2" 1>&2
	exit $1
}

check_utility()
{
	if ! which "$1" > /dev/null 2>&1; then
		ohnoes 2 "bargrab: external program $1 required but not found"
	fi
}

check_utility xwd
check_utility zbarimg

if ! [ -e /dev/stdin ]; then
	ohnoes 3 "bargrab: /dev/stdin needed for opening standard input"
fi

if [ "a$DISPLAY" = "a" ]; then
	ohnoes 4 "bargrab: No X display available, please set DISPLAY appropriately"
fi


XWDOPTS="-root"
CLIDUMP=0

while [ "a$1" != "a" ]; do
	if [ "a$1" = "a-w" ]; then
		XWDOPTS=""
		shift
	elif [ "a$1" = "a-t" ]; then
		CLIDUMP=1
		shift
	elif [ "a$1" = "a-tw" -o "a$1" = "a-wt" ]; then
		XWDOPTS=""
		CLIDUMP=1
		shift
	else
		RETVAL=1
		if [ "a$1" = "a-h" ]; then
			RETVAL=0
		fi
		ohnoes $RETVAL "Usage: bargrab [-w] [-t]

-w	Scan a single window (chosen with the mouse)
-t	Report results on stdout instead of a window
"
	fi
done

# Why the... what the... xwd dies if launched from the panel without this
sleep 1

if [ "a$CLIDUMP" = "a1" ]; then
	xwd $XWDOPTS | zbarimg -q /dev/stdin
else
	check_utility zenity
	xwd $XWDOPTS | zbarimg -q /dev/stdin | zenity --text-info --title "bargrab results" --filename /dev/stdin > /dev/null
fi

exit 0
