# Upstream to nixpkgs/nixos/modules/services/networking/ssh/openpgp-card-ssh-agent.nix
{
  config,
  lib,
  pkgs,
  ...
}:

let
  inherit (lib)
    mkIf
    mkPackageOption
    ;
  cfg = config.services.openpgp-card-ssh-agent;
in
{
  options.services.openpgp-card-ssh-agent = {

    enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Whether to start openpgp-card-ssh-agent when you log in.
        Also sets SSH_AUTH_SOCK to point at openpgp-card-ssh-agent.
      '';
    };

    package = mkPackageOption pkgs "openpgp-card-ssh-agent" { };
  };

  config = mkIf cfg.enable {
    environment.systemPackages = [ cfg.package ];

    systemd.user.sockets.openpgp-card-ssh-agent = {
      wantedBy = [ "sockets.target" ];
      description = "A simple ssh-agent backed by OpenPGP card authentication keys";
      documentation = [
        "https://codeberg.org/openpgp-card/ssh-agent"
        "man:ssh-add(1)"
        "man:ssh-agent(1)"
        "man:ssh(1)"
      ];
      socketConfig = {
        ListenStream = "%t/openpgp-card/ssh-agent.sock";
        SocketMode = "0600";
        DirectoryMode = "0700";
      };
    };

    systemd.user.services.openpgp-card-ssh-agent = {
      description = "A simple ssh-agent backed by OpenPGP card authentication keys";
      documentation = [
        "https://codeberg.org/openpgp-card/ssh-agent"
        "man:ssh-add(1)"
        "man:ssh-agent(1)"
        "man:ssh(1)"
      ];
      after = [ "local-fs.target" ];
      requires = [
        "openpgp-card-ssh-agent.socket"
        # "gnome-keyring-daemon.service"
      ];

      serviceConfig = {
        ExecStart = ''
          ${cfg.package}/bin/openpgp-card-ssh-agent -H fd://
        '';
      };
    };

    environment.extraInit = ''
      if [ -z "$SSH_AUTH_SOCK" ] && [ -n "$XDG_RUNTIME_DIR" ]; then
        export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/openpgp-card/ssh-agent.sock"
      fi
    '';

    assertions = [
      {
        assertion = cfg.enable -> !config.programs.ssh.startAgent;
        message = "You can't use ssh-agent and GnuPG agent with SSH support enabled at the same time!";
      }
      {
        assertion = cfg.enable -> !config.programs.gnupg.agent.enableSSHSupport;
        message = "You can't use GnuPG agent with SSH support enabled and openpgp-card-ssh-agent at the same time!";
      }
    ];
  };
}
