{ config, containerCfg, pkgs, lib, builder, name, ... }:
let 
  version = "2026.2.2";
  serverCfg = config.syscfg.server;
  mediaCfg = config.syscfg.media;
  authentikBackground = if mediaCfg.banner.png != null then mediaCfg.banner.png else mediaCfg.bg;
  logoSvgFileName = builtins.baseNameOf (toString mediaCfg.logo.svg);
  logoIcoFileName = builtins.baseNameOf (toString mediaCfg.logo.ico);
  backgroundFileName = builtins.baseNameOf (toString authentikBackground);
  logoSvgMount = "/data/media/public/branding/${logoSvgFileName}";
  logoIcoMount = "/data/media/public/branding/${logoIcoFileName}";
  backgroundMount = "/data/media/public/branding/${backgroundFileName}";
  authentikData = builder.mkData { 
    name = "authentik"; dir = "authentik"; vars = {
      AUTHENTIK_DOMAIN = "${containerCfg.subdomain}.${serverCfg.domain}";
      COOKIE_DOMAIN = "${serverCfg.domain}";
      AUTHENTIK_LDAP_DC_DOMAIN = "dc=ldap," + (lib.concatMapStringsSep "," (x: "dc=${x}") (lib.splitString "." serverCfg.domain));
      AUTHENTIK_BRANDING_TITLE = if containerCfg.extra ? name then containerCfg.extra.name else "authentik";
      AUTHENTIK_BRANDING_LOGO = "branding/${logoSvgFileName}";
      AUTHENTIK_BRANDING_FAVICON = "branding/${logoIcoFileName}";
      AUTHENTIK_BRANDING_BACKGROUND = "branding/${backgroundFileName}";
    } 
    // (if serverCfg.containers?jellyfin then { JELLYFIN_DOMAIN = "${serverCfg.containers.jellyfin.subdomain}.${serverCfg.domain}";} else {})
    // (if serverCfg.containers?gitea then { GITEA_DOMAIN = "${serverCfg.containers.gitea.subdomain}.${serverCfg.domain}";} else {})
    // (if serverCfg.containers?immich then { IMMICH_DOMAIN = "${serverCfg.containers.immich.subdomain}.${serverCfg.domain}";} else {})
    // (if serverCfg.containers?freshrss then { FRESHRSS_DOMAIN = "${serverCfg.containers.freshrss.subdomain}.${serverCfg.domain}";} else {})
    // (if serverCfg.containers?homepage then { HOMEPAGE_DOMAIN = "${serverCfg.containers.homepage.subdomain}.${serverCfg.domain}";} else {})
    // (if serverCfg.containers?nextcloud then { NEXTCLOUD_DOMAIN = "${serverCfg.containers.nextcloud.subdomain}.${serverCfg.domain}";} else {});
  };
in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [{
      path="${serverCfg.path.config.path}/authentik";
      owner = "1000:1000";
      dirs = ["media" "templates"];
      mode = "0755";
    }];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "ghcr.io/goauthentik/server:${version}";
        port = 9000;
        secret = name;
        extraEnv = {
          AUTHENTIK_REDIS__HOST = builder.host;
          AUTHENTIK_POSTGRESQL__HOST = builder.host;
          AUTHENTIK_POSTGRESQL__USER = "authentik_user";
          AUTHENTIK_POSTGRESQL__NAME = "authentik_db";
          AUTHENTIK_POSAUTHENTIK_POSTGRESQL__SSLMODE = "false";
          AUTHENTIK_DISABLE_UPDATE_CHECK = "true";
          AUTHENTIK_POSTGRESQL__SSLMODE = "disable";
        } // lib.optionalAttrs (serverCfg.mail.server != null) {
          AUTHENTIK_EMAIL__HOST = serverCfg.mail.server;
          AUTHENTIK_EMAIL__PORT = "587";
          AUTHENTIK_EMAIL__USERNAME = "noreply@${serverCfg.domain}";
          AUTHENTIK_EMAIL__USE_TLS = "true";
          AUTHENTIK_EMAIL__USE_SSL = "false";
          AUTHENTIK_EMAIL__TIMEOUT = "10";
          AUTHENTIK_EMAIL__FROM = "sso@noreply.${serverCfg.domain}";
        };
        overrides = {
          environmentFiles =  [ config.sops.secrets."AUTHENTIK".path config.sops.secrets."CUSTOM".path ] ;
        
          cmd = [ "server" ];
          volumes = [
            "${serverCfg.path.config.path}/authentik/media:/media"
            "${serverCfg.path.config.path}/authentik/templates:/templates"
            "${authentikData}:/blueprints/custom:ro"
            "${mediaCfg.logo.svg}:${logoSvgMount}:ro"
            "${mediaCfg.logo.ico}:${logoIcoMount}:ro"
            "${authentikBackground}:${backgroundMount}:ro"
          ];
        };
      };

      worker = builder.mkContainer {
        image = "ghcr.io/goauthentik/server:${version}";
        secret = name;
        extraEnv = {
          AUTHENTIK_REDIS__HOST = builder.host;
          AUTHENTIK_POSTGRESQL__HOST = builder.host;
          AUTHENTIK_POSTGRESQL__USER = "authentik_user";
          AUTHENTIK_POSTGRESQL__NAME = "authentik_db";
          AUTHENTIK_POSAUTHENTIK_POSTGRESQL__SSLMODE = "false";
          AUTHENTIK_DISABLE_UPDATE_CHECK = "true";
          AUTHENTIK_POSTGRESQL__SSLMODE = "disable";
        };
        overrides = {
          cmd = [ "worker" ];
          volumes = [
            "${serverCfg.path.config.path}/authentik/media:/media"
            "${serverCfg.path.config.path}/authentik/templates:/templates"
            "${authentikData}:/blueprints/custom:ro"
            "${mediaCfg.logo.svg}:${logoSvgMount}:ro"
            "${mediaCfg.logo.ico}:${logoIcoMount}:ro"
            "${authentikBackground}:${backgroundMount}:ro"
          ];
        };
      };

      ldap = builder.mkContainer {
        image = "ghcr.io/goauthentik/ldap:${version}";
        secret = name;
        extraEnv = {
          AUTHENTIK_HOST = "https://${containerCfg.subdomain}.${serverCfg.domain}"; 
          AUTHENTIK_INSECURE = "false"; 
        };
      };
    };

    setup = {
      trigger = "worker";
      script = pkgs.writeShellScript "setup" ''
        # Define the command wrapper
        AK="${pkgs.podman}/bin/podman --events-backend=none exec --env-file ${config.sops.secrets."CUSTOM".path} -e DOMAIN=${serverCfg.domain} -u root authentik-worker ak"

        $AK apply_blueprint /blueprints/custom/authentik.yaml
        $AK apply_blueprint /blueprints/custom/branding.yaml
        $AK apply_blueprint /blueprints/custom/traefik.yaml
        $AK apply_blueprint /blueprints/custom/ldap.yaml

        ${lib.optionalString (serverCfg.containers ? gitea) ''$AK apply_blueprint /blueprints/custom/gitea.yaml''}
        ${lib.optionalString (serverCfg.containers ? jellyfin) ''$AK apply_blueprint /blueprints/custom/jellyfin.yaml''}
        ${lib.optionalString (serverCfg.containers ? nextcloud) ''$AK apply_blueprint /blueprints/custom/nextcloud.yaml''}
        ${lib.optionalString (serverCfg.containers ? immich) ''$AK apply_blueprint /blueprints/custom/immich.yaml''}
        ${lib.optionalString (serverCfg.containers ? freshrss) ''$AK apply_blueprint /blueprints/custom/freshrss.yaml''}
        ${lib.optionalString (serverCfg.containers ? homepage) ''$AK apply_blueprint /blueprints/custom/homepage.yaml''}

        echo "Completed Authentik Setup"
      '';
    };
  };
}
