#! /bin/bash
#
# Johannes Meixner <jsmeix@suse.de>, 2004, 2005, 2006

#set -x

export PATH="/sbin:/usr/sbin:/usr/bin:/bin"
export LC_ALL="POSIX"
export LANG="POSIX"
umask 022

MY_NAME=${0##*/}

# Input:

# Create temporary files:
TMP_DATA=$(mktemp -u /tmp/$MY_NAME.XXXXXX)
TMP_DATA_UNIQUE=$(mktemp -u /tmp/$MY_NAME.XXXXXX)
cat /dev/null >$TMP_DATA

# Function to extract USB entries from a description file with SANE syntax.
Extract()
{ grep -o '^[[:space:]]*:usbid[[:space:]]*"0x[0-9A-Fa-f]*"[[:space:]]*"0x[0-9A-Fa-f]*"' $1 | tr '[:upper:]' '[:lower:]' | sed -e 's/^[^"]*"\([^"]*\)"[[:space:]]*"\([^"]*\)"/\1 \2/'
}

# Process the SANE description files:
# At least the SANE description files must exist:
DESCRIPTION_FILES="/usr/share/sane/descriptions/*.desc"
ls $DESCRIPTION_FILES &>/dev/null || { echo "Error: Required SANE description files $DESCRIPTION_FILES not found." 1>&2 ; exit 3 ; }
# Extract USB entries from SANE description files:
for DESCRIPTION_FILE in $DESCRIPTION_FILES
do Extract $DESCRIPTION_FILE
done >>$TMP_DATA
# Extract USB entries from optional SANE external description files:
# In particular:
# /usr/share/sane/descriptions-external/hpaio.desc when package hplip is installed
# /usr/share/sane/descriptions-external/hpoj.desc when package hp-officeJet is installed
# /usr/share/sane/descriptions-external/epkowa.desc when package iscan or iscan-free is installed
DESCRIPTION_FILES="/usr/share/sane/descriptions-external/*.desc"
for DESCRIPTION_FILE in $DESCRIPTION_FILES
do Extract $DESCRIPTION_FILE
done >>$TMP_DATA

# Remove duplicates:
sort -u $TMP_DATA >$TMP_DATA_UNIQUE && mv -f $TMP_DATA_UNIQUE $TMP_DATA

# Output:

# Output header:
echo '<?xml version="1.0" encoding="ISO-8859-1"?>'
echo '<deviceinfo version="0.2">'
echo '  <device>'
echo

# Output generic SCSI scanner entry for those SCSI scanners which show up with scsi.type = scanner:
echo '    <match key="info.category" string="scsi_generic">'
echo '      <match key="@info.parent:scsi.type" string="scanner">'
echo '        <append key="info.capabilities" type="strlist">scanner</append>'
echo '      </match>'
echo '    </match>'
echo

# Output model specific USB scanner entries:
exec <$TMP_DATA
while read VENDOR PRODUCT
do echo '    <match key="info.category" string="usbraw">'
   echo "      <match key=\"@info.parent:usb_device.vendor_id\" int=\"$VENDOR\">"
   echo "        <match key=\"@info.parent:usb_device.product_id\" int=\"$PRODUCT\">"
   echo '          <append key="info.capabilities" type="strlist">scanner</append>'
   echo '        </match>'
   echo '      </match>'
   echo '    </match>'
   echo
done

# Output footer:
echo '  </device>'
echo '</deviceinfo>'

# Remove the temporary file
rm $TMP_DATA

exit 0

