about summary refs log tree commit diff
path: root/ops/modules/clbot.nix
blob: 0a436a8749d008f8dfcce59a7bb75b62d12e9342 (plain) (blame)
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
# Module that configures CLBot, our Gerrit->IRC info bridge.
{ depot, config, lib, pkgs, ... }:

let
  inherit (builtins) attrValues concatStringsSep mapAttrs readFile;
  inherit (pkgs) runCommand;

  inherit (lib)
    listToAttrs
    mapAttrsToList
    mkEnableOption
    mkIf
    mkOption
    removeSuffix
    types;

  description = "Bot to forward CL notifications";
  cfg = config.services.depot.clbot;

  mkFlags = flags:
    concatStringsSep " "
      (attrValues (mapAttrs (key: value: "-${key} \"${toString value}\"") flags));

  # Escapes a unit name for use in systemd
  systemdEscape = name: removeSuffix "\n" (readFile (runCommand "unit-name" { } ''
    ${pkgs.systemd}/bin/systemd-escape '${name}' >> $out
  ''));

  mkUnit = channel: channelFlags: {
    name = "clbot-${systemdEscape channel}";
    value = {
      description = "${description} to ${channel}";
      wantedBy = [ "multi-user.target" ];

      script = "${depot.fun.clbot}/bin/clbot ${mkFlags (cfg.flags // channelFlags // {
        irc_channel = channel;
      })} -alsologtostderr";

      serviceConfig = {
        User = "clbot";
        EnvironmentFile = cfg.secretsFile;
        Restart = "always";
      };
    };
  };
in
{
  options.services.depot.clbot = {
    enable = mkEnableOption description;

    flags = mkOption {
      type = types.attrsOf types.str;
      description = "Key value pairs for command line flags";
    };

    channels = mkOption {
      type = with types; attrsOf (attrsOf str);
      description = "Channels in which to post (generates one unit per channel); nested attrs are used as extra flags to the service, which override the attrs in `flags`";
    };

    secretsFile = mkOption {
      type = types.str;
      description = "EnvironmentFile from which to load secrets";
      default = config.age.secretsDir + "/clbot";
    };
  };

  config = mkIf cfg.enable {
    # This does not use DynamicUser because we need to make some files
    # (notably the SSH private key) readable by this user outside of
    # the module.
    users = {
      groups.clbot = { };

      users.clbot = {
        group = "clbot";
        isSystemUser = true;
      };
    };

    systemd.services = listToAttrs (mapAttrsToList mkUnit cfg.channels);
  };
}