{config, ...}: let
  inherit (config) sops;
  inherit (sops) templates placeholder;
  redis_port = "6380";
  authentik_port = "8084";
  postgres = {
    user = "authentik";
    db = "authentik";
    port = "5437";
  };
  authentik-config = {
    image = "ghcr.io/goauthentik/server:2023.10.7";
    volumes = ["/home/tristan/pods/authentik/media:/media"];
    environment = {
      AUTHENTIK_POSTGRESQL__USER = postgres.user;
      AUTHENTIK_POSTGRESQL__HOST = "192.168.1.2";
      AUTHENTIK_POSTGRESQL__PORT = postgres.port;
      AUTHENTIK_REDIS__HOST = "192.168.1.2";
      AUTHENTIK_REDIS__PORT = redis_port;
      AUTHENTIK_EMAIL__FROM = "Authentik <tristan@tristans.cloud>";
      AUTHENTIK_DEFAULT_USER_CHANGE_USERNAME = "false";
    };
    envFile = templates."authentik/environment".path;
  };
in {
  sops.secrets = {
    "authentik/postgres_password" = {};
    "authentik/secret_key" = {};
    "mail/host" = {};
    "mail/port" = {};
    "mail/username" = {};
    "mail/password" = {};
    "mail/ssl" = {};
  };
  sops.templates = {
    "authentik/environment" = {
      content = ''
        AUTHENTIK_POSTGRESQL__PASSWORD="${placeholder."authentik/postgres_password"}"
        AUTHENTIK_SECRET_KEY="${placeholder."authentik/secret_key"}"
        AUTHENTIK_EMAIL__HOST="${placeholder."mail/host"}"
        AUTHENTIK_EMAIL__PORT="${placeholder."mail/port"}"
        AUTHENTIK_EMAIL__USERNAME="${placeholder."mail/username"}"
        AUTHENTIK_EMAIL__PASSWORD="${placeholder."mail/password"}"
        AUTHENTIK_EMAIL__USE_SSL="${placeholder."mail/ssl"}"
      '';
    };
    "authentik/postgres_env" = {
      content = ''
        POSTGRES_PASSWORD="${placeholder."authentik/postgres_password"}"
      '';
    };
  };

  podman.authentik-redis = {
    image = "redis:latest";
    ports = ["${redis_port}:6379"];
  };

  podman.authentik-server =
    authentik-config
    // {
      command = "server";
      ports = ["${authentik_port}:9000" "9084:9300"];
    };

  podman.authentik-worker =
    authentik-config
    // {
      command = "worker";
    };

  podman.authentik-postgres = {
    image = "docker.io/postgres:14-alpine";
    ports = ["${postgres.port}:5432"];
    volumes = ["/home/tristan/pods/authentik/db:/var/lib/postgresql/data"];
    environment = {
      POSTGRES_USER = postgres.user;
      POSTGRES_DB = postgres.db;
    };
    envFile = templates."authentik/postgres_env".path;
  };

  services.nginx.virtualHosts."auth.tristans.cloud" = {
    forceSSL = true;
    enableACME = true;
    locations."~" = {
      proxyPass = "http://localhost:${authentik_port}";
      proxyWebsockets = true;
    };
  };
}
