{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.khscodes.services.openstack-read-vault-auth-from-userdata;
in
{
  options.khscodes.services.openstack-read-vault-auth-from-userdata = {
    enable = lib.mkEnableOption "Enables reading vault auth information from instance userdata";
  };

  config = lib.mkIf (cfg.enable && config.khscodes.services.vault-agent.enable) (
    let
      vault_addr = config.khscodes.services.vault-agent.vault.address;
      secretIdFilePath = config.khscodes.services.vault-agent.secretIdFilePath;
      roleIdFilePath = config.khscodes.services.vault-agent.roleIdFilePath;
    in
    {
      systemd.services."openstack-read-vault-auth-from-userdata" = {
        enable = true;
        wantedBy = [ "multi-user.target" ];
        after = [ "network-online.target" ];
        serviceConfig = {
          Type = "oneshot";
          RemainAfterExit = true;
          ExecStart = lib.getExe (
            pkgs.writeShellApplication {
              name = "openstack-read-vault-auth-from-userdata";
              runtimeInputs = [
                pkgs.curl
                pkgs.jq
                pkgs.openbao
              ];
              text = ''
                if [[ -f "${lib.escapeShellArg secretIdFilePath}" ]]; then
                  echo "Secret id already found, not copying new id"
                  exit 0
                fi
                userdata="$(curl http://169.254.169.254/openstack/2012-08-10/user_data)"
                role_id="$(echo "$userdata" | jq --raw '.VAULT_ROLE_ID')"
                secret_id_wrapped="$(echo "$userdata" | jq --raw '.VAULT_SECRET_ID_WRAPPED')"
                secret_id="$(BAO_ADDR=${lib.escapeShellArg vault_addr} bao unwrap -field=secret_id "$secret_id_wrapped")"
                mkdir -p "$(dirname ${lib.escapeShellArg secretIdFilePath})"
                mkdir -p "$(dirname ${lib.escapeShellArg roleIdFilePath})"
                echo -n "$role_id" > ${lib.escapeShellArg roleIdFilePath}
                echo -n "$secret_id" > ${lib.escapeShellArg secretIdFilePath}
                chown root:root "$${lib.escapeShellArg secretIdFilePath}"
                chmod 0600 "$${lib.escapeShellArg secretIdFilePath}"
                chown root:root "$${lib.escapeShellArg roleIdFilePath}"
                chmod 0600 "$${lib.escapeShellArg roleIdFilePath}"
                echo "Role id and secret id copied, restart vault-agent"
                systemctl restart vault-agent-openbao.service
              '';
            }
          );
        };
      };
    }
  );
}
