{ config, pkgs, lib, ... }:
with lib;
let
  cfgBase = config.base;
  cfg = config.services.ppForgejo;
in
{
  options.services.ppForgejo = {
    domain = mkOption {
      type = types.str;
      default = "git.${cfgBase.domainName}";
      example = "git.example.com";
      description = "The domain of the server";
    };
    openIdEnabled = mkOption {
      type = types.bool;
      default = false;
      description = "If OpenId provider is setup and should be used exclusively.";
    };
    openIdClientName = mkOption {
      type = types.str;
      default = "";
      description = "The name (id) of the openId client to use exclusively.";
    };
    dbPasswordFile = mkOption {
      type = types.path;
      default = "/etc/forgejo_db_pwd";
      description = "The file containing the database password. Be sure to secure it.";
    };
    actionsEnabled = mkOption {
      type = types.bool;
      default = false;
      description = "Enable the use of actions";
    };
  };

  config = {

    services.forgejo.settings.DEFAULT.APP_NAME = "git";
    services.forgejo.stateDir = "/var/lib/forgejo"; # default value, /var/lib/gitea in gitea, move it before migration!
                                                    # carefull to change ownership from gitea to forgejo
                                                    # and to move /var/lib/forgejo/data/gitea.db to /var/lib/forgejo/data/forgejo.db
    services.forgejo.enable = true;
    services.forgejo.settings.server.ROOT_URL = "https://${cfg.domain}/";
    services.forgejo.settings.session.COOKIE_SECURE = lib.mkForce true;        # Why do I need to override this???

    services.forgejo.user = "git";
    users.users.git = {
      home = config.services.forgejo.stateDir;
      useDefaultShell = true;
      isSystemUser = true;
      group = "git";
    };
    users.groups.git = {};

    # If true, openid users cannot create new account
    #services.forgejo.settings.service.DISABLE_REGISTRATION = lib.mkForce (!cfg.openIdEnabled);
    services.forgejo.settings.service.DISABLE_REGISTRATION = lib.mkForce false;
    services.forgejo.settings.service.ALLOW_ONLY_EXTERNAL_REGISTRATION = cfg.openIdEnabled;

    services.forgejo.lfs.enable = true;
    services.forgejo.settings.server.DOMAIN = cfg.domain;
    # services.forgejo.database.type = "postgres"; # Default is sqlite3, probably better for a small instance
    services.forgejo.database.passwordFile = cfg.dbPasswordFile;

    services.forgejo.settings.repository.ENABLE_PUSH_CREATE_USER = true;
    services.forgejo.settings.repository.ENABLE_PUSH_CREATE_ORG = true;
    services.forgejo.settings.repository.DEFAULT_REPO_UNITS = "repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages,repo.actions";

    # Set the permittions for the db file
    system.activationScripts = {
      forgejoDbFilePermission.text = 
      ''
        chmod 400 ${cfg.dbPasswordFile}
        chown ${config.services.forgejo.user} ${cfg.dbPasswordFile}
      '';
    };
    environment.systemPackages = with pkgs; [
      forgejo
    ];
    systemd.services.forgejo.environment.FORGEJO_CUSTOM = "${config.services.forgejo.stateDir}/custom";
    services.forgejo.settings = {
      ui = {
        THEMES = "forgejo-auto,forgejo-light,forgejo-dark,auto,gitea,arc-green";
        DEFAULT_THEME = "forgejo-auto";
      };
      "ui.meta" = {
        DESCRIPTION = "Code everywhere";
      };
    };


    services.forgejo.settings.actions = lib.mkIf (cfg.actionsEnabled) {
      ENABLED = true;
      DEFAULT_ACTION_URL = "https://${cfg.domain}";
    };
  

    # NGINX
    security.acme.acceptTerms = true;
    security.acme.defaults.email = cfgBase.adminEmail;
    services.nginx = {
        enable = true;
        virtualHosts = {
          "${cfg.domain}" = {
            forceSSL = true;
            enableACME = true;
            locations."/" = {
              proxyPass = "http://127.0.0.1:3000";
              extraConfig = ''
                client_max_body_size 0;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Server $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $host;
                proxy_pass_request_headers on;
              '';
            };
            locations."/user/login" = lib.mkIf (cfg.openIdEnabled) {
              return = "301 https://$host/user/oauth2/${cfg.openIdClientName}";
            };
          };
        };
      };
    networking.firewall.allowedTCPPorts = [ 80 443 ];
  };
}