#!/bin/bash

TIMEOUT=120

# This function reports of a successful scan. By default it beeps.
notify_scanok() {
	cnt=1000
	while [ $cnt -gt 0 ]; do
		printf "\a"  >/dev/tty1
		cnt=$(($cnt-1))
	done
}

# Empty clipboard
echo "" | xclip

CANCEL="                      Cancel                      "
XMSG="xmessage -timeout $TIMEOUT -center -file - -buttons "

(
	RESULT="`pbmscan 20 | decode2`"
	echo "$RESULT" | xclip
	if [ "$RESULT" != "" ]; then
		notify_scanok
	fi
) &
PBMPPPID=$!

(
	printf "\n\n\
                     Scan barcode\n\n\n\
     A beep sound will denote a successful scan\n\
   After scanning, paste with middle mouse button   \n\
      Scanning will be canceled in $TIMEOUT seconds\n\n\n\n" | $XMSG "$CANCEL"
	PBMPPID=`ps j|awk "{if (\\$1==$PBMPPPID) print \\$2}"`
	PBMPID=`ps j|awk "{if (\\$1==$PBMPPID) print \\$2}"`
	kill $PBMPID $PBMPPID $PBMPPPID  >&/dev/null
) &
XMSGPPID=$!
XMSGPID=`ps j|awk "{if (\\$1==$!) print \\$2}"`

wait $PBMPPPID
kill $XMSGPPID $XMSGPID >&/dev/null

#killall pbmscan >&/dev/null
