#!/usr/bin/env bash
##
## printers_setup_capt.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"

init_printer(){
    echo "${DEVNAME}" | grep -q "/dev/usb/lp" && DEVNAME="$(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
    DEV_IDPRODUCT="$(cat /sys/${DEVNAME}/../idProduct)"
    DEV_IDVENDOR="$(cat /sys/${DEVNAME}/../idVendor)"
    DEV_SERIAL="$(cat /sys/${DEVNAME}/../serial)"
    DEV_IEEE1284_ID="$(cat /sys/${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 "/" "-"  | tr " " "-" 2>/dev/null)-CAPT"
    PRINTER_NAME="$(echo "${PRINTER_MDL}" | tr "/" "-"  | tr " " "-" 2>/dev/null)"
    PRINTER_NAME_PPD="$(echo "${PRINTER_MDL}" | tr " " "-"  2>/dev/null)"
    for WAIT_TIME in 1 2 3 4; do	
	PRINTER_LP=$(basename $(ls -Udb /sys/${DEVNAME}/usbmisc/lp* 2>/dev/null | head -1) 2>/dev/null)
	[[ -z ${PRINTER_LP} ]] && sleep ${WAIT_TIME} || break
    done
#    PRINTER_LP="/dev/$(cat /sys/${DEVNAME}/usbmisc/*/uevent | grep DEVNAME | cut -d= -f2)"
    PRINTER_LP="/dev/usb/${PRINTER_LP}"
    [[ ${PRINTER_MDL} == "LBP810" ]] && PRINTER_MDL="LBP1120"
    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_MDL} ]] || exit 1
    [[ ${PRINTER_CLS} == "PRINTER" ]] || exit 1
    [[ ${PRINTER_CMD} == "CAPT" ]] || exit 1
# Установка в AppArmor профиля в щадящий режим для cupsd
#    aa-complain /usr/sbin/cupsd
}

auto_detect_capt_lp(){
    echo "$(date '+%m.%d.%Y %T') : $0 : auto_detect_lp"
    for DEV_LP in /dev/usb/lp*; do
	INFODEV="$(udevadm info -a -n ${DEV_LP} 2>/dev/null)"
	DEV_IEEE1284_ID="$(echo "${INFODEV}" | grep ATTRS{ieee1284_id} | head -1 | grep -o '".*"' | tr -d '"' | tr ";" "\n" 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_CMD} == "CAPT" ]] && DEVNAME="$(udevadm info -a -n ${DEV_LP} | grep "looking at" | head -1 | cut -d\' -f2 | sed "s/\/usbmisc.*//")" && echo "$(date '+%m.%d.%Y %T') : $0 : Auto detect CAPT printer: ${DEV_LP}" || echo "$(date '+%m.%d.%Y %T') : $0 : Printer: ${DE_LP} is not CAPT !" 
    done
}

# Удалить CAPT принтер, который определился и установился автоматически без CCPD
remove_not_ccpdcapt(){
    echo "$(date '+%m.%d.%Y %T') : $0 : remove_not_ccpdcapt : ${PRINTER_NAME}"
    PRINTER_NOTCCP=$(LC_ALL=en_US.UTF-8 lpstat -v 2>/dev/null | grep " usb://.*${DEV_SERIAL}.*" | head -1 | cut -d: -f1 | cut -d" " -f3)
    [[ -n ${PRINTER_NOTCCP} ]] && lpadmin -x "${PRINTER_NOTCCP}" && echo "$(date '+%m.%d.%Y %T') : $0 : remove_not_ccpdcapt : REMOVE : ${PRINTER_NOTCCP}"
#    LC_ALL=en_US.UTF-8 lpstat -v "${PRINTER_NAME}" 2>/dev/null | grep -q " usb://.*${DEV_SERIAL}.*" | head -1 && lpadmin -x "${PRINTER_NAME}" && echo "$(date '+%m.%d.%Y %T') : $0 : remove_not_ccpdcapt : REMOVE : ${PRINTER_NAME}"
}

add_printer(){
# Сделать проверку, если принтер существует с одинаковым именем, но другой адрес ${PRINTER_LP}
    if ! LC_ALL=en_US.UTF-8 lpstat -v "${PRINTER_NAME}" &>/dev/null; then
	echo "$(date '+%m.%d.%Y %T') : $0 : add_printer : ${PRINTER_NAME}"
        NAME_URI="ccp://localhost:59687"
	NAME_PPD=$(lpinfo --make-and-model ${PRINTER_NAME_PPD} -m | head -1 | cut -d" " -f1)
#    	NAME_PPD=$(basename -- $(grep -H ${PRINTER_NAME} /usr/share/cups/model/*.ppd | 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"
	sleep 2
	ccpdadmin -p "${PRINTER_NAME}" -o "${PRINTER_LP}"
	systemctl -q is-active ccpd.service 2>/dev/null && systemctl restart ccpd.service || systemctl enable --now ccpd.service 2>/dev/null
    fi
# PageSize
#	PAGESIZE_OPT=$(lpoptions -l -p ${PRINTER_NAME} | egrep "PageSize|Media Size" | head -1 | cut -d: -f1)
#	[[ ${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) 
#	[[ ${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
}

remove_printer(){
    while read PRINTER_DEV_LP_CAPT; do
        if [[ ! -e "${PRINTER_DEV_LP_CAPT}" ]] || echo "${DEVNAME}" | grep -q "/dev/usb/lp"; then
	    PRINTER_NAME=$(cat /etc/ccpd.conf | grep -B1 "^DevicePath" | head -1 | tr -d "<&>" | cut -d" " -f2)
	    echo "$(date '+%m.%d.%Y %T') : $0 : remove_printer : ${ACTION} : ${DEVNAME} : ${PRINTER_DEV_LP_CAPT} : ${PRINTER_NAME}"
	    cupsdisable -E "${PRINTER_NAME}"  2>/dev/null
	    cupsreject -E "${PRINTER_NAME}"  2>/dev/null
	    ccpdadmin -x "${PRINTER_NAME}" 2>/dev/null
	    lpadmin -x "${PRINTER_NAME}" 2>/dev/null
	    systemctl disable --now ccpd.service 2>/dev/null
	    pkill -9 -x ccpd
	    pkill -9 -x captmoncnabc
	    grep -q "${PRINTER_NAME}" /etc/profile.d/ublinux-default-printer.sh 2>/dev/null && rm -f /etc/profile.d/ublinux-default-printer.sh
	fi
    done <<< "$(systemctl -q is-enabled ccpd.service && [[ -f /etc/ccpd.conf ]] && cat /etc/ccpd.conf | grep "^DevicePath" | cut -d" " -f2 | xargs)"
# Удалить все принтеры CCP
    while read PRINTER_CCP; do
	echo "$(date '+%m.%d.%Y %T') : $0 : remove_printer : REMOVE PRINTER CCP: ${PRINTER_CCP}"
#	cupsdisable -E "${PRINTER_CCP}"  2>/dev/null
#	cupsreject -E "${PRINTER_CCP}"  2>/dev/null
#	ccpdadmin -x "${PRINTER_CCP}"
#    	lpadmin -x "${PRINTER_CCP}"
    done <<< "$(LC_ALL=en_US.UTF-8 lpstat -v 2>/dev/null | grep " ccp://" | cut -d: -f1 |  cut -d" " -f3)"
#    [[ -n "${PRINTER_NAME}" ]] && return 0 || return 1
}

start_captstatusui(){
    NAME_CAPTSTATUSUI="captstatusui-${PRINTER_NAME}"
    DESKTOP_CAPTSTATUSUI="${NAME_CAPTSTATUSUI}.desktop"
    SERVICE_CAPTSTATUSUI="${NAME_CAPTSTATUSUI}.service"
# Создаем кнопку запуска captstatusui
    echo "$(date '+%m.%d.%Y %T') : $0 : start_captstatusui : ${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}"
    echo '[Desktop Entry]
Type=Application
Exec=captstatusui -P '${PRINTER_NAME}'
Terminal=false
Icon=printer
Name=Satus Canon CAPT '${PRINTER_NAME}'
Name[ru]=Статус Canon CAPT '${PRINTER_NAME}'
GenericName=Status monitor for Canon CAPT Printer '${PRINTER_NAME}'
GenericName[ru]=Статус для принтера Canon CAPT '${PRINTER_NAME}'
Comment=Status monitor for Canon CAPT Printer '${PRINTER_NAME}'
Comment[ru]=Статус для принтера Canon CAPT '${PRINTER_NAME} > "${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}"
    chmod 644 "${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}"
#    ln -sf "${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}" "${XDG_AUTOSTART}"
    find /home/*/"${XDG_DESKTOP_DIR}" -maxdepth 0 -type d -exec cp "${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}" {} \;
    find /home/*/"${XDG_DESKTOP_DIR}" -maxdepth 1 -type f -iname "${DESKTOP_CAPTSTATUSUI}" -exec chmod 0777 {} \;
    find /home/*/"${XDG_DESKTOP_DIR}" -maxdepth 1 -type f -iname "${DESKTOP_CAPTSTATUSUI}" -exec chown root:users {} \;
# Запуск  captstatusui
#    [[ -n "${DISPLAY}" && -n ${LOGIN_USER} ]] && su ${LOGIN_USER} -c "nohup captstatusui -P ${PRINTER_NAME} -e 2>&1 &"
#    DISPLAY=:0 su superadmin -c "nohup captstatusui -P LBP2900 2>&1 &"
echo '[Unit]
Description=Start captstatusui for printer '${PRINTER_NAME}'
Requires=graphical-session.target
After=graphical-session.target

[Service]
ExecStart=/usr/bin/captstatusui -P '${PRINTER_NAME}' -e
Restart=always
RestartSec=3s

[Install]
WantedBy=default.target' > /usr/lib/systemd/user/${SERVICE_CAPTSTATUSUI}
#    systemctl daemon-reload
    systemctl --global enable ${SERVICE_CAPTSTATUSUI}
#    [[ -n ${LOGIN_USER} ]] && systemctl --machine=${LOGIN_USER}@.host --user daemon-reload 2>/dev/null
    [[ -n ${LOGIN_USER} ]] && systemctl --machine=${LOGIN_USER}@.host --user start --now ${SERVICE_CAPTSTATUSUI} 2>/dev/null
}

stop_captstatusui(){
    [[ -z ${PRINTER_NAME} ]] && PRINTER_NAME=*
    NAME_CAPTSTATUSUI="captstatusui-${PRINTER_NAME}"
    DESKTOP_CAPTSTATUSUI="${NAME_CAPTSTATUSUI}.desktop"
    SERVICE_CAPTSTATUSUI="${NAME_CAPTSTATUSUI}.service"
    echo "$(date '+%m.%d.%Y %T') : $0 : stop_captstatusui : ${PATH_APPLICATION}/${DESKTOP_CAPTSTATUSUI}"
    [[ -n ${LOGIN_USER} ]] && systemctl -q --machine=${LOGIN_USER}@.host --user disable --now ${SERVICE_CAPTSTATUSUI} 2>/dev/null
    systemctl --global disable ${SERVICE_CAPTSTATUSUI}
#    rm -f "${XDG_AUTOSTART}/${DESKTOP_CAPTSTATUSUI}"
    find ${PATH_APPLICATION} -maxdepth 2 -iname ${DESKTOP_CAPTSTATUSUI} -delete
    find /home/*/"${XDG_DESKTOP_DIR}"/ -maxdepth 2 -iname ${DESKTOP_CAPTSTATUSUI} -delete
    find /usr/lib/systemd/user/ -maxdepth 2 -iname ${SERVICE_CAPTSTATUSUI} -delete
    pkill -9 -x captstatusui
#    [[ -n ${LOGIN_USER} ]] && systemctl --machine=${LOGIN_USER}@.host --user daemon-reload 2>/dev/null
#    systemctl daemon-reload
}

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

    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

    [[ -n $1 ]] && ACTION="$1" || ACTION="add"
    [[ -n $2 ]] && DEVNAME="$2" || auto_detect_capt_lp 

    echo "$(date '+%m.%d.%Y %T') : $0 : Start: ${ACTION} : ${DEVNAME}"

# Пользователь под которым мы вошли в ситему
    LOGIN_USER=$(who | grep "(:[[:digit:]])" | grep "tty" | head -1 | cut -d" " -f1) #"
#    [[ -z ${LOGIN_USER} ]] && LOGIN_USER="root"
#    LOGIN_USER_HOME=$(su ${LOGIN_USER} -c env | grep -i "home=" | xargs | cut -d'=' -f2)
#    export DISPLAY=$(ps -u $(id -u) -o pid= | xargs -I{} cat /proc/{}/environ 2>/dev/null | tr '\0' '\n' | grep -m1 '^DISPLAY=' | cut -d= -f2 2>/dev/null)
#    echo $DISPLAY
    XDG_AUTOSTART="/etc/xdg/autostart"
    PATH_APPLICATION="/usr/share/applications"
# Подгружаем файл содержащий путь до рабочего стола
    XDG_DESKTOP_DIR=$(cat $(find /home/*/.config/user-dirs.dirs -type f -print -quit) | grep XDG_DESKTOP_DIR | cut -d= -f2 | tr -d '"' | cut -d"/" -f2) 
    [[ -z ${XDG_DESKTOP_DIR} ]] && XDG_DESKTOP_DIR="Рабочий стол"
    case "$ACTION" in
	add)
	    sleep 2
	    init_printer
	    remove_not_ccpdcapt
	    add_printer
	    start_captstatusui
	    sleep 20 
	    remove_not_ccpdcapt
        ;;
	remove)
	    remove_printer 
	    stop_captstatusui
        ;;
    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'

#ссылки на утилиту autoshutdowntool
#declare -A URL_ASDT=([amd64]='https://drive.google.com/uc?export=download&confirm=no_antivirus&id=0Byemcyi98JRjc0s2YlJVZ0xBckk' \
#[i386]='https://drive.google.com/uc?export=download&confirm=no_antivirus&id=0Byemcyi98JRjdzFlWjVnbGpBMFU')

#соостветствие ppd файлов и моделей принтеров
#declare -A LASERSHOT=([LBP-810]=1120 [LBP-1120]=1120 [LBP-1210]=1210 \
#[LBP2900]=2900 [LBP3000]=3000 [LBP3010]=3050 [LBP3018]=3050 [LBP3050]=3050 \
#[LBP3100]=3150 [LBP3108]=3150 [LBP3150]=3150 [LBP3200]=3200 [LBP3210]=3210 \
#[LBP3250]=3250 [LBP3300]=3300 [LBP3310]=3310 [LBP3500]=3500 [LBP5000]=5000 \
#[LBP5050]=5050 [LBP5100]=5100 [LBP5300]=5300 [LBP6000]=6018 [LBP6018]=6018 \
#[LBP6020]=6020 [LBP6020B]=6020 [LBP6200]=6200 [LBP6300n]=6300n [LBP6300]=6300 \
#[LBP6310]=6310 [LBP7010C]=7018C [LBP7018C]=7018C [LBP7200C]=7200C [LBP7210C]=7210C \
#[LBP9100C]=9100C [LBP9200C]=9200C)

#отсортированные имена принтеров 
#NAMESPRINTERS=$(echo "${!LASERSHOT[@]}" | tr ' ' '\n' | sort -n -k1.4)

#список моделей, которые поддерживаются утилитой автоотключения
#declare -A ASDT_SUPPORTED_MODELS=([LBP6020]='MTNA002001 MTNA999999' \
#[LBP6020B]='MTMA002001 MTMA999999' [LBP6200]='MTPA00001 MTPA99999' \
#[LBP6310]='MTLA002001 MTLA999999' [LBP7010C]='MTQA00001 MTQA99999' \
#[LBP7018C]='MTRA00001 MTRA99999' [LBP7210C]='MTKA002001 MTKA999999')
