{ zentralwerk, config, pkgs, ... }:
let
  # wrap reload in freeze/thaw so that zones are reloaded that had
  # been updated by dyndns
  reloadCommand = with pkgs; writeScriptBin "reload-bind" ''
    #!${runtimeShell}

    rndc() {
      ${bind}/sbin/rndc -k /etc/bind/rndc.key $@
    }

    rndc freeze
    rndc reload
    rndc thaw
  '';
in
{
  c3d2 = {
    hq.statistics.enable = true;
    deployment.server = "server10";
  };

  environment.etc.gitconfig.text = ''
    [url "gitea@gitea.c3d2.de:"]
    insteadOf = https://gitea.c3d2.de/
  '';

  networking = {
    hostName = "bind";
    firewall = {
      allowedTCPPorts = [
        # DNS
        53
      ];
      allowedUDPPorts = [
        # DNS
        53
      ];
    };
  };

  # Privileged commands triggered by deploy-c3d2-dns
  security.sudo.extraRules = [ {
    users = [ "c3d2-dns" ];
    commands = [ {
      command = "${reloadCommand}/bin/reload-bind";
      options = [ "NOPASSWD" ];
    } ];
  } ];

  # DNS server
  services.bind = {
    enable = true;
    extraConfig = ''
      include "${config.users.users.c3d2-dns.home}/zones.conf";
      include "${zentralwerk.packages.${pkgs.system}.dns-slaves}";

      # for collectd
      statistics-channels {
        inet 127.0.0.1 port 8053;
      };
    '';
  };

  # BIND statistics in Grafana
  services.collectd.plugins.bind = ''
    URL "http://127.0.0.1:8053/";
    ParseTime       false
    OpCodes         true
    QTypes          true
    ServerStats     true
    ZoneMaintStats  true
    ResolverStats   false
    MemoryStats     true
  '';

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets = {
     "ssh-keys/c3d2-dns/private" = {
        owner = "c3d2-dns";
        mode = "400";
        path = "/var/lib/c3d2-dns/.ssh/id_ed25519";
      };
      "ssh-keys/c3d2-dns/public" = {
        owner = "c3d2-dns";
        mode = "440";
        path = "/var/lib/c3d2-dns/.ssh/id_ed25519.pub";
      };
    };
  };

  system.stateVersion = "22.05";

  systemd.services.bind.serviceConfig = {
    Restart = "always";
    RestartSec = "5s";
  };

  systemd.tmpfiles.rules = [
    "d ${config.users.users.c3d2-dns.home} 0755 c3d2-dns ${config.users.users.c3d2-dns.group} - -"
    "d /var/lib/bind/slave 0755 named nogroup - -"
  ];

  # Build user
  users.groups.c3d2-dns = {};
  users.users.c3d2-dns = {
    isNormalUser = true;
    group = "c3d2-dns";
    home = "/var/lib/c3d2-dns";
    openssh.authorizedKeys.keys = [
      "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHIkIN1gi5cX2wV2WuNph/QzVK7vvYkvqnR/P69s36mZ drone@c3d2"
    ];
    packages = [ reloadCommand ];
  };
}
