#include "main.h"

char *configFileName;

void
FeedConfigInit(int level)
{
	configFileName="feeds.conf";
	if (!configFileName)
		abort();
	ReadConfig(configFileName,level);
}

void
StripEOL(char *s)
{
  while (*s!=0) {
    if ((*s=='\r') || (*s=='\n')) {
      *s=0;
      return;
    }
    s++;
  }
}

int
ReadConfig(char *fname,int level)
{
  FILE *f;
  char *buf,bb[16384],*k,*v,*s,name[255],path[255],*dist;
  int inout=0,size;

  f=fopen(fname,"r");

  if (!f)
	return -1;

  SiteMarkAll();

  buf=bb;

  while (!feof(f)) {
	fgets(buf,2000,f);

//	printf("%s",buf);
	
	StripEOL(buf);

	if ((buf[0]==';') || (buf[0]=='#') || (strlen(buf)<1))
		continue;

        if (buf[strlen(buf)-1]=='\\') {
		buf+=(strlen(buf)-1);
		if (buf-bb>16384) {
			buf=bb;
			warn("config line too long");
		}
		continue;
	}

	if (buf!=bb) {
		buf=bb;
	}

	k=strtok(buf,"\t ");

	v=k+strlen(k)+1;

	while ((v) && isblank(v)) {
		v++;
	}

	if (!strcasecmp(k,"end")) {

		if (inout==2) {
			if ((size>0) && (path[0]) && 
				(isdigit(*name)) ) {
				CreateArtStore(atoi(name),path,size,dist);
				if (dist!=NULL) 
					free(dist);
			}
		}

		if (inout==4) {
			AddInclude(name,dist);
			free(dist);
		}
		
		inout=0;
		continue;
	}

	if (level==1) {
		if (!strcasecmp(k,"globals")) {
			if (inout) {
				printf("config file error\n");
				abort();
			}
			inout=1;
			continue;
		}

		if (inout==1) {
			add_config(k,v);
//			printf("added %s = %s\n",k,v);
			continue;
		}

	}

	if (level==2) {
		if (!strcasecmp(k,"store")) {
			if (inout) {
				printf("config file error\n");
				abort();
			}
			inout=2;
			strcpy(name,v);
			path[0]=0;
			dist=NULL;
			size=0;
			continue;
		}

		if (inout==2) {
			if (!strcasecmp(k,"path")) {
				strcpy(path,v);
			}
		
			if (!strcasecmp(k,"size")) {
				size=atoi(v);
			}

			if (!strcasecmp(k,"dist")) {
				dist=strdup(v);
			}
		}
		continue;
	}

	if (level==4) {
		if (!strcasecmp(k,"distinclude")) {
			strcpy(name,v);
			inout=4;
			dist=NULL;
		}

		if (inout==4) {
			if (!strcasecmp(k,"dist")) {
				dist=strdup(v);
			}
		}
	}

	if (level==5) {
		if (!strcasecmp(k,"outgoing")) {
			if (inout) {
				printf("config file error\n");
				abort();
			}
			inout=5;
			s=strtok(v,"\t ");
			v=strtok(NULL,"\t ");
			printf("creating %s as %i\n",v,atoi(s));
			SiteCreate(atoi(s),v);
			strcpy(name,v);
			continue;
		}	

		if (!strcasecmp(k,"incoming")) {
			if (inout) {
				printf("config file error\n");
				abort();
			}
			inout=6;
			printf("creating %s\n",v);
			IncomingAdd(v);
			strcpy(name,v);
			continue;
		}	
	
		if (inout==5) {
			SiteSet(name,k,v);
//			printf("setting %s to %s for %s\n",k,v,name);
		}

		if (inout==6) {
			IncomingSet(name,k,v);
//			printf("setting %s to %s for %s\n",k,v,name);
		}

	}


  }

  SiteDeleteMarked();

  fclose(f);

  return 0;
}
