{ config, pkgs, ... }:
let
  domain = "git.ccnlc.eu";
  sshPort = 2222;
in
{
  imports = [
    ./runner.nix
  ];

  systemd.tmpfiles.rules =
    let
      # Disallow crawlers from indexing this site.
      robots = pkgs.writeText "forgejo-robots-txt" ''
        User-agent: *
        Disallow: /
      '';
    in
    [
      "L+ ${config.services.forgejo.customDir}/public/robots.txt - - - - ${robots.outPath}"
    ];

  networking.firewall.allowedTCPPorts = [ sshPort ];

  services.nginx = {
    virtualHosts.${domain} = {
      locations."/" = {
        proxyPass = "http://unix:/run/forgejo/forgejo.sock";
        extraConfig = ''
          proxy_ssl_server_name on;
          proxy_pass_header Authorization;
          proxy_set_header X-Real-IP $remote_addr;
        '';
      };
      forceSSL = true;
      enableACME = true;
      quic = true;
    };
  };

  services.forgejo = {
    enable = true;
    package = pkgs.forgejo;

    settings = {
      server = {
        SSH_PORT = sshPort;
        SSH_LISTEN_PORT = sshPort;
        START_SSH_SERVER = true;
        DOMAIN = domain;
        HTTP_PORT = 3000;
        ROOT_URL = "https://${domain}";
        PROTOCOL = "http+unix";
        LANDING_PAGE = "/explore";
      };
      migrations.ALLOWED_DOMAINS = "*";
      service = {
        DISABLE_REGISTRATION = true;
      };
      packages.ENABLED = false;
      log.LEVEL = "Info";
      session = {
        COOKIE_SECURE = true;
        SAME_SITE = "strict";
      };
      federation = {
        ENABLED = true;
      };
      ui = {
        DEFAULT_THEME = "forgejo-dark";
        SHOW_USER_EMAIL = false;
      };
      security = {
        INSTALL_LOCK = true;
        MIN_PASSWORD_LENGTH = 30;
        PASSWORD_COMPLEXITY = "lower, upper, digit, spec";
        PASSWORD_CHECK_PWN = true;
        REVERSE_PROXY_LIMIT = 1;
        REVERSE_PROXY_TRUSTED_PROXIES = "127.0.0.1";
      };

      repository = {
        DISABLE_STARS = true;
        PREFERRED_LICENSES = "MIT,GPL-3.0,GPL-2.0,LGPL-3.0,LGPL-2.1";
        ENABLE_PUSH_CREATE_USER = true;

        DEFAULT_PRIVATE = "public";
        DEFAULT_PRIVATE_PUSH_CREATE = true;
        DEFAULT_REPO_UNITS = "repo.code, repo.issues, repo.pulls, repo.actions";
      };

      actions = {
        ENABLED = true;
        DEFAULT_ACTIONS_URL = "https://code.forgejo.org";
      };
    };
  };

  environment.etc = {
    "fail2ban/filter.d/forgejo-authentication.conf".text = # ini
      ''
        # forgejo
        [Definition]
        failregex =  .*(Failed authentication attempt|invalid credentials|Attempted access of unknown user).* from <HOST>
        ignoreregex =
        journalmatch = _SYSTEMD_UNIT=forgejo.service
      '';
  };

  services.fail2ban.jails.forgejo.settings = {
    enabled = true;
    filter = "forgejo-authentication";
    action = "nftables-allports";
    mode = "aggressive";
    maxretry = 5;
    findtime = 600;
  };
}