#include <gtk/gtk.h>

static GtkTextBuffer *
open_file (GFile *file)
{
	gchar *content;
	GtkTextBuffer *buffer;
	GError *error = NULL;

	g_file_load_contents (file, NULL, &content, NULL, NULL, &error);
	g_assert_no_error (error);

	buffer = gtk_text_buffer_new (NULL);
	gtk_text_buffer_set_text (buffer, content, -1);

	g_free (content);
	return buffer;
}

static void
insert_warning (GtkTextBuffer *buffer)
{
	GtkTextIter iter;
	GtkTextIter define_start;

	gtk_text_buffer_get_start_iter (buffer, &iter);
	if (!gtk_text_iter_forward_search (&iter,
					   "#define",
					   GTK_TEXT_SEARCH_TEXT_ONLY,
					   &define_start,
					   NULL,
					   NULL))
	{
		g_error ("#define not found.");
	}

	iter = define_start;
	gtk_text_iter_forward_line (&iter);

	gtk_text_buffer_insert (buffer,
				&iter,
				"\n"
				"#if !defined (GTK_SOURCE_H_INSIDE) && !defined (GTK_SOURCE_COMPILATION)\n"
				"#warning \"Only <gtksourceview/gtksource.h> can be included directly.\"\n"
				"#endif\n",
				-1);
}

static void
save_content (const gchar   *path,
	      GtkTextBuffer *buffer)
{
	GtkTextIter start;
	GtkTextIter end;
	gchar *content;
	GError *error = NULL;

	gtk_text_buffer_get_bounds (buffer, &start, &end);
	content = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
	g_assert (content != NULL);

	g_file_set_contents (path, content, -1, &error);
	g_assert_no_error (error);

	g_free (content);
}

gint
main (gint argc, gchar *argv[])
{
	const gchar *path;
	GFile *file;
	GtkTextBuffer *buffer;

	gtk_init (&argc, &argv);

	if (argc != 2)
	{
		g_error ("Usage: %s <path/to/header.h>", argv[0]);
	}

	path = argv[1];
	file = g_file_new_for_path (path);
	buffer = open_file (file);
	insert_warning (buffer);
	save_content (path, buffer);

	g_print ("%s: OK\n", path);

	g_object_unref (file);
	g_object_unref (buffer);
	return 0;
}
