{ config, ... }:

{
  age.secrets = {
    ldap = {
      mode = "440";
      group = "authelia-main";
    };
    jwt = {
      file = ../secrets/jwt.age;
      owner = "authelia-main";
      group = "authelia-main";
      mode = "440";
    };
    autheliaSession = {
      file = ../secrets/authelia_session.age;
      owner = "authelia-main";
      group = "authelia-main";
      mode = "440";
    };
    autheliaStorageEncryptionKey = {
      file = ../secrets/authelia_storage.age;
      owner = "authelia-main";
      group = "authelia-main";
      mode = "440";
    };
  };
  services = {
    postgresql = {
      ensureDatabases = [ "authelia" ];
      ensureUsers = [
        {
          name = "authelia";
          ensureDBOwnership = true;
        }
      ];
    };
    authelia.instances.main = {
      enable = true;
      secrets = {
        jwtSecretFile = config.age.secrets.jwt.path;
        sessionSecretFile = config.age.secrets.autheliaSession.path;
        storageEncryptionKeyFile = config.age.secrets.autheliaStorageEncryptionKey.path;
      };
      environmentVariables = {
        AUTHELIA_AUTHENTICATION_BACKEND_LDAP_PASSWORD_FILE = config.age.secrets.ldap.path;
      };
      settings = {
        authentication_backend = {
          password_reset.disable = false;
          refresh_interval = "1m";
          ldap = {
            implementation = "custom";
            address = "ldap://localhost:3890";
            timeout = "5s";
            start_tls = false;
            base_dn = "dc=thewordnerd,dc=info";
            additional_users_dn = "ou=people";
            users_filter = "(&({username_attribute}={input})(objectClass=person))";
            additional_groups_dn = "ou=groups";
            groups_filter = "(member={dn})";
            user = "uid=service,ou=people,dc=thewordnerd,dc=info";
            attributes = {
              username = "uid";
              display_name = "displayName";
              group_name = "cn";
              mail = "mail";
            };
          };
        };
        storage = {
          postgres = {
            address = "/run/postgresql";
            database = "authelia";
            username = "authelia";
            password = "trusted";
          };
        };
        access_control = {
          rules = [
            {
              domain = "*.thewordnerd.info";
              policy = "one_factor";
            }
          ];
        };
        session = {
          cookies = [
            {
              domain = "thewordnerd.info";
              authelia_url = "https://auth.thewordnerd.info";
            }
          ];
        };
        notifier = {
          filesystem = {
            filename = "/tmp/authelia.txt";
          };
        };
        server.endpoints.authz.forward-auth.implementation = "ForwardAuth";
      };
    };
    caddy.globalConfig = ''
      servers {
        trusted_proxies static 192.168.0.1
      }
    '';
  };
}