{ pkgs, lib, ... }:

let

  custom_gnupg = pkgs.gnupg.overrideAttrs (final: prev: {
    configureFlags = prev.configureFlags ++ [
      # Make sure scdaemon never ever again tries to use its own ccid driver
      "--disable-ccid-driver"
    ];
  });

in {

  programs.gnupg.package = custom_gnupg;
  programs.gnupg.agent = {
    enable = true;
    enableSSHSupport = true;
    pinentryPackage = lib.mkDefault pkgs.pinentry-curses;
  };

  environment.systemPackages = with pkgs; [
    custom_gnupg
    yubikey-personalization
    openpgp-card-tools

    # Add wrapper around ssh that takes the gnupg ssh-agent
    # instead of gnome-keyring
    ssh-gpg
  ];

  services.pcscd.enable = true;

  # pcscd sometimes breaks and seem to need a manual restart
  # so we allow users to restart that service themself
  security.polkit.extraConfig = ''
    polkit.addRule(function(action, subject) {
        if (
            action.id == "org.freedesktop.systemd1.manage-units"
            && action.lookup("unit") == "pcscd.service"
            && action.lookup("verb") == "restart"
            && subject.isInGroup("users")
        ) {
            return polkit.Result.YES;
        }
    });
  '';

  services.udev.packages = with pkgs; [
    yubikey-personalization
  ];
}