/* $Id: evhandler.c,v 1.5 2002/06/28 11:27:53 indoh Exp $ */
/* command/evhandler.c */

/************************************************************
 *
 * COPYRIGHT (C) HITACHI,LTD. 2002 ALL RIGHTS RESERVED.
 * WRITTEN BY HITACHI SYSTEMS DEVELOPMENT LABORATORY,
 *            HITACHI CENTRAL RESEARCH LABORATORY.
 *
 * Created by K.Hatasaki <keisukeh@crl.hitachi.co.jp>
 *
 ************************************************************/

#include "command.h"
#include <string.h>

inline void evhandler_list()
{
	int retval;
	int fd;
	int i;
	lkst_evhandler_id evhandler_id;
	struct lkst_evhandler_listparam lp;
	struct lkst_evhandler_listent listent[LKST_EVHANDLER_TBL_MAX];

	fd = open_dev();

	lp.listent_size = LKST_EVHANDLER_LISTENT_SIZE(LKST_EVHANDLER_TBL_MAX);
	lp.listent = listent;

	retval = ioctl(fd, LKST_IOC_EVHANDLER_LIST, &lp); /* evhandler list */

	if (retval) {
		fprintf(stderr, "ioctl() error: %s\n", strerror(errno));
		exit(1);
	}

	printf("evhandler_id\tname\n");
	for (i = 0; i < LKST_EVHANDLER_TBL_MAX; i++) {
		if (lp.listent[i].id != LKST_EVHANDLER_ID_VOID) {
	  		printf(" %3d\t\t%s\n",
			       lp.listent[i].id,
			       lp.listent[i].name);
		}
	}

	close(fd);
}

inline void evhandler_ctrl(lkst_evhandler_id id, char *file_name, int name_set)
{
	int retval;
	int fd;
	FILE *fp_i;
	char temp[4096], *buf = NULL;
	size_t bufsize = 0;
	struct lkst_evhandler_ctrl_param evhandler_ctrl_param;
	struct stat file_stat;

	fd = open_dev();

	if (name_set) {
		if (0 == strncmp("-", file_name, 2)) {
			fp_i = stdin;
			buf = (char*) malloc(4096);
			while(retval = fread(temp, sizeof(char), 4096, fp_i)) {
				buf = (char*) realloc(buf, bufsize + retval);
				memcpy(buf + bufsize, temp, retval);
				bufsize += retval;
			}
		} else {
			if ((fp_i = fopen(file_name, "r")) == NULL) {
				perror("input");
				exit(1);
			}
			
			if (stat(file_name, &file_stat)) {
				perror("fstat");
				exit(1);
			}

			bufsize = (size_t) file_stat.st_size;

			buf = (char*) malloc(bufsize);

			fread(buf, sizeof(char), bufsize, fp_i);
		}
	}

	evhandler_ctrl_param.id = id;
  
	evhandler_ctrl_param.buf = buf;	/* pointer to a communication area */
	evhandler_ctrl_param.bufsize = bufsize;	/* size of the area */

	retval = ioctl(fd, LKST_IOC_EVHANDLER_CTRL, &evhandler_ctrl_param);
						/* evhandler_ctrl */
	if (retval) {
		fprintf(stderr, "ioctl() error: %s\n", strerror(errno));
		exit(1);
	}
 
	printf("ioctl retval=%d\n", retval);

	printf("control-function return value=%d\n", evhandler_ctrl_param.ret);

	close(fd);
}
