{self, ...}: let
  inherit (builtins) concatStringsSep attrNames;

  clusterConfig = import "${self}/data/pipedClusterConfig.nix";
  inherit (clusterConfig) hosts ports;
in {
  systemd.services.haproxy.wantedBy = ["piped-backend.service"];

  services.haproxy = {
    enable = true;
    config = ''
        global
          maxconn 4096

        defaults
          mode tcp
          retries 5
          timeout connect 5s
          timeout client 10m
          timeout server 10m
          option clitcpka

      listen psql
        bind :${toString ports.cockroachDB_HAProxy}
        mode tcp
        balance roundrobin
        option httpchk GET /health?ready=1
      ${concatStringsSep "\n" (
        map (serverConfig: "  " + serverConfig)
        (map (
          hostName: "server ${hostName} ${hosts.${hostName}.advertiseAddr} check port ${toString ports.cockroachDB_HTTP}"
        ) (attrNames hosts))
      )}
    '';
  };
}