{ depot, config, ... }:

let
  authentikEnvironment = {
    POSTGRES_PASSWORD = "";
    AUTHENTIK_POSTGRESQL__USER = "authentik";
    AUTHENTIK_POSTGRESQL__PASSWORD = "";
    AUTHENTIK_POSTGRESQL__HOST = "";
    PROMETHEUS_MULTIPROC_DIR = "/tmp";
  };
in
{
  services.nginx.virtualHosts."auth.lukegb.com" = {
    forceSSL = true;
    locations."/" = {
      proxyPass = "http://localhost:9000/";
      proxyWebsockets = true;
    };
  };
  my.vault.acmeCertificates."auth.lukegb.com" = {
    hostnames = [ "auth.lukegb.com" ];
    nginxVirtualHosts = [ "auth.lukegb.com" ];
  };

  users.groups.authentik = {};
  users.users.authentik = {
    group = "authentik";
    isSystemUser = true;
  };

  systemd.services.authentik-server = {
    environment = authentikEnvironment;
    wants = [ "network.target" "postgresql.service" ];
    wantedBy = [ "multi-user.target" ];
    script = ''
      ${depot.nix.pkgs.authentik.server}/bin/authentik-django-admin migrate
      exec ${depot.nix.pkgs.authentik.server}/bin/authentik-server
    '';
    serviceConfig = {
      User = "authentik";
      PrivateTmp = true;
      EnvironmentFile = config.my.vault.secrets.authentik-environment.path;
    };
  };
  systemd.services.authentik-worker = {
    environment = authentikEnvironment;
    wants = [ "network.target" "postgresql.service" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      User = "authentik";
      ExecStart = "${depot.nix.pkgs.authentik.server}/bin/authentik-celery -A authentik.root.celery worker -Ofair --max-tasks-per-child=1 --autoscale 3,1 -E -B -s /tmp/celerybeat-schedule -Q authentik,authentik_scheduled,authentik_events";
      PrivateTmp = true;
      EnvironmentFile = config.my.vault.secrets.authentik-environment.path;
    };
  };

  my.vault.secrets.authentik-environment = {
    restartUnits = ["authentik-worker.service" "authentik-server.service"];
    group = "root";
    template = ''
      {{ with secret "kv/apps/authentik" }}
      {{ .Data.data.environment }}
      {{ end }}
    '';
  };
}