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

let
  keyFile = lib.escapeShellArg config.sops.age.keyFile;
in

{

  sops.age.generateKey = true;
  sops.age.keyFile = "${config.home.homeDirectory}/.config/sops/age/keys.txt";
  sops.defaultSopsFile = ../../../../secrets/user-pbsds.yaml;

  sops.secrets."hm-age-keys".path = "%r/sops/age/keys-hm.txt";

  /**/
  home.activation.append-hm-sops-keys = lib.hm.dag.entryAfter ["writeBoundary"] ''
    if ! test -f ${keyFile}; then
      $DRY_RUN_CMD mkdir -p "$(dirname ${keyFile})"
      $DRY_RUN_CMD ${lib.getBin pkgs.age}/bin/age-keygen -o ${keyFile} >/dev/null
    fi

    if test -s "''${XDG_RUNTIME_DIR:-}"/sops/age/keys-hm.txt; then
      if test -w ${keyFile}; then
        for pubkey in $(age-keygen -y "$XDG_RUNTIME_DIR"/sops/age/keys-hm.txt); do
          if ! grep -q "$pubkey" <(${lib.getBin pkgs.age}/bin/age-keygen -y ${keyFile}); then
            # TODO: deduplicate
            cat "$XDG_RUNTIME_DIR"/sops/age/keys-hm.txt | $DRY_RUN_CMD tee --append ${keyFile} > /dev/null
            break
          fi
        done
      fi
    fi
  '';
  /**/

  /** /
  home.sessionVariables = {
    #SOPS_AGE_KEY_FILE = config.sops.age.keyFile;
    SOPS_AGE_KEY_FILE = "$XDG_RUNTIME_DIR/sops/age/keys.txt";
  };

  systemd.user.services.combine-keys = {
    Install.WantedBy = config.systemd.user.services.sops-nix.Install.WantedBy;
    Unit.After = [ "sops-nix.service" ];
    Service = {
      Type = "oneshot";
      ExecStart = pkgs.writeShellScript "mk-sops-age-key" ''
        set -euo pipefail
        test -n "$XDG_RUNTIME_DIR"
        test -d "$XDG_RUNTIME_DIR"
        test -f ${config.sops.age.keyFile}
        install -Dm600 -t "$XDG_RUNTIME_DIR/sops/age/keys.txt" <(
           cat ${config.sops.age.keyFile}
           if test -s "$XDG_RUNTIME_DIR"/sops/age/keys-hm.txt; then
             cat "$XDG_RUNTIME_DIR"/hm-keys.txt
           fi
        )
      '';
    };
  };
  /**/

}
