{ pkgs, config, lib, ... }:
with lib;
let
  cfg = config.eboskma.keycloak;

  keywindTheme = pkgs.stdenv.mkDerivation {
    pname = "keycloak-theme-keywind";
    version = "unstable-2023-10-22";

    src = pkgs.fetchFromGitHub {
      owner = "lukin";
      repo = "keywind";
      rev = "b1c47673ae091bc1a85a04434f2929ba5b8fa8bf";
      hash = "sha256-Y88L7oW127Fex2D33A0tMnaJtSvM7hFZkzuVXZYoBhQ=";
    };

    doConfigure = false;
    doBuild = false;
    doCheck = false;

    installPhase = ''
      mkdir $out
      cp -r $src/theme/keywind/* $out/
    '';

  };
in
{
  options.eboskma.keycloak = { enable = mkEnableOption "keycloak"; };

  config = mkIf cfg.enable {
    services.keycloak = {
      enable = true;
      database.passwordFile = config.sops.secrets.keycloak-db-password.path;

      settings = {
        hostname = "id.datarift.nl";
        http-host = "127.0.0.1";
        http-port = 8081;
        proxy = "edge";
        features = "docker";
      };

      themes = {
        keywind = keywindTheme;
      };

      plugins = [
        (pkgs.callPackage ./keycloak-orgs.nix {
          inherit (pkgs) fetchFromGitHub;
          inherit (pkgs.maven) buildMavenPackage;
        })
        (pkgs.callPackage ./keycloak-admin-ui.nix {
          inherit (pkgs) fetchFromGitHub;
          inherit (pkgs.maven) buildMavenPackage;
          keycloak = config.services.keycloak.package;
        })
        (pkgs.callPackage ./phasetwo-admin-ui.nix {
          inherit (pkgs) stdenv fetchFromGitHub;
        })
      ];
    };

    services. caddy = {
      enable = true;

      email = "erwin@datarift.nl";

      virtualHosts = {
        "${config.services.keycloak.settings.hostname}" = {
          extraConfig = ''
            @public_or_allowed_remote {
              expression path('/realms/*', '/resources/*', '/js/*', '/robots.txt') || remote_ip('86.85.243.40/32', '2a02:a441:c959:1::/64', '100.64.0.0/10', 'fd7a:115c:a1e0:ab12:4843:cd96:6240:0000/106')
            }

            route {
                  reverse_proxy @public_or_allowed_remote ${config.services.keycloak.settings.http-host}:${toString config.services.keycloak.settings.http-port}

                  error "Nope." 401
            }
          '';
        };
      };
    };

    security.acme.acceptTerms = true;

    networking.firewall.allowedTCPPorts = [ 80 443 ];
  };
}