#!/bin/bash
# lastact: arturo@2024-02-13
# desc: Extraemos la información de las impresoras del fichero /etc/cups/printers.conf

# Si no se reciben parámetros mostramos la información de todas las impresoras configuradas:
LISTA_IMPRESORAS=( $(lpstat -v | cut -d" " -f3 | cut -d":" -f1) )
FICH_PRINTERS="/etc/cups/printers.conf"

function checkprinter() {
    _IMPRESORA="${1}"
    PATRON="[[:space:]]{1}${_IMPRESORA}:"
    lpstat -v | grep -E "${PATRON}" && return 0 || return 1
}

function impresora_info() {
    IMPRESORA="${1}"
    OPCION_PRINTERS="${2}"
    SALIDA="#> Impresora: \"${IMPRESORA}\""
    if [[ -z "${OPCION_PRINTERS}" ]] ; then
        RES="$(awk "/<*Printer ${IMPRESORA}/,/<\/*Printer>/" "${FICH_PRINTERS}")"
        SALIDA="${SALIDA}\n${RES}"
    else
        RES="$(awk "/<*Printer ${IMPRESORA}/,/<\/*Printer>/" "${FICH_PRINTERS}" | grep "${OPCION_PRINTERS}" | cut -d" " -f3)"
        SALIDA="${SALIDA}\n## Opción: ${OPCION_PRINTERS}\n${RES}"
    fi
    echo -e "${SALIDA}"
}
if [ -z "${1}" ] ; then
    for IMP in "${LISTA_IMPRESORAS[@]}"; do
        impresora_info "${IMP}"
    done
else
    checkprinter "${1}" && \
    impresora_info "${1}" || \
    echo "=> No existe ninguna impresora configurada con ese nombre: ${1}"
fi

exit 0