#!/usr/sbin/openrc-run

description="Common Unix Printing System"

command="/usr/sbin/cupsd"
pidfile="/run/cups/cupsd.pid"

depend() {
	need localmount
	use logger net
	after rsyslog
}

coldplug_usb_printers() {
	local printer

	if type udevadm > /dev/null 2>&1 && [ -x /lib/udev/udev-configure-printer ]; then
		for printer in $(udevadm trigger --verbose --dry-run --subsystem-match=usb \
			--attr-match=bInterfaceClass=07 --attr-match=bInterfaceSubClass=01 2>/dev/null || true; \
			udevadm trigger --verbose --dry-run --subsystem-match=usb \
			--sysname-match='lp[0-9]*' 2>/dev/null || true); do
			/lib/udev/udev-configure-printer add "${printer#/sys}"
		done
	fi
}

start() {
	[ -x "$command" ] || return 1
	unset TMPDIR

	mkdir -p /run/cups/certs
	[ -x /sbin/restorecon ] && /sbin/restorecon -R /run/cups

	if [ -z "${TZ:-}" ] && [ -e /etc/timezone ]; then
		TZ=$(cat /etc/timezone)
		export TZ
	fi

	checkpath -d -m 0755 -o root:root "$(dirname "$pidfile")"

	ebegin "Starting ${RC_SVCNAME}"
	start-stop-daemon -S -p "$pidfile" -x "$command"
	eend $?
}

start_post() {
	coldplug_usb_printers
}

stop() {
	ebegin "Stopping ${RC_SVCNAME}"
	start-stop-daemon -K -p "$pidfile"
	eend $?
}

reload() {
	ebegin "Reloading ${RC_SVCNAME}"
	start-stop-daemon -K -s HUP -p "${pidfile}"
	eend $?
}
