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

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

    server = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "Set to true if configured a server - otherwise a client is assumed";
    };

    host-config = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      description = "Additional host-specific config file";
    };

  };
  config = lib.mkIf cfg.enable {
    # services.consul.enable = true;
    services.nomad = {
      enable = true;
      dropPrivileges = false;
      extraSettingsPaths = [ "/etc/nomad.d" ];
    };

    # --- Systemd patch --------------------------------

    systemd.services.nomad = {
      after = [ "sys-subsystem-net-devices-tailscale0.device" "tailscaled.service" ];
      requires = [ "tailscaled.service" "consul.service" ];
    };

    # --- Config files ---------------------------------

    environment.etc = {
      # Common configuration
      nomad-common-cfg = {
        target = "nomad.d/common.json";
        source = ../../config/nomad.d/common.json;
      };
      # Consul token
      nomad-consul-token = {
        target = "nomad.d/consul-token.json";
        source = config.age.secrets."nomad.d/consul-token.json".path;
      };
      # Client configuration
      nomad-client-cfg = {
        target = "nomad.d/client.json";
        source = ../../config/nomad.d/client.json;
      };
    } // lib.optionalAttrs cfg.server {
      # Server configuration
      nomad-server-cfg = {
        target = "nomad.d/server.json";
        source = ../../config/nomad.d/server.json;
      };
    } // lib.optionalAttrs (! isNull cfg.host-config) {
      # Host-specific configuration
      nomad-host-cfg = {
        target = "nomad.d/host.hcl";
        source = cfg.host-config;
      };
    };

    age.secrets = {
      "nomad.d/consul-token.json" = {
        file = if cfg.server
               then ../../secrets/nomad.d/consul-token-server.json.age
               else ../../secrets/nomad.d/consul-token-client.json.age;
        mode = "644";
      };
    };

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