{ config, lib, ... }:

with lib;

let
  cfg = config.settings.containers.linkding;
in {
  options = {
    settings.containers.linkding.enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Enable linkding container
      '';
    };
  };

  config = mkIf cfg.enable {
    services.podman.containers.linkding = {
      image = "ghcr.io/sissbruecker/linkding:latest";
      network = "proxy";
      volumes = [
        "%h/containers/linkding/data:/etc/linkding/data" 
      ];
      environment = {
        LD_ENABLE_OIDC = "True";
        OIDC_RP_CLIENT_ID = "linkding";
        OIDC_OP_AUTHORIZATION_ENDPOINT = "https://auth.tbmrs.nl/ui/oauth2";
        OIDC_OP_TOKEN_ENDPOINT = "https://auth.tbmrs.nl/oauth2/token";
        OIDC_OP_USER_ENDPOINT = "https://auth.tbmrs.nl/oauth2/openid/linkding/userinfo";
        OIDC_OP_JWKS_ENDPOINT = "https://auth.tbmrs.nl/oauth2/openid/linkding/public_key.jwk";
        OIDC_RP_SIGN_ALGO = "ES256";
      };
      environmentFile = [
        "${config.sops.templates."container-linkding.env".path}"
      ];
    };

    settings.containers.caddy.routes.tbmrs-local.routes.linkding = {
      host = "links";
      url = "linkding:9090"; 
    };

    settings.services.sops.enable = true;

    sops.templates = {
      "container-linkding.env" = {
        content = /*bash*/ ''
          OIDC_RP_CLIENT_SECRET=${config.sops.placeholder."containers/linkding/oidc-secret"}
        '';
      };
    };

    sops.secrets = {
      "containers/linkding/oidc-secret" = { };
    };
  };
}
