#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <syslog.h>
#include <errno.h>
#include "SysConfig.h"
#ifndef TARGET_OSX
#include "config.h"
#endif

#define SYSCONFIG_BUF_SIZE	(128)

SYSCONFIG_RESULT
SysConfigInit(	PSYSCONFIG	pSysConfig,
				char*		confFileName)
{
	char	fullConfFileName[SYSCONFIG_BUF_SIZE];
	char	confLine[SYSCONFIG_BUF_SIZE + 1];
	FILE*				fp;
	int					retValue;
	SYSCONFIG_RESULT	result;

	syslog(	LOG_INFO,
			"SysConfigInit(0x%X, [%s]) "
			"entered\n",
			pSysConfig,
			confFileName);

	if (pSysConfig == NULL)
	{
		syslog(LOG_INFO, "SysConfigInit: pSysConfig == NULL\n");
		result = SYSCONFIG_FAIL;
		goto InvalidParameter;
	}
	if (confFileName == NULL)
	{
		syslog(LOG_INFO, "SysConfigInit: confFileName == NULL\n");
		result = SYSCONFIG_FAIL;
		goto InvalidParameter;
	}

	pSysConfig->numEntry = 0;

	sprintf(fullConfFileName, "/etc/%s", confFileName);
	fp = fopen(fullConfFileName, "r");
	if (fp == NULL)
	{
		syslog(	LOG_INFO,
				"SysConfigInit: open [%s] "
				"failed(%d)[%s]\n",
				fullConfFileName,
				errno,
				strerror(errno));
		result = SYSCONFIG_FAIL;
		goto OpenConfFileFailed;
	}

	while (fgets(confLine, SYSCONFIG_BUF_SIZE, fp) != NULL)
	{
		retValue = sscanf(
			confLine,
			"%s = %s",
			pSysConfig->entry[pSysConfig->numEntry].name,
			pSysConfig->entry[pSysConfig->numEntry].value);
		if (retValue == 2)
		{
			syslog(	LOG_INFO,
					"SysConfigInit: [%d] [%s][%s] decoded\n",
					pSysConfig->numEntry,
					pSysConfig->entry[pSysConfig->numEntry].name,
					pSysConfig->entry[pSysConfig->numEntry].value);

			pSysConfig->numEntry++;
		}
	}

	fclose(fp);
	return SYSCONFIG_SUCCESS;

/****** Error Part ******/
	fclose(fp);

OpenConfFileFailed:
InvalidParameter:
	return result;
}

void
SysConfigCleanUp(PSYSCONFIG	pSysConfig)
{
}

SYSCONFIG_RESULT
SysConfigQuery(	PSYSCONFIG	pSysConfig,
				char*		valueName,
				char*		valueStr)
{
	int	i;

	for (i = 0; i < pSysConfig->numEntry; i++)
	{
		if (strcmp(	pSysConfig->entry[i].name,
					valueName) == 0)
		{
			strcpy(valueStr, pSysConfig->entry[i].value);
			return SYSCONFIG_SUCCESS;
		}
	}
	return SYSCONFIG_FAIL;
}
