/*
 * main.c Copyright 1999 Christopher M Sedore. All Rights Reserved.
 * Please see the "COPYING" file for license details.
 * 
 */
#include "main.h"
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>

extern volatile int timerCallback;

int lsock;

int cc=0;
char *cm=NULL;

/*
 * ioloop()
 *
 * ioloop is the core dispatch routine.  It picks up completed aio
 * operations via aio_waitcomplete(), calls the associated callback,
 * checks to see if the alarm signal has been delivered and we need
 * to run timer events.
 */

int pickups,totalpickedup;

void
ioloop()
{
	struct timespec tv;
	int x,r,s;
	struct myaiocb *cb;

	tv.tv_sec=1;
	tv.tv_nsec=0;

	while (1) {
		errno=0;
		r=aio_waitcomplete((struct aiocb **)&cb,&tv);

		if (timerCallback) {
			TimerInterval();
			timerCallback=0;
		}
	
//		if ((r<0) && ((errno==EAGAIN) || (errno==EINTR)))
//			continue;

		if (cb==NULL) {
//			printf("null ret, r=%i, errno=%u\n",r,errno);	
			continue;
		}

		assert(cb!=NULL);
		assert(cb->callback!=NULL);

//		printf("calling %p with %i\r\n",cb->callback,cb);
		if (cb->callback) 
			cb->callback(cb,r);
	}
}

/* 
 * Shutdown()
 *
 * close files, sync, etc.
 */

void
Shutdown()
{
	int x=1;

	printf("shutting down\n");
	FeedDBShutdown();
	StoreShutdown();

	while (++x<1024) {
		close(x);
	}
	exit(1);
}

int
main(int argc, char **argv)
{
  int s;
  int listenport;
  char storepath[1024];
  char newsuid[32];
  char newsgid[32];
  gid_t tempgid;
  struct passwd *passwd;
  struct group *group;
  gid_t gid;


	FeedConfigInit(1);
	FeedConfigInit(2);


  GetConfigInt("ListenPort",&listenport);
  if(listenport==0 || listenport<1)
	{
		printf("No ListenPort defined - defaulting to 119");
		listenport=119;
	}
  lsock=my_listen(listenport);

	strncpy(newsuid, GetConfigString("NewsUID"), 16);
	strncpy(newsgid, GetConfigString("NewsGID"), 16);

/*	tempgid = group->gr_gid; */
/*	setgroups(1, &tempgid); */
	(struct passwd *)passwd=getpwnam(newsuid);
	(struct group *)group=getgrnam(newsgid);
	if (passwd == NULL || group == NULL) {
		printf("Either NewsUID or NewsGID set incorrectly.\n");
		exit(1);
	}
	if(setuid(passwd->pw_uid) != 0) {
		printf("Unable to set UID setuid(%s).\n", newsuid);
		exit(1);
	}
/*	if(setgid(group->gr_gid) != 0) {
		printf("Unable to set GID setgid(%s).\n", newsgid);
		exit(1);
	} */

	DnsInit();
	SeenInit();
	TimerInit();
	DistributionInit();
	NntpInit();
	ArtProcInit();
	PrecommitInit();
	FeedDBInit();
	FeedInit();
	IncomingInit();

	FeedConfigInit(4);
	FeedConfigInit(5);

	ioloop();


}
