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

let
  gpg_test_wkd =
    (pkgs.writeScriptBin "gpg_test_wkd" (builtins.readFile ./files/gpg_test_wkd.bash)).overrideAttrs
      (old: {
        buildCommand = "${old.buildCommand}\n patchShebangs $out";

      });
in
{
  imports = [ ];

  options.me = {
    gpg.enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      example = true;
      description = "Whether we want to install gpg.";
    };
  };

  config = lib.mkIf config.me.gpg.enable (
    lib.mkMerge [
      {
        # Fetch public keys:
        # gpg --locate-keys tom@fizz.buzz
        #
        # gpg -vvv --auto-key-locate local,wkd --locate-keys tom@fizz.buzz

        hardware.gpgSmartcards.enable = true;
        services.udev.packages = [
          pkgs.yubikey-personalization
          pkgs.libfido2
          (pkgs.writeTextFile {
            name = "my-rules";
            text = ''
              ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0406", MODE="660", GROUP="wheel"
              KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1050", ATTRS{idProduct}=="0406", TAG+="uaccess", GROUP="wheel", MODE="0660"
            '';
            destination = "/etc/udev/rules.d/50-yubikey.rules";
          })
        ];
        services.pcscd.enable = true;
        # services.gnome.gnome-keyring.enable = true;

        # services.dbus.packages = [ pkgs.gcr ];

        # services.pcscd.plugins = lib.mkForce [ ];

        #   programs.gpg.scdaemonSettings = {
        #   disable-ccid = true;
        # };

        # .gnupg/scdaemon.conf
        home-manager.users.talexander =
          { pkgs, ... }:
          {
            home.file.".gnupg/scdaemon.conf" = {
              source = ./files/scdaemon.conf;
            };
          };

        # programs.gnupg.dirmngr.enable = true;
        programs.gnupg.agent = {
          enable = true;
          enableSSHSupport = true;
          pinentryPackage = pkgs.pinentry-qt;
          # settings = {
          #   disable-ccid = true;
          # };
        };

        environment.persistence."/persist" = lib.mkIf (!config.me.buildingIso) {
          hideMounts = true;
          users.talexander = {
            directories = [
              {
                directory = ".gnupg";
                user = "talexander";
                group = "talexander";
                mode = "0700";
              } # Local keyring
            ];
          };
        };

        environment.systemPackages = with pkgs; [
          pcsclite
          pcsctools
          yubikey-personalization
          yubikey-manager
          glibcLocales
          ccid
          libusb-compat-0_1
          gpg_test_wkd
        ];

        programs.gnupg.agent.enableExtraSocket = true;
      }
    ]
  );
}