{ config, pkgs, inputs, lib, system, ... }:
let
  unstable = inputs.nixpkgs-nixos-unstable;
  package = unstable.legacyPackages."${system}".forgejo;
  httpPort = 8083;
  sshPort = 22;
  domain = "git.cyplo.dev";
  emailDomain = "peninsula.industries";
  baseurl = "https://${domain}";
  mailgunSmtpSecretName = "forgejo-mailgun-smtp-password";
  mailgunSmtpPasswordPath = "/run/secrets/${mailgunSmtpSecretName}";
  uid = 2051;
  gid = 3051;
  systemUserName = "forgejo";
  systemGroupName = "forgejo";
  users = {
    users."${systemUserName}" = {
      inherit uid;
      isSystemUser = true;
      isNormalUser = false;
      group = systemGroupName;
    };
    groups."${systemGroupName}" = {
      inherit gid;
      members = [ "${systemUserName}" "nginx" ];
    };
  };
in {
  imports =
    [ ../nginx.nix "${unstable}/nixos/modules/services/misc/forgejo.nix" ];
  disabledModules = [ "services/misc/forgejo.nix" ];

  inherit users;

  boot.kernel.sysctl = { "net.ipv4.ip_unprivileged_port_start" = 0; };
  systemd.services.systemd-sysctl.enable = lib.mkForce true;

  networking.firewall.allowedTCPPorts = [ sshPort ];
  services.nginx = {
    virtualHosts = {
      "${domain}" = {
        forceSSL = true;
        enableACME = true;
        locations."/" = {
          proxyPass = "http://127.0.0.1:" + toString httpPort;
        };
      };
    };
  };

  sops.secrets."${mailgunSmtpSecretName}" = {
    sopsFile = ./mailgun.sops.yaml;
    path = mailgunSmtpPasswordPath;
    owner = systemUserName;
    group = systemGroupName;
  };

  services.forgejo = {
    enable = true;
    inherit package;
    user = systemUserName;
    mailerPasswordFile = mailgunSmtpPasswordPath;
    lfs.enable = true;
    database.type = "sqlite3";
    settings = {
      service.DISABLE_REGISTRATION = true;
      security.INSTALL_LOCK = true;
      oauth2.ENABLE = false;
      log.LEVEL = "Info";
      actions.ENABLED = true;
      "git.timeout" = {
        DEFAULT = 600;
        MIGRATE = 3600;
        MIRROR = 3600;
        CLONE = 600;
        PULL = 600;
        GC = 600;
      };
      "cron".ENABLED = true;
      "cron.git_gc_repos".ENABLED = true;
      "cron.delete_old_actions".ENABLED = true;
      "cron.delete_old_system_notices".ENABLED = true;
      "cron.gc_lfs".ENABLED = true;
      server = {
        ROOT_URL = baseurl;
        DOMAIN = domain;
        START_SSH_SERVER = true;
        SSH_PORT = sshPort;
        HTTP_PORT = httpPort;
        SSH_LISTEN_PORT = sshPort;
        DISABLE_SSH = false;
      };
      mailer = {
        ENABLED = true;
        FROM = "git.cyplo.dev <forgejo@${emailDomain}>";
        PROTOCOL = "smtps";
        SMTP_ADDR = "smtp.eu.mailgun.org";
        SMTP_PORT = 465;
        USER = "postmaster@${emailDomain}";
      };
    };
  };
}
