{ pkgs, lib, config, ... }: 
let
  base = "muon.host";
  domain = "head.${base}";
in {
  options.mods.server.headscale = {
    enable = lib.mkEnableOption {
      default = false;
      description = "enables headscale server";
    };
  };

  config = lib.mkIf config.mods.server.headscale.enable {
    services = {
      headscale = {
        enable = true;
        port = 8085;
        address = "127.0.0.1";
        settings = {
          dns_config = {
            override_local_dns = true;
            base_domain = "${base}";
            magic_dns = true;
            domains = [ "${domain}" ];
            nameservers = [
              "9.9.9.9"
            ];
          };
          server_url = "https://${domain}";
          metrics_listen_addr = "127.0.0.1:8095";
          logtail.enabled = false;
          log.level = "warn";
          ip_prefixes = [
            "100.64.0.0/10"
          ];
        };
      };

      nginx.enable = true;
      nginx.virtualHosts.${domain} = {
        forceSSL = true;
        enableACME = true;
        locations = {
          "/" = {
            proxyPass = "http://localhost:${toString config.services.headscale.port}";
            proxyWebsockets = true;
          };
          "/metrics" = {
            proxyPass = "http://${config.services.headscale.settings.metrics_listen_addr}/metrics";
          };
        };
      };
    };

    security.acme = {
      acceptTerms = true;
      defaults.email = "acme@muon.host";
    };

    environment.systemPackages = [ config.services.headscale.package ];
  };
}
