summaryrefslogtreecommitdiffstats
path: root/printq
blob: a33f5be0d9a0e269b941a3b815dc46a19b7fa6bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/bin/sh
#
# printq - Watches a directory of print queues and submits files for printing
#
# Copyright (C) 2021  P. J. McDermott
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

set -eu

print_from_queue()
{
	local dest="${1}"
	local queue="${2}"
	local file="${3}"
	shift 3
	local opt=

	set -- -d "${dest}"
	while read opt; do
		set -- "${@}" -o "${opt}"
	done 0<"${queue}/.options"

	logger -t 'printq' "Printing ${queue}/${file}"
	if ! out="$(lp "${@}" "${queue}/${file}" 2>&1)"; then
		logger -t 'printq' "Failed to print: ${out}"
		return 1
	fi
	rm -f "${queue}/${file}" || return 1

	return 0
}

watch_queues()
{
	local dir="${1}"
	shift 1
	local watched_filename=
	local event_names=
	local event_filename=
	local dest=

	logger -t 'printq' "Watching queues under ${dir}"
	inotifywait -m -r -q -e close_write "${dir}" | \
		while read -r watched_filename event_names event_filename; do
			dest="${watched_filename#${dir}}"
			while ! [ x"${dest}" = x"${dest#/}" ]; do
				dest="${dest#/}"
			done
			dest="${dest%%/*}"
			print_from_queue "${dest}" "${watched_filename}" \
				"${event_filename}" || :  # Don't exit on error.
		done

	# Shouldn't reach this point.
	logger -t 'printq' 'Failed to watch queues'
	return 1
}

usage()
{
	printf 'Usage: %s <dir>\n' "${0}"

	return 0
}

main()
{
	local dir=

	if [ ${#} -ne 1 ]; then
		usage 1>&2
		return 1
	fi
	dir="${1}"
	shift 1

	watch_queues "${dir}" || return 1

	return 0
}

main "${@}"