#!/usr/bin/env bash
##
## printers_setup.sh [$1 $2]
##      without $1 $2 - Action=auto
## $1 - Action
##	add
##	remove
## $2 - Device name
##	/dev/lp0
##	or
##	sys/devices/pci0000:00/0000:00:14.0/usb1/1-8
##

# Проверка на суперпользователя
#[[ $USER != 'root' ]] && exec sudo "$0"

LIST_PPD=$(cat <<EOF
HP LaserJet Pro M404-M405:hp-laserjet_pro_m404-m405-ps.ppd.gz
HP LaserJet Pro M201-M202:hp-laserjet_pro_m201_m202-ps.ppd.gz
EOF
)

init_printer(){
    echo "${DEVNAME}" | grep -q "/dev/usb/lp" && DEVNAME="sys$(udevadm info -a -n ${DEVNAME} 2>/dev/null | grep "looking at" | head -1 | cut -d\' -f2 | sed "s/\/usbmisc.*//")"
    [[ -z "${DEVNAME}" ]] && echo "$(date '+%m.%d.%Y %T'): $0 : ${ACTION} : ERROR : Not found DEVICE ${DEVNAME}"; [[ -z "${DEVNAME}" ]] && exit 1
#    INFODEV="$(udevadm info -a -n ${DEVNAME} 2>/dev/null)"
#    DEV_IDPRODUCT="$(echo "${INFODEV}" | grep ATTRS{idProduct} | head -1 | grep -o '".*"' | tr -d '"' 2>/dev/null)"
    DEV_IDPRODUCT="$(cat /${DEVNAME}/../idProduct)"
#    DEV_IDVENDOR="$(echo "${INFODEV}" | grep ATTRS{idVendor} | head -1 | grep -o '".*"' | tr -d '"' 2>/dev/null)"
    DEV_IDVENDOR="$(cat /${DEVNAME}/../idVendor)"
#    DEV_SERIAL="$(echo "${INFODEV}" | grep ATTRS{serial} | head -1 | grep -o '".*"' | tr -d '"' 2>/dev/null)"
    DEV_SERIAL="$(cat /${DEVNAME}/../serial)"
#    DEV_IEEE1284_ID="$(echo "${INFODEV}" | grep ATTRS{ieee1284_id} | head -1 | grep -o '".*"' | tr -d '"' | tr ";" "\n" 2>/dev/null)"
    DEV_IEEE1284_ID="$(cat /${DEVNAME}/ieee1284_id | head -1 | tr ";" "\n")"
    PRINTER_MFG="$(echo "${DEV_IEEE1284_ID}" | grep MFG | head -1 | cut -d: -f2 2>/dev/null)"
    PRINTER_MDL="$(echo "${DEV_IEEE1284_ID}" | grep MDL | head -1 | cut -d: -f2 2>/dev/null)"
    PRINTER_CMD="$(echo "${DEV_IEEE1284_ID}" | grep CMD | head -1 | cut -d: -f2 2>/dev/null)"
    PRINTER_CLS="$(echo "${DEV_IEEE1284_ID}" | grep CLS | head -1 | cut -d: -f2 2>/dev/null)"
    PRINTER_NAME=$(echo "${PRINTER_MDL}" | tr " " "-" 2>/dev/null)
    for WAIT_TIME in 1 2 3 4; do	
	PRINTER_LP=$(basename $(ls -Udb /${DEVNAME}/usbmisc/lp* 2>/dev/null | head -1) 2>/dev/null)
	[[ -z ${PRINTER_LP} ]] && sleep ${WAIT_TIME} || break
    done
#    PRINTER_LP="/dev/$(cat /${DEVNAME}/usbmisc/*/uevent | grep DEVNAME | cut -d= -f2)"
    PRINTER_LP="/dev/usb/${PRINTER_LP}"
    echo "$(date '+%m.%d.%Y %T') : $0 : init_printer : ${ACTION} : ${DEVNAME} : ${DEV_IDPRODUCT}:${DEV_IDVENDOR} : ${PRINTER_MFG} : ${PRINTER_MDL} : ${PRINTER_CMD} : ${PRINTER_CLS} : ${DEV_SERIAL} : ${PRINTER_NAME} : ${PRINTER_LP}"
    [[ ${PRINTER_CLS} == "PRINTER" ]] || exit 1
    [[ -z ${PRINTER_NAME} ]] && exit 1
#    PATH_LOG="/tmp/printer-${DEV_SERIAL}.log"
}

add_printer(){
    echo "$(date '+%m.%d.%Y %T') : $0 : add_printer : ${ACTION} : ${DEVNAME} : ${DEV_IDPRODUCT}:${DEV_IDVENDOR} : ${PRINTER_MFG} : ${PRINTER_MDL} : ${PRINTER_CMD} : ${PRINTER_CLS} : ${DEV_SERIAL} : ${PRINTER_NAME} : ${PRINTER_LP}"
#    echo "${LIST_PPD}"  | while read STR_PRINTER; do
#	if [[ ${PRINTER_MDL} == $(echo ${STR_PRINTER} | cut -d":" -f1) ]]; then
#	    NAME_URI=$(lpinfo -v | grep "direct" | grep "${DEV_SERIAL}" | cut -d" " -f2 | head -1)
#	    NAME_PPD=$(lpinfo --make-and-model "${PRINTER_MDL}" -m | head -1 | cut -d" " -f1)
#	    lpadmin -E -p ${PRINTER_NAME} -E -v "${NAME_URI}" -m ${NAME_PPD} -D "Info" -L "Office" -o "printer-is-shared=false" -m ${NAME_PPD}
#	fi	
#    done
    if [[ ${PRINTER_CMD} == "CAPT" ]]; then
#	/usr/bin/bash -c "${PATH_SETUP_CAPT} ${DEVNAME} ${ACTION}"
	echo "$(date '+%m.%d.%Y %T') : $0 : Forward to CAPT script : ${ACTION} : ${DEVNAME} : ${DEV_IDPRODUCT}:${DEV_IDVENDOR} : ${PRINTER_MFG} : ${PRINTER_MDL} : ${PRINTER_CMD} : ${PRINTER_CLS} : ${DEV_SERIAL} : ${PRINTER_NAME} : ${PRINTER_LP}"
	/usr/bin/bash -c "/usr/lib/ublinux/scripts/printers_setup_capt.sh ${ACTION} ${DEVNAME} "
    else 
#	NAME_URI=$(lpinfo -v | grep "direct" | grep "usb:" | grep "${DEV_SERIAL}" | cut -d" " -f2 | head -1)
	NAME_URI=$(/usr/lib/cups/backend/usb | grep "direct usb:" | grep "${DEV_SERIAL}" | cut -d" " -f2 | head -1)
# Если принтер добавлен совпадает частично имя принтера и серийник, то выходим
	LC_ALL=en_US.UTF-8 lpstat -v "${PRINTER_NAME}" 2>/dev/null  | grep -q ${NAME_URI} && return
	NAME_PPD=$(lpinfo --make-and-model "${PRINTER_MDL}" -m | head -1 | cut -d" " -f1)
	lpadmin -E -p "${PRINTER_NAME}" -E -v "${NAME_URI}" -m "${NAME_PPD}" -D "${PRINTER_NAME}" -L "Office" -o "printer-is-shared=false"
# PageSize A4
#	PAGESIZE_OPT=$(lpoptions -l -p "${PRINTER_NAME}" | egrep "PageSize|Page Size|Media Size" | head -1 | cut -d: -f1)
#	[[ -n ${PAGESIZE_OPT} ]] && echo "lpoptions -E -p "${PRINTER_NAME}" -o "${PAGESIZE_OPT%%/*}"=A4"
# Duplex On
#	DUPLEX_OPT=$(lpoptions -l -p "${PRINTER_NAME}" | egrep "HPOption_Duplexer|Duplex Unit|Duplexing" | head -1 | cut -d: -f1) 
#	[[ -n ${DUPLEX_OPT} ]] && echo "lpoptions -p "${PRINTER_NAME}" -o "${DUPLEX_OPT%%/*}"=True"
	
	lpoptions -E -d "${PRINTER_NAME}" >/dev/null
	lpadmin -E -d "${PRINTER_NAME}"
	cupsenable -E "${PRINTER_NAME}"
	cupsaccept -E "${PRINTER_NAME}"
	echo "export PRINTER=\"${PRINTER_NAME}\"" > /etc/profile.d/ublinux-default-printer.sh
	echo "export LPDEST=\"${PRINTER_NAME}\"" >> /etc/profile.d/ublinux-default-printer.sh 
	echo "$(date '+%m.%d.%Y %T') : $0 : end add_printer : ${ACTION} : ${DEVNAME} : ${DEV_IDPRODUCT}:${DEV_IDVENDOR} : ${PRINTER_MFG} : ${PRINTER_MDL} : ${PRINTER_CMD} : ${PRINTER_CLS} : ${DEV_SERIAL} : ${PRINTER_NAME} : ${PRINTER_LP}"
    fi
}

remove_printer(){
    /usr/lib/ublinux/scripts/printers_setup_capt.sh ${ACTION} ${DEVNAME}
# Удаляем все принтеры которые не обнаружены /usr/lib/cups/backend/usb
     while read STR_PRINTER; do
        PRINTER_NAME=$(echo ${STR_PRINTER%%:*})
	URI=$(echo ${STR_PRINTER#*: })
# Если принтер CAPT
	echo ${URI} | grep -q "ccp://" 2>/dev/null && break
##	if ! lpinfo -v | grep "direct" | grep " usb:" | cut -d" " -f2 | grep "${URI}"; then
	if ! /usr/lib/cups/backend/usb | grep "direct" | grep " usb:" | cut -d" " -f2 | grep -q "${URI}"; then
	    cupsdisable -E "${PRINTER_NAME}"  2>/dev/null
	    cupsreject -E "${PRINTER_NAME}"  2>/dev/null
#	    lpadmin -x "${PRINTER_NAME}" 2>/dev/null
	    grep -q "${PRINTER_NAME}" /etc/profile.d/ublinux-default-printer.sh 2>/dev/null && rm -f /etc/profile.d/ublinux-default-printer.sh
	    echo "$(date '+%m.%d.%Y %T') : $0 : remove_printer : ${ACTION} : ${DEVNAME} : ${PRINTER_NAME}"
	fi
    done <<< "$(LC_ALL=en_US.UTF-8 lpstat -v 2>/dev/null | grep "device for"  | sed "s/device for //")"
}

#################################################################
#								#
# Main								#
#								#
#################################################################

    PATH_SETUP_CAPT="/usr/lib/ublinux/scripts/printers_setup_capt.sh"
    PATH_LOG="/var/log/cups/printers_setup.log"

    exec 3>&1 4>&2
    trap 'exec 2>&4 1>&3' 0 1 2 3
    exec 1>>${PATH_LOG} 2>&1

    [[ -z ${ACTION} ]] && ACTION=$1
    [[ -z ${DEVNAME} ]] && DEVNAME=$2
    ([[ -z ${DEVNAME} || -z ${ACTION} ]]) && exit 0
    echo; echo "-------------------------------------------------------------------------------------------------------------------"
    echo "$(date '+%m.%d.%Y %T') : $0 : Start : ${ACTION} : ${DEVNAME}"

    case "${ACTION}" in
	add)
	    sleep 5
	    init_printer 
	    add_printer 
        ;;
	remove)
#	    echo "${DEVNAME}"
#	    echo $0 $@ called by $PPID
	    remove_printer
        ;;
    esac
    echo "$(date '+%m.%d.%Y %T') : $0 : Finish : ${ACTION} : ${DEVNAME}"



#udevadm info -a -n /dev/usb/lp0 | grep "ATTRS{ieee1284_id}"

#lpstat -v
#lpadmin -p M405 -v usb://HP/LaserJet%20Pro%20M404-M405?serial=PHCL262970 -E -m everywhere
#lpadmin -p 'GroceryPrinter' -E -v socket://$prt01/ipp/print -L 'Grocery Office' -m everywhere
#lpstat -l -p GroceryPrinter
#sudo udevadm control --reload-rules && udevadm trigger
#sudo udevadm test '/devices/pci0000:00/0000:00:14.0/usb1/1-8'