#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "ctlError.h"
#include "libctlParameter.h"

void usage(char *prog_name) {
	printf("Usage : %s -l -f file_name\n", basename(prog_name));
	printf("Usage : %s -f file_name [-s paragram_name] -p parameter_name\n", basename(prog_name));
	exit(1);
}

void h_error() {
	printf("%s", strErrMSG(0));
	exit(1);
}

int main(int argc, char **argv) {
	struct configList *fileConf;
	char **plist;				// for paragram list
	char *pstr;				// for paragram name
	char val[PARAMETER_VALUE_MAX + 1];	// for parameter value
	char *file_name = NULL;
	char *parag_name = NULL;
	char *param_name = NULL;
	int l_opt = 0, i = 0;
	int ret, opt, fd;

	while((opt = getopt(argc, argv, "f:s:p:l")) != -1) {
		switch(opt) {
			case 'f':
				file_name = optarg;
				break;
			case 's':
				parag_name = optarg;
				break;
			case 'p':
				param_name = optarg;
				break;
			case 'l':
				l_opt = 1;
				break;
			default:
				usage(argv[0]);
		}
	}
	if(file_name == NULL) {
		usage(argv[0]);
	}
	if((param_name == NULL) && (l_opt == 0)) {
		usage(argv[0]);
	}
	if((param_name != NULL) && (l_opt == 1)) {
		usage(argv[0]);
	}

	/* Read configuration file */
	if((fd = open(file_name, O_RDONLY)) == -1) {
		printf("open error(File:%s)\n", file_name);
		return 1;
	}
	if((fileConf = initConfigList()) == NULL) {
		h_error();
	}
	if(readConfigFile(fd, fileConf) != 0) {
		h_error();
	}
	close(fd);

	/* Show parameter value/paragram list */
	if(l_opt == 1) {
		plist = getParagramList(fileConf);
		if(plist == NULL) {
			h_error();
		}
		while((pstr = plist[i++]) != NULL) {
			printf("%s\n", pstr);
		}
		free(plist);
	} else {
		ret = getParameterValue(val, parag_name, param_name, NORMAL_PARAMETER, fileConf);
		if(ret == -1) {
			h_error();
		} else if(ret == 0) {
			printf("%s\n", val);
		}
	}

	/* Free memory of configuration list */
	freeConfigList(fileConf);
	return 0;
}


