{
  config,
  common,
  ...
}:
let
  cfg = config.services.headscale;

  domain = "beta.vpn.${common.domain}";
  dnsDomain = "secure.${common.domain}";
in
{
  networking.firewall = {
    trustedInterfaces = [ config.services.tailscale.interfaceName ];
    allowedUDPPorts = [ config.services.tailscale.port ];
  };

  services = {
    headscale = {
      enable = true;
      address = "0.0.0.0";
      port = 8083;
      settings = {
        database = {
          postgres = {
            host = "/run/postgresql";
            name = "headscale";
            port = config.services.postgresql.settings.port;
            user = cfg.user;
          };
          type = "postgres";
        };
        dns = {
          base_domain = dnsDomain;
          magic_dns = true;
        };
        logtail.enabled = false;
        server_url = "https://${domain}";
      };
    };

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

    postgresql =
      let
        psql = cfg.settings.database.postgres;
      in
      {
        ensureDatabases = [ psql.name ];
        ensureUsers = [
          {
            name = psql.user;
            ensureDBOwnership = true;
          }
        ];
      };
  };

}
