{ pkgs, ... }:
pkgs.writeShellApplication {
  name = "kanidm-dovecot-service-account-provision";
  runtimeInputs = [
    pkgs.openssh
    pkgs.openbao
    pkgs.uutils-coreutils-noprefix

  ];
  text = ''
    tmpfile="$(mktemp)"
    exec {fd}>&1
    trap 'rm "$tmpfile"' EXIT
    api_token="$(ssh -tt security.kaareskovgaard.net -- kanidm-provision-dovecot-service-account | tee >(cat - >&"$fd"))"
    # Using tail to do this ends up including a \r character, so remove it.
    api_token="$(echo "$api_token" | tail -n1 | head -c-2)"
    exec {fd}<&-
    echo "$api_token" | bao kv put -mount=kanidm "ldap/dovecot" apiToken=-
    >&2 echo "API token stored in vault"
  '';
}
