
/* gcc -Wall -Werror ctversion.c -lct -o ctlib-version */

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <ctpublic.h>

int
main(int argc, char *argv[])
{
	const bool DEBUG = 0;
	CS_RETCODE rc = CS_FAIL;
	CS_CONTEXT *context = NULL;
	CS_INT outlen = 0;
	CS_CHAR t = '\0';
	CS_CHAR *buf = NULL;

	/* Allocate the context */
	rc = cs_ctx_alloc(CS_VERSION_100, &context);
	if (rc != CS_SUCCEED)
	{
		fprintf(stderr, "%s:%d: cs_ctx_alloc() failed!\n", argv[0], __LINE__);
		exit(EXIT_FAILURE);
	}

	/* Initialize the Client Library */
	rc = ct_init(context, CS_VERSION_100);
	if (rc != CS_SUCCEED)
	{
		fprintf(stderr, "%s:%d: ct_init() failed!\n", argv[0], __LINE__);
		exit(EXIT_FAILURE);
	}

	/* Get length of version string */
	rc = ct_config(context, CS_GET, CS_VER_STRING, &t, 1 , &outlen );
	outlen += 1; /* NUL terminator */
	if (DEBUG) {
		printf("%s: need buffer of size %d for version string.\n", argv[0], outlen);
	}

	/* Allocate buffer for version string */
	buf = calloc(outlen, sizeof(CS_CHAR));
	if (buf == NULL) {
		fprintf(stderr, "%s:%d: calloc(%d) failed! %s.\n", argv[0], __LINE__, outlen, strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* Retrieve and print the version string */
	rc = ct_config(context, CS_GET, CS_VER_STRING, buf, outlen, &outlen);
	if (rc != CS_SUCCEED)
	{
		fprintf(stderr, "%s:%d: ct_config() failed!\n", argv[0], __LINE__);
		exit(EXIT_FAILURE);
	}
	printf("%s: \'%s\'.\n", argv[0], buf);

	/* clean up the client library data space for the context */
	rc = ct_exit(context, CS_UNUSED);
	if (rc != CS_SUCCEED)
	{
		fprintf(stderr, "%s:%d: ct_exit() failed!\n", argv[0], __LINE__);
		exit(EXIT_FAILURE);
	}

	/* Deallocate the context */
	rc = cs_ctx_drop(context);
	if (rc != CS_SUCCEED)
	{
		fprintf(stderr, "%s:%d: cs_ctx_drop() failed!\n", argv[0], __LINE__);
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}
