/* $Id: config2.c,v 1.1 1999/08/23 16:18:47 naamato Exp $ */
/*
 * Copyright(c) 1998 by Hitachi.Ltd All rights reserved.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <sys/types.h>

#include "config.h"

#define FILE_NAME_SIZE 256

char *if_name;
FILE *fp;
char *config;
CONFIG *configp=NULL;
CONFIG parent;
CONFIG child;
int insock = -1;

CONFIG *init_config(file)
char *file;
{
    CONFIG *dummy;

    if(file) {
	if( !(fp = fopen(file,"r"))) {
	    printf(" can't open %s \n",file);
	    exit(0);
	}
    }
    else {
	fp = stdin;
	insock = fileno(fp);
    }

    if(!config)
	configp = (CONFIG *)malloc(sizeof(CONFIG));
    if(parent.fp) {
	child.fp = configp->fp = fp;
    }
    else {
	parent.fp = configp->fp = fp;
    }

    return configp;
}

int parse_command(fp, cmdbuf)
FILE *fp;
char *cmdbuf;
{
    char *bufp,c;
    int rt;

    bufp = cmdbuf;
    while((c = getc(fp)) != EOF) {
        if(c == 0x0a) {
	    *bufp = '\0';
	    break;
	}
	else if(c == ' ' || c == '\t') {
	    *bufp = '\0';
	    break;
	}
	else if(c == '#') {
	    while(getc(fp)!=0x0a);
	}
        else {
	    *bufp++ = c;
	}
    }

    rt = strcmp(cmdbuf,"quit");
    if(c == EOF)
	return CNF_EOF;
    else if(rt == 0)
	return CNF_EOF;
    else 
	return CNF_NORMAL;
}

int get_config_command(configp,gettbl)
CONFIG *configp;
CONF_PARAGET *gettbl;
{
    char c,buf[256],*bufp,*cmdbuf;
    int rt;
    u_long addr,id;
    int i;
/*
    if(parse_command(configp->fp,gettbl->command)==CNF_EOF)
	return CNF_EOF;
*/
    bzero(gettbl->command,CONF_STR_MAX+1);
    gettbl->paramcount=0;
    bzero(buf,256);
    bufp = buf;

    while(1) {
	c = getc(configp->fp);
        if(c == 0x0a) {
	    *bufp = '\0';
	    if(*gettbl->command) 
		strcpy(gettbl->paramtbl[gettbl->paramcount++],buf);
	    else 
		strcpy(gettbl->command,buf);
	    rt = CNF_NORMAL;
	    break;
	}
	else if(c == ' ' || c == '\t') {
	    *bufp = '\0';
	    if(*gettbl->command)
		strcpy(gettbl->paramtbl[gettbl->paramcount++],buf);
	    else
		strcpy(gettbl->command,buf);
	    bzero(buf,256);
	    bufp = buf;
	}
	else if(c == '#') {
	    while(getc(configp->fp)!=0x0a);
	    if(*gettbl->command) {
		strcpy(gettbl->paramtbl[gettbl->paramcount++],buf);
		rt = CNF_NORMAL;
		break;
	    }
	}
	else if(c == EOF) {
	    if(child.fp) {
		end_config(&child);
		configp->fp = parent.fp;
	    }
	    else {
		rt = CNF_EOF;
		break;
	    }
	}
        else {
	    *bufp++ = c;
	}
    }

    return rt;
}

int end_config(configp)
CONFIG *configp;
{
    if(configp->fp)
	fclose(configp->fp);
    bzero(configp,sizeof(CONFIG));
}

