{ config, lib, pkgs, self, ... }:

let
  cfg = config.samfelag.modules.server.consul;
in
{
  options.samfelag.modules.server.consul = {
    enable = lib.mkEnableOption "consul";

    agent-token = lib.mkOption {
      type = lib.types.str;
      description = "Agent token config file (should be secret)";
    };

  };
  config = lib.mkIf cfg.enable {
    services.consul = {
      enable = true;
      webUi = true;
    };

    environment.etc = {
      agent-ca = {
        # Consul agent CA
        target = "consul.d/certs/consul-agent-ca.pem";
        source = config.age.secrets."consul.d/consul-agent-ca.pem".path;
      };
      gossip = {
        # Gossip encryption key
        target = "consul.d/gossip.json";
        source = config.age.secrets."consul.d/gossip.json".path;
      };
      client = {
        # Client config
        target = "consul.d/client.json";
        source = ../../config/consul.d/client.json;
      };
      agent-token = {
        # Agent token
        target = "consul.d/agent-token.json";
        source = cfg.agent-token;
      };
    };

    # networking.firewall.allowedTCPPorts = [ 22 ];
  };
}
