/*
 * SPDX-FileCopyrightText: (C) 2018 Red Hat, Inc. (www.redhat.com)
 * SPDX-License-Identifier: LGPL-2.0-or-later
 */

#include "evolution-data-server-config.h"

#include <stdio.h>
#include <string.h>
#include <glib.h>

static void
output (const gchar *varname,
	GSList *strings)
{
	GSList *link;
	gint index;

	g_return_if_fail (varname != NULL);
	g_return_if_fail (strings != NULL);

	printf ("static const gchar %s_table[] = {\n", varname);
	for (link = strings; link; link = g_slist_next (link)) {
		const gchar *str = link->data;

		printf ("  \"%s\\0\"\n", str);
	}
	printf ("};\n");

	index = 0;

	printf ("static const guint %s_index[] = {\n", varname);
	for (link = strings; link; link = g_slist_next (link)) {
		const gchar *str = link->data;

		printf ("  %d,\n", index);

		index += strlen (str) + 1;
	}
	printf ("};\n\n");
}

typedef enum {
	STATE_VAR,
	STATE_STRING
} State;

static void
process_content (const gchar *content)
{
	State state = STATE_VAR;
	const gchar *varname = NULL;
	GSList *strings = NULL;
	gchar **lines;
	gint ii;

	printf ("/* This file is generated by gen-western-table. DO NOT EDIT */\n");

	lines = g_strsplit (content, "\n", -1);

	for (ii = 0; lines && lines[ii]; ii++) {
		gchar *line = lines[ii];

		if (!*line) {
			strings = g_slist_reverse (strings);
			output (varname, strings);
			state = STATE_VAR;
			varname = NULL;
			g_slist_free (strings);
			strings = NULL;
		} else if (state == STATE_VAR) {
			varname = line;
			state = STATE_STRING;
		} else if (state == STATE_STRING) {
			strings = g_slist_prepend (strings, line);
		} else {
			g_warn_if_reached ();
		}
	}

	g_strfreev (lines);

	g_warn_if_fail (state == STATE_VAR);
	g_warn_if_fail (strings == NULL);
}

gint
main (gint argc,
      gchar *argv[])
{
	GError *error = NULL;
	gchar *contents = NULL;

	if (argc != 2) {
		g_warning ("Expects one argument, input file with western tables description");
		return 1;
	}

	if (!g_file_get_contents (argv[1], &contents, NULL, &error) || !contents || error) {
		g_warning ("Failed to read '%s': %s\n", argv[1], error ? error->message : "Unknown error");
		g_clear_error (&error);
		return 2;
	}

	process_content (contents);

	g_free (contents);

	return 0;
}
