#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "config.h"

int main(int argc, char **argv)
{
	const char *v = PACKAGE_STRING;
	char *e;
	int maj = 0, min = 0, patch = 0;

	if (strncmp(v, "dovecot ", 8) && strncmp(v, "Dovecot ", 8))
		return 1;

	/* skip "dovecot " */
	v += 8;

	maj = strtol(v, &e, 10);
	if (v == e)
		return 2;

	v = e + 1;

	min = strtol(v, &e, 10);
	if (v == e)
		return 3;

	/* not end of string yet? */
	if (*e) {
		v = e + 1;

		if (isdigit(*v)) {
			patch = strtol(v, &e, 10);
			if (v == e)
				return 4;
		} else
			patch = 0;
	}

	printf("/* Auto-generated file, do not edit */\n\n");
	printf("#define DOVECOT_VERSION_CODE(maj, min, patch)	"
		"((maj)<<16 | ((min)<<8) | (patch))\n\n");
	
	printf("#define DOVECOT_VCODE				"
		"0x%.2x%.2x%.2x\n", maj, min, 0);
	printf("#define DOVECOT_VCODE_PATCH			"
		"0x%.2x%.2x%.2x\n", maj, min, patch);
	printf("#define DOVECOT_IS_EQ(maj, min)			"
		"DOVECOT_VCODE == DOVECOT_VERSION_CODE(maj, min, 0)\n");
	printf("#define DOVECOT_IS_GT(maj, min)			"
		"DOVECOT_VCODE > DOVECOT_VERSION_CODE(maj, min, 0)\n");
	printf("#define DOVECOT_IS_GE(maj, min)			"
		"DOVECOT_VCODE >= DOVECOT_VERSION_CODE(maj, min, 0)\n");
	printf("#define DOVECOT_IS_LT(maj, min)			"
		"DOVECOT_VCODE < DOVECOT_VERSION_CODE(maj, min, 0)\n");
	printf("#define DOVECOT_IS_LE(maj, min)			"
		"DOVECOT_VCODE <= DOVECOT_VERSION_CODE(maj, min, 0)\n");

	printf("#define DOVECOT_P_IS_EQ(maj, min, patch)	"
		"DOVECOT_VCODE_PATCH == DOVECOT_VERSION_CODE(maj, min, patch)\n");
	printf("#define DOVECOT_P_IS_GT(maj, min, patch)	"
		"DOVECOT_VCODE_PATCH > DOVECOT_VERSION_CODE(maj, min, patch)\n");
	printf("#define DOVECOT_P_IS_GE(maj, min, patch)	"
		"DOVECOT_VCODE_PATCH >= DOVECOT_VERSION_CODE(maj, min, patch)\n");
	printf("#define DOVECOT_P_IS_LT(maj, min, patch)	"
		"DOVECOT_VCODE_PATCH < DOVECOT_VERSION_CODE(maj, min, patch)\n");
	printf("#define DOVECOT_P_IS_LE(maj, min, patch)	"
		"DOVECOT_VCODE_PATCH <= DOVECOT_VERSION_CODE(maj, min, patch)\n");

	/* Use the antispam-storage-2.0.c for dovecot 2.1 - 2.3 as well */
	if (maj == 2 && min < 4)
		min = 0;

	printf("#define ANTISPAM_STORAGE			"
		"\"antispam-storage-%d.%d.c\"\n", maj, min);

	return 0;
}
