#include <fcntl.h>
#include <stdint.h>
#include <locale.h>
#include <sys/ioctl.h>
#include <gio/gio.h>
#include <glib.h>
#include <glib/gstdio.h>

#include <drm/xe_drm.h>

int main (int argc, char **argv)
{
	const char *devname;
	g_autofd int fd = -1;
	g_autofree struct drm_xe_query_config *config = NULL;
	g_autoptr(GOptionContext) option_context = NULL;
	g_autoptr(GError) error = NULL;

	setlocale (LC_ALL, "");
	option_context = g_option_context_new ("");

	if (!g_option_context_parse (option_context, &argc, &argv, &error)) {
		g_printerr ("Failed to parse arguments: %s\n", error->message);
		return EXIT_FAILURE;
	}

	if (argc < 2) {
		g_printerr ("%s\n", g_option_context_get_help (option_context, TRUE, NULL));
		return EXIT_FAILURE;
	}
	devname = argv[1];

	fd = open (devname, O_RDWR);
	if (fd < 0)
		return EXIT_FAILURE;

	struct drm_xe_device_query query = {
		.extensions = 0,
		.query = DRM_XE_DEVICE_QUERY_CONFIG,
		.size = 0,
		.data = 0,
	};

	if (ioctl (fd, DRM_IOCTL_XE_DEVICE_QUERY, &query))
		return EXIT_FAILURE;

	config = g_malloc (query.size);
	if (!config)
	   return EXIT_FAILURE;

	query.data = (uintptr_t)config;
	if (ioctl (fd, DRM_IOCTL_XE_DEVICE_QUERY, &query))
		return EXIT_FAILURE;

	/* if the GPU has dedicated vram then its considered discrete */
	if (config->info[DRM_XE_QUERY_CONFIG_FLAGS] & DRM_XE_QUERY_CONFIG_FLAG_HAS_VRAM)
		return EXIT_SUCCESS;

	return EXIT_FAILURE;
}
