summaryrefslogtreecommitdiff
path: root/custom/unit-status-mail.nix
blob: c7f9bf379d787e83baae4a410fe5980fc84b8a70 (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
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.systemd.status-mail;

  serviceCfg = foldl singleServiceCfg {} cfg.onFailure;
  singleServiceCfg = attrs: unitName: attrs // (setAttrByPath [unitName "onFailure"] ["unit-status-mail@%n.service"]);
in {
  options = {
    systemd.status-mail = {
      onFailure = mkOption {
        default = [];
        type = types.listOf types.str;
        description = ''
          Send status mail when these units fail
        '';
      };

      recipient = mkOption {
        default = "root";
        type = types.str;
        description = ''
          Recipient of status mails
        '';
      };
    };
  };

  config = mkIf (cfg.onFailure != []) {
    systemd.services = {
      "unit-status-mail@" = {
        serviceConfig = {
          Type = "oneshot";
        };
        scriptArgs = "%I \"Hostname: %H\" \"Machine-ID: %m\" \"Boot-ID: %b\"";
        path = with pkgs; [nettools];
        script = ''
          #!${pkgs.stdenv.shell}
          MAILTO="${cfg.recipient}"
          MAILFROM="unit-status-mailer@$(hostname -f)"
          UNIT=$1
  
          EXTRA=""
          for e in "''${@:2}"; do
            EXTRA+="$e"$'\n'
          done
  
          ${config.security.wrapperDir}/sendmail $MAILTO <<EOF
          From:$MAILFROM
          To:$MAILTO
          Subject:Status of $UNIT

          Status report for unit: $UNIT
          $EXTRA
          $(systemctl status $UNIT)
          EOF
        '';
      };
    } // serviceCfg;
  };
}