#!/bin/bash

PARM=$1
USB_BACKEND=""
USE_USB_BACKEND=0

genericUSBList(){
    res=`${USB_BACKEND} | awk '{print $2}'` 
    count=0
    for item in ${res}; do
        name=`echo $item | sed 's/usb:\\/\\///g' | sed 's/\?.*$//g'`
        model=`echo $name | sed 's/%20/ /g' | sed 's/\\// /g'`
        echo "$count;$model;$item"
        count=`expr $count + 1`
    done
}


wsuUSBList(){
    UDEVADM=/sbin/udevadm
    if [ -f ${UDEVADM} ]; then
        for ((n=0; n < 16; n++))
        do
            if [ -e /dev/usb/lp${n} ]; then
                lnk=`${UDEVADM} info -q path -n /dev/usb/lp${n}`
                if [ "$lnk" != "" ]; then
                    nfo=`${UDEVADM} info -a -p ${lnk} | grep ieee1284_id | sed 's/ATTRS{ieee1284_id}==//g' | awk -F\" '{print $2}'`
                    model=`echo $nfo | sed 's/^.*MODEL://g' | sed 's/;.*$//g'`
                    mfg=`echo $nfo | sed 's/^.*MFG://g' | sed 's/;.*$//g'`
                    escmodel=`echo $model | sed 's/ /%20/g'`
                    echo "$n;$mfg $model;usb://$mfg/$escmodel"
                fi
            fi
        done
    fi
}

checkUSBBackend(){

    if [ -f /usr/lib/cups/backend/usb ]; then
        `/usr/lib/cups/backend/usb > /dev/null 2> /dev/null`
        if [ "$?" = "0" ]; then
            USE_USB_BACKEND=1
            USB_BACKEND="/usr/lib/cups/backend/usb"
        fi
    elif [ -f /usr/lib64/cups/backend/usb ]; then
        `/usr/lib64/cups/backend/usb > /dev/null 2> /dev/null`
        if [ "$?" = "0" ]; then
            USE_USB_BACKEND=1
            USB_BACKEND="/usr/lib64/cups/backend/usb"
        fi        
    fi
}

oldCUPSBackend(){

    for i in `${USB_BACKEND} | sed -e 's/\ /!!space!!/g'`
    do
    
        line=`echo $i | sed -e 's/!!space!!/\ /g'`

        item=`echo $line | awk '{print $2}'`

        name=`echo $item | sed 's/usb:\\/\\///g' | sed 's/\?.*$//g'`
  
        model=`echo $name | sed 's/%20/ /g' | sed 's/\\// /g'`

        usb=`echo $line | awk -F "\"" '{ printf $4; }' | sed -e 's/.*#\(.*\)/\1/g'`

        usb_num=`expr $usb - 1`

        usb_path=`echo "/dev/usb/lp${usb_num}"`

        echo "$usb_num;$model;$item"
    
    done


}


wsuGetList(){
    checkUSBBackend

    if [ "${USE_USB_BACKEND}" = "1" ]; then
        `${USB_BACKEND} | grep "USB #" > /dev/null 2> /dev/null`
        if [ "$?" = "0" ]; then
            oldCUPSBackend
        else
            wsuUSBList
        fi
    else
        wsuUSBList
    fi            


}

genericGetList(){
    checkUSBBackend
    
    if [ "${USE_USB_BACKEND}" = "1" ]; then
        genericUSBList
    else
        wsuUSBList
    fi    
         
}



case $PARM in
   
    wsu) wsuGetList
         ;;
    *) genericGetList
         ;;
         
esac     
