{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.khscodes.services.read-vault-auth-from-userdata;
in
{
  options.khscodes.services.read-vault-auth-from-userdata = {
    enable = lib.mkEnableOption "Enables reading vault auth information from instance userdata";
    doubleDecodeJsonData = lib.mkEnableOption "Enables double decoding the JSON data. Used by the hcloud provider as hetzner encodes the entire user data as a string";
    url = lib.mkOption {
      type = lib.types.str;
      description = "URL to retrieve instance metadata from";
    };
  };

  config = lib.mkIf (cfg.enable && config.khscodes.services.vault-agent.enable) (
    let
      vault_addr = lib.escapeShellArg config.khscodes.services.vault-agent.vault.address;
      secretIdFilePath = lib.escapeShellArg config.khscodes.services.vault-agent.vault.secretIdFilePath;
      roleIdFilePath = lib.escapeShellArg config.khscodes.services.vault-agent.vault.roleIdFilePath;
      cacheFilePath = lib.escapeShellArg "${config.khscodes.services.vault-agent.vault.secretIdFilePath}.wrapped";
    in
    {
      systemd.services."read-vault-auth-from-userdata" = {
        enable = true;
        wantedBy = [ "multi-user.target" ];
        wants = [ "network-online.target" ];
        after = [ "network-online.target" ];
        environment = {
          DOUBLE_DECODE = if cfg.doubleDecodeJsonData then "yes" else "no";
        };
        serviceConfig = {
          Type = "oneshot";
          RemainAfterExit = true;
          ExecStart = lib.getExe (
            pkgs.writeShellApplication {
              name = "read-vault-auth-from-userdata";
              runtimeInputs = [
                pkgs.curl
                pkgs.jq
                pkgs.openbao
                pkgs.getent
                pkgs.systemd
              ];
              text = ''
                DOUBLE_DECODE="''${DOUBLE_DECODE:-no}"
                userdata="$(curl ${lib.escapeShellArg cfg.url})"
                if [[ "$DOUBLE_DECODE" == "yes" ]]; then
                  userdata="$(echo "$userdata" | jq --raw-output '.')"
                fi
                role_id="$(echo "$userdata" | jq --raw-output '.VAULT_ROLE_ID')"
                secret_id_wrapped="$(echo "$userdata" | jq --raw-output '.VAULT_SECRET_ID_WRAPPED')"
                if [[ -f ${cacheFilePath} ]]; then
                  cache_key="$(cat ${cacheFilePath})"
                  if [[ "$secret_id_wrapped" == "$cache_key" ]]; then
                    echo "Secret id matched last used value, exiting program"
                    exit 0
                  fi
                fi
                secret_id="$(BAO_ADDR=${vault_addr} bao unwrap -field=secret_id "$secret_id_wrapped")"
                mkdir -p "$(dirname ${secretIdFilePath})"
                mkdir -p "$(dirname ${roleIdFilePath})"
                echo -n "$role_id" > ${roleIdFilePath}
                echo -n "$secret_id" > ${secretIdFilePath}
                chown root:root ${secretIdFilePath}
                chmod 0600 ${secretIdFilePath}
                chown root:root ${roleIdFilePath}
                chmod 0600 ${roleIdFilePath}
                echo -n "$secret_id_wrapped" > ${cacheFilePath}
                chmod 0600 ${cacheFilePath}
                chown root:root ${cacheFilePath}
                echo "Role id and secret id copied, restarting vault-agent"
                systemctl restart vault-agent-openbao.service
              '';
            }
          );
        };
      };
    }
  );
}
