summaryrefslogtreecommitdiff
path: root/custom/unit-status-mail.nix
blob: 1b87a0b0b8dc3f493cf286aeef9af54be0bbaed4 (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
{ 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\"";
        script = ''
          #!${pkgs.stdenv.shell}
          MAILTO="${cfg.recipient}"
          MAILFROM="unit-status-mailer"
          UNIT=$1
  
          EXTRA=""
          for e in "''${@:2}"; do
            EXTRA+="$e"$'\n'
          done
  
          UNITSTATUS=$(systemctl status $UNIT)
  
          ${config.security.wrapperDir}/sendmail $MAILTO <<EOF
          From:$MAILFROM
          To:$MAILTO
          Subject:Status of $UNIT

          Status report for unit: $UNIT
          $EXTRA

          $UNITSTATUS
          EOF
        '';
      };
    } // serviceCfg;
  };
}