{ pkgs, ... }:
let
  domain = "git.fediversity.eu";
in
{
  services.forgejo = {
    enable = true;
    lfs.enable = true;
    settings = {
      service = {
        DISABLE_REGISTRATION = true;
      };
      server = {
        DOMAIN = "${domain}";
        ROOT_URL = "https://${domain}/";
        HTTP_ADDR = "127.0.0.1";
        LANDING_PAGE = "explore";
      };
    };

    settings.service.ENABLE_NOTIFY_MAIL = true;
    settings.mailer = {
      ENABLED = true;
      PROTOCOL = "smtp+starttls";
      SMTP_ADDR = "mail.protagio.nl";
      SMTP_PORT = "587";
      FROM = "git@fediversity.eu";
      USER = "git@fediversity.eu";
    };
    secrets.mailer.PASSWD = "/var/lib/forgejo/data/keys/forgejo-mailpw";

    database = {
      type = "mysql";
      socket = "/run/mysqld/mysqld.sock";
      passwordFile = "/var/lib/forgejo/data/keys/forgejo-dbpassword";
    };
  };

  users.groups.keys.members = [ "forgejo" ];

  services.mysql = {
    enable = true;
    package = pkgs.mariadb;
    ensureDatabases = [ "forgejo" ];
    ensureUsers = [
      {
        name = "forgejo";
        ensurePermissions = {
          "forgejo.*" = "ALL PRIVILEGES";
        };
      }
    ];
  };

  security.acme = {
    acceptTerms = true;
    defaults.email = "beheer@procolix.com";
  };

  services.nginx = {
    enable = true;
    recommendedTlsSettings = true;
    recommendedOptimisation = true;
    recommendedGzipSettings = true;
    recommendedProxySettings = true;
    clientMaxBodySize = "500m";
    appendHttpConfig = ''


      map $uri $forgejo_access_log {
        default 1;
        /api/actions/runner.v1.RunnerService/FetchTask 0;
      }

      # Add HSTS header with preloading to HTTPS requests.
      # Adding this header to HTTP requests is discouraged
      map $scheme $hsts_header {
          https   "max-age=31536000; includeSubdomains; always";
      }
      add_header Strict-Transport-Security $hsts_header;
    '';
    virtualHosts.${domain} = {
      listenAddresses = [
        "185.206.232.34"
        "[2a00:51c0:12:1201::20]"
      ];
      enableACME = true;
      forceSSL = true;
      locations."/" = {
        proxyPass = "http://127.0.0.1:3000/";
        extraConfig = ''
          proxy_set_header X-Real-IP $remote_addr;
          #access_log /var/log/nginx/access.log info if=$forgejo_access_log;
        '';
      };
    };
  };
}
