{ pkgs, ... }:
pkgs.writeShellApplication {
  name = "bao-import-secret";
  runtimeInputs = [
    pkgs.openbao
    pkgs.uutils-coreutils-noprefix
  ];
  text = ''
    role_id="''${1:-}"
    wrapped_secret_id="''${2:-}"

    if [[ "$role_id" == "" || "$wrapped_secret_id" == "" ]]; then
      >&2 echo "Usage: bao-import-secret <role-id> <wrapped-secret-id>"
      exit 1
    fi

    if [[ "$(id -u)" != "0" ]]; then
      >&2 echo "Must run as root"
      exit 2
    fi
    secret_id="$(BAO_ADDR=https://secrets.kaareskovgaard.net bao unwrap -field=secret_id "$wrapped_secret_id")"
    mkdir -p /var/lib/vault-agent
    touch /var/lib/vault-agent/role-id
    touch /var/lib/vault-agent/secret-id
    chmod 0600 /var/lib/vault-agent/role-id
    chmod 0600 /var/lib/vault-agent/secret-id
    echo -n "$role_id" > /var/lib/vault-agent/role-id
    echo -n "$secret_id" > /var/lib/vault-agent/secret-id
    systemctl restart vault-agent-openbao.service
  '';
}
