/*
 * Copyright 2024 Richard Hughes <richard@hughsie.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "fu-fuzzer.h"
#include "fu-bytes.h"

#include "@INCLUDE@"

int
main(int argc, char **argv)
{
	g_autoptr(GBytes) blob_dst = NULL;
	g_autoptr(GBytes) blob_src = NULL;
	g_autoptr(GError) error = NULL;
	g_autoptr(GObject) object = NULL;

	/* do not use g_option_context_parse() here for speed */
	if (argc != 3 || !g_str_has_suffix(argv[1], ".builder.xml") ||
	    !g_str_has_suffix(argv[2], ".bin")) {
		g_printerr("Invalid arguments, expected %s XML BIN\n", argv[0]);
		return EXIT_FAILURE;
	}

	/* load if exists */
	if (g_file_test(argv[1], G_FILE_TEST_EXISTS)) {
		blob_src = fu_bytes_get_contents(argv[1], &error);
		if (blob_src == NULL) {
			g_printerr("Failed to load %s: %s\n", argv[1], error->message);
			return EXIT_FAILURE;
		}
	}

	/* build blob */
	g_type_ensure(@GTYPE@);
	object = g_object_new(@GTYPE@, NULL);
	blob_dst = fu_fuzzer_build_example(FU_FUZZER(object), blob_src, &error);
	if (blob_dst == NULL) {
		g_printerr("Failed to build %s: %s\n", argv[1], error->message);
		return EXIT_FAILURE;
	}

	/* save blob */
	if (!fu_bytes_set_contents(argv[2], blob_dst, &error)) {
		g_printerr("Failed to save %s: %s\n", argv[3], error->message);
		return EXIT_FAILURE;
	}

	/* success */
	return EXIT_SUCCESS;
}
