{ options, config, lib, pkgs, ... }:

with lib;
with lib.metacfg;
let
  cfg = config.metacfg.pccs;
  cfg_podman = config.metacfg.podman;
in
{
  options.metacfg.pccs = with types; {
    enable = mkBoolOpt false "Whether or not to enable a SGX-DCAP.";
    secret = mkOption {
      type = with types; nullOr path;
      default = null;
      example = literalExpression "config.sops.secrets.pccs.path";
      description = lib.mdDoc "path to the pccs secret file";
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      {
        assertion = cfg.secret != null;
        message = "path to the pccs secret file is required when pccs is enabled";
      }
      {
        assertion = cfg_podman.enable;
        message = "podman must be enabled when pccs is enabled";
      }
    ];

    metacfg = {
      nix.extra-substituters = {
        "https://nixsgx.cachix.org".key = "nixsgx.cachix.org-1:tGi36DlY2joNsIXOlGnSgWW0+E094V6hW0umQRo/KoE=";
      };
    };

    virtualisation.oci-containers.backend = "podman";
    virtualisation.oci-containers.containers = {
      # podman run --pull=always --name pccs -it --rm -v /dev/log:/dev/log --secret PCCS_CONFIG,type=mount -p 8081:8081 registry.gitlab.com/haraldh/pccs:pccs_1_19
      pccs = {
        image = "docker.io/backslashhh/pccs:dcap_1_19";
        autoStart = true;
        ports = [ "8081:8081" ];
        extraOptions = [
          "--volume=/dev/log:/dev/log"
          "--secret=PCCS_CONFIG,type=mount"
        ];
      };
    };

    systemd.services.pccs-secret =
      {
        description = "Inject pccs secret";
        wantedBy = [ "multi-user.target" ];
        before = [ "podman-pccs.service" ];

        serviceConfig = {
          EnvironmentFile = cfg.secret;
          ExecStart = ''
            -${pkgs.podman}/bin/podman secret create --env PCCS_CONFIG PCCS_CONFIG
          '';
          RemainAfterExit = true;
        };
      };


  };
}