{ pkgs, config, lib, ... }:
let
  servers = [
    "c1"
    "c2"
    "c3"
  ];
in
{
  options.clusterRole.consulServer = lib.mkEnableOption "Consul server mode";

  config = {
    services.consul = {
      enable = true;
      webUi = true;
      interface.advertise = config.networking.cluster.primaryInterface;
      extraConfig = {
        client_addr = "0.0.0.0";
        datacenter = "alo";
        server = config.clusterRole.consulServer;
        bootstrap_expect = if config.clusterRole.consulServer then (builtins.length servers + 2) / 2 else null;
        retry_join = builtins.filter (elem: elem != config.networking.hostName) servers;
      telemetry = {
        prometheus_retention_time = "24h";
        disable_hostname = true;
      };
    };
    };

    environment.persistence.${config.custom.impermanence.persistPath}.directories = [ "/var/lib/consul" ];

    networking.firewall = {
      allowedTCPPorts = [
        8600
        8500
        8301
        8302
        8300
      ];
      allowedUDPPorts = [
        8600
        8301
        8302
      ];
    };
  };
}
