#!/usr/bin/bash

set -eu

## Exit if first printserver is not reachable
ping -c1 -W1 {{ printservers | first }} || exit 0

printservers="{{ printservers | join(' ') }}"
hostgroup="$(id -Gn "${HOSTNAME^^}$")"
usergroup="$(id -Gn "${SUDO_USER}")"
installedprinters="$(lpstat -v | cut -f 3 -d" " | sed 's/:$//' )"

cat <<EOF
Hostgroups: ${hostgroup}
Usergroups: ${usergroup}
Local print queues:
${installedprinters}

EOF

## Remove all printers not wanted:
for p in $installedprinters ; do
    printer_ip=$(lpstat -v "${p}" | sed -nE "s%.*ipp://(.+)/printers.*%\1%p")
    if [[ -n $printer_ip ]] && (echo "${printservers}" | grep -w -q "${printer_ip}"); then
	echo "Removing print queue '$p'."
	lpadmin -x "$p"
    fi
done

installedprinters="$(lpstat -v | cut -f 3 -d" " | sed 's/:$//' )"

## Add all printers needed:
for ps in $printservers ; do
    echo "Checking print server '$ps' for available printers:"
    printers="$(timeout 5 lpstat -h "$ps" -U "${SUDO_USER}" -v | sed -E 's/^.+ (\w+): .+$/\1/')"
    echo -e "$printers\n"
    for p in $printers; do
	if [[ "${hostgroup}" =~ "$p" ]] || [[ "${usergroup}" =~ "$p" ]] ; then
	    if [[ "$installedprinters" =~ "$p" ]] ; then
		echo "Print queue '$p' already available."
	    else
		echo "Adding print queue '$p'."
		timeout 10 lpadmin -p "$p" -E -v \
			"ipp://$ps/printers/$p" \
			-m "driverless:ipp://$ps/printers/$p" || echo "Adding queue '$p' failed."
		installedprinters+=" $p"
	    fi
	fi
    done
done
