{
  lib,
  config,
  globals,
  ...
}: {
  options.forgejo.enable = lib.mkEnableOption "forgejo";

  config = lib.mkIf config.forgejo.enable {
    kubernetes.resources = {
      secrets.forgejo.stringData.config = lib.generators.toINI {} (import ./config.nix);

      deployments.server.spec = {
        selector.matchLabels.app = "forgejo";

        strategy = {
          type = "RollingUpdate";

          rollingUpdate = {
            maxSurge = 0;
            maxUnavailable = 1;
          };
        };

        template = {
          metadata.labels.app = "forgejo";

          spec = {
            # This disables services from becoming environmental variables
            # to prevent SSH_PORT clashing with Forgejo config.
            enableServiceLinks = false;

            containers.forgejo = {
              image = globals.images.forgejo;
              imagePullPolicy = "IfNotPresent";

              env = {
                USER_UID.value = "1000";
                USER_GID.value = "1000";
              };

              ports = {
                web.containerPort = 3000;
                ssh.containerPort = 22;
              };

              volumeMounts = [
                {
                  name = "data";
                  mountPath = "/data";
                }
                {
                  name = "config";
                  mountPath = "/data/gitea/conf/app.ini";
                  subPath = "config";
                }
              ];
            };

            volumes = {
              data.persistentVolumeClaim.claimName = "data";
              config.secret.secretName = "forgejo";
            };
          };
        };
      };

      services = {
        web.spec = {
          selector.app = "forgejo";

          ports.web = {
            port = 80;
            targetPort = "web";
          };
        };

        ssh.spec = {
          type = "LoadBalancer";
          loadBalancerIP = globals.gitIPv4;
          selector.app = "forgejo";

          ports.ssh = {
            port = 56287;
            targetPort = "ssh";
          };
        };
      };
    };

    lab = {
      ingresses.web = {
        host = "git.kun.is";

        service = {
          name = "web";
          portName = "web";
        };
      };

      longhorn.persistentVolumeClaim.data = {
        volumeName = "forgejo";
        storage = "20Gi";
      };
    };
  };
}