#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>

#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include "value-list.h"
#include "tree.h"


static void
id_gen_object_struct(struct idinfo *oi, FILE *fp)
{
	struct idval *v;

	fprintf(fp, "struct objectclasses\n");
	fprintf(fp, "{\n");
	fprintf(fp, "\tchar *name;\n");
	fprintf(fp, "\tchar *class;\n");
	fprintf(fp, "} objectclasses[] = \n");
	fprintf(fp, "{\n");

	for (v = oi->head; v->next; v = v->next) {
		if (v->type != OBJ)
			continue;
		fprintf(fp, "\t{ \"%s\", \"%s\" }, \n",
			v->rawname, v->name);
	}

	fprintf(fp, "\t{ \"%s\", \"%s\" }\n};\n",
		v->rawname, v->name);
}


static int
write_class_struct(char *csv, char *arg, struct idinfo *ids)
{
	char filename[4096];
	FILE *out = NULL;
	int fd = -1;

	if (!strcmp(arg, "-")) {
		out = stdout;
	} else {
		snprintf(filename, sizeof(filename), "%s.XXXXXX", arg);
		fd = mkstemp(filename);
		if (fd < 0) {
			perror("mkstemp");
			return -1;
		}

		out = fdopen(fd, "w");
		if (out == NULL) {
			perror("fdopen");
			close(fd);
			return -1;
		}
	}

	fprintf(out, "/* Begin autogenerated class struct from %s */\n", csv);
	id_gen_object_struct(ids, out);
	fprintf(out, "/* End autogenerated class struct */\n");

	fflush(out);

	if (fd >= 0) {
		fsync(fd);
		fclose(out);
		close(fd);
		rename(filename, arg);
	}

	return 0;
}


int
main(int argc, char **argv)
{
	struct idinfo info;

	memset(&info, 0, sizeof(info));

	if (argc < 3) {
		printf("Translate csv -> C structure\n"
		       "file for future reuse of IDs\n");
		printf("Usage: %s file.csv output.c\n",
		       argv[0]);
		return 1;
	}

	if (id_readfile(&info, argv[1]) < 0) {
		printf("Can't read %s\n", argv[1]);
		return 1;
	}

	write_class_struct(argv[1], argv[2], &info);

	return 0;
}
