#!/usr/bin/bash

set -eu

printservers="{{ printservers | join(' ') }}"
hostgroup="$(id -Gn "${HOSTNAME^^}$")"
usergroup="$(id -Gn "${SUDO_USER}")"
installedprinters="$(lpstat -p | cut -f 2 -d" ")"

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

EOF

## Remove all printers not wanted:
for p in $installedprinters ; do
    if [[ ! "${hostgroup}" =~ "$p" ]] && [[ ! "${usergroup}" =~ "$p" ]] ; then
	echo "Removing print queue '$p'."
	lpadmin -x "$p"
    fi
done

## Add all printers needed:
for ps in $printservers ; do
    echo "Checking print server '$ps' for available printers:"
    printers="$(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 everywhere || echo "Adding queue '$p' failed."
	    fi
	fi
    done
done
