{ config, lib, ... }:

with lib;

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

  config = mkIf cfg.enable {
    services.podman.containers.karakeep = {
      image = "ghcr.io/karakeep-app/karakeep:release";
      network = "proxy";
      volumes = [
        "%h/containers/karakeep/data:/data" 
      ];
      environment = {
        MEILI_ADDR = "http://karakeep-meilisearch:7700";
        BROWSER_WEB_URL = "http://karakeep-chrome:9222";
        DATA_DIR = "/data";
      };
      environmentFile = [
        "${config.sops.templates."container-karakeep.env".path}"
      ];
      extraConfig = {
        Unit = {
          After = [
            "podman-karakeep-chrome.service"
            "podman-karakeep-meilisearch.service"
          ];
          Requires = [
            "podman-karakeep-chrome.service"
            "podman-karakeep-meilisearch.service"
          ];
        };
      };
    };

    services.podman.containers.karakeep-chrome = {
      image = "gcr.io/zenika-hub/alpine-chrome:123";
      network = "proxy";
      exec = "--no-sandbox --disable-gpu --disable-dev-shm-usage --remote-debugging-address=0.0.0.0 --remote-debugging-port=9222 --hide-scrollbars";
    };

    services.podman.containers.karakeep-meilisearch = {
      image = "getmeili/meilisearch:v1.13.3";
      network = "proxy";
      environment = {
        MEILI_NO_ANALYTICS = "true";
      };
      volumes = [
        "%h/containers/karakeep/meilisearch:/meili_data" 
      ];
    };

    settings.services.sops.enable = true;

    sops.secrets = {
      "containers/karakeep/nextauth-secret" = { };
      "containers/karakeep/meili-key" = { };
    };

    sops.templates = {
      "container-karakeep.env" = {
        content = ''
          KARAKEEP_VERSION=release
          NEXTAUTH_SECRET=${config.sops.placeholder."containers/karakeep/nextauth-secret"}
          MEILI_MASTER_KEY=${config.sops.placeholder."containers/karakeep/meili-key"}
          NEXTAUTH_URL=https://karakeep.local.tbmrs.nl
        '';
      };
    };
  };
}
