1{ config, lib, pkgs, ... }:
2with lib;
3let
4 cfg = config.hardware.printers;
5
6 ensurePrinter = p: let
7 args = cli.toGNUCommandLineShell {} ({
8 p = p.name;
9 v = p.deviceUri;
10 m = p.model;
11 } // optionalAttrs (p.location != null) {
12 L = p.location;
13 } // optionalAttrs (p.description != null) {
14 D = p.description;
15 } // optionalAttrs (p.ppdOptions != {}) {
16 o = mapAttrsToList (name: value: "'${name}'='${value}'") p.ppdOptions;
17 });
18 in ''
19 ${pkgs.cups}/bin/lpadmin ${args} -E
20 '';
21
22 ensureDefaultPrinter = name: ''
23 ${pkgs.cups}/bin/lpadmin -d '${name}'
24 '';
25
26 # "graph but not # or /" can't be implemented as regex alone due to missing lookahead support
27 noInvalidChars = str: all (c: c != "#" && c != "/") (stringToCharacters str);
28 printerName = (types.addCheck (types.strMatching "[[:graph:]]+") noInvalidChars)
29 // { description = "printable string without spaces, # and /"; };
30
31
32in {
33 options = {
34 hardware.printers = {
35 ensureDefaultPrinter = mkOption {
36 type = types.nullOr printerName;
37 default = null;
38 description = ''
39 Ensures the named printer is the default CUPS printer / printer queue.
40 '';
41 };
42 ensurePrinters = mkOption {
43 description = ''
44 Will regularly ensure that the given CUPS printers are configured as declared here.
45 If a printer's options are manually changed afterwards, they will be overwritten eventually.
46 This option will never delete any printer, even if removed from this list.
47 You can check existing printers with {command}`lpstat -s`
48 and remove printers with {command}`lpadmin -x <printer-name>`.
49 Printers not listed here can still be manually configured.
50 '';
51 default = [];
52 type = types.listOf (types.submodule {
53 options = {
54 name = mkOption {
55 type = printerName;
56 example = "BrotherHL_Workroom";
57 description = ''
58 Name of the printer / printer queue.
59 May contain any printable characters except "/", "#", and space.
60 '';
61 };
62 location = mkOption {
63 type = types.nullOr types.str;
64 default = null;
65 example = "Workroom";
66 description = ''
67 Optional human-readable location.
68 '';
69 };
70 description = mkOption {
71 type = types.nullOr types.str;
72 default = null;
73 example = "Brother HL-5140";
74 description = ''
75 Optional human-readable description.
76 '';
77 };
78 deviceUri = mkOption {
79 type = types.str;
80 example = literalExpression ''
81 "ipp://printserver.local/printers/BrotherHL_Workroom"
82 "usb://HP/DESKJET%20940C?serial=CN16E6C364BH"
83 '';
84 description = ''
85 How to reach the printer.
86 {command}`lpinfo -v` shows a list of supported device URIs and schemes.
87 '';
88 };
89 model = mkOption {
90 type = types.str;
91 example = literalExpression ''
92 "gutenprint.''${lib.versions.majorMinor (lib.getVersion pkgs.gutenprint)}://brother-hl-5140/expert"
93 '';
94 description = ''
95 Location of the ppd driver file for the printer.
96 {command}`lpinfo -m` shows a list of supported models.
97 '';
98 };
99 ppdOptions = mkOption {
100 type = types.attrsOf types.str;
101 example = {
102 PageSize = "A4";
103 Duplex = "DuplexNoTumble";
104 };
105 default = {};
106 description = ''
107 Sets PPD options for the printer.
108 {command}`lpoptions [-p printername] -l` shows supported PPD options for the given printer.
109 '';
110 };
111 };
112 });
113 };
114 };
115 };
116
117 config = mkIf (cfg.ensurePrinters != [] && config.services.printing.enable) {
118 systemd.services.ensure-printers = {
119 description = "Ensure NixOS-configured CUPS printers";
120 wantedBy = [ "multi-user.target" ];
121 wants = [ "cups.service" ];
122 after = [ "cups.service" ];
123
124 serviceConfig = {
125 Type = "oneshot";
126 RemainAfterExit = true;
127 };
128
129 script = concatStringsSep "\n" [
130 (concatMapStrings ensurePrinter cfg.ensurePrinters)
131 (optionalString (cfg.ensureDefaultPrinter != null)
132 (ensureDefaultPrinter cfg.ensureDefaultPrinter))
133 # Note: if cupsd is "stateless" the service can't be stopped,
134 # otherwise the configuration will be wiped on the next start.
135 (optionalString (with config.services.printing; startWhenNeeded && !stateless)
136 "systemctl stop cups.service")
137 ];
138 };
139 };
140}