/*
	Make dnews not restart until reload
	----------------------
  Fix discrepency
  Auto re-read newsfeeds.conf and dnews.conf
  
---------------------------------------------------------------

pending -xx xxx (must be counting it wrong)
fque, entry is being freed when still in someones linked list.
  
    
-------------------------------------------------------------------
Dnews:
-------------------------------------------------------------------
Tests:
  unix - test file handles
  test multiple feeds
  test multiple links per feed.
  test failures
  Test multiple feeds / performance and reliability & failure modes
  test file handles
-------------------------------------

*/
#ifdef isunix
#include <signal.h>
#endif
#include "dfeed.h"

void sig_init(void);
int main(void)
{
	if (!dfeed_init()) return 1;
	dfeed_run();
	return 1;

}
int dfeed_init(void)
{
	sig_init();
	ini_load();
	imsg_open();
	imsg("\n");
	imsg("%d = %d\n",I_DFEED_DEBUG,ini_true(I_DFEED_DEBUG));
	imsg("-------------- DFEED %s Starting -------------------\n",DFEED_VERSION);
	dmsg("Debug logging on\n");
	feeds_load();
	lib_mkdir(file_bque(1));
	remove(file_work("dfeed.exit"));

	return chan_init();
}
/* Free 'everything' and reload to defragment memory */
int dfeed_reload(void)
{
	return TRUE;
}
int dfeed_run(void)
{
	for (;TRUE;) {
		chan_run();
		dfeed_idle();
		dfeed_status();
	}
	d_check();
	return TRUE;
}


void dfeed_exit(void)
{
	imsg("dfeed exit called\n");
	feeds_exit();
	chan_exit();

	d_check();
	exit(0);
}
void dfeed_idle_20(void)
{
	int done=FALSE;
	char *s;
	time_t t = time(NULL);
	static int lastt;
	static time_t feed_mtime,dnews_mtime;

	if (t-lastt<20) return;
	lastt = t;
	imsg_flush();
	if (feed_mtime==0) {
		feed_mtime = file_mtime(file_config("newsfeeds.conf"));
		dnews_mtime = file_mtime(file_dnews());
	}
	
	t = file_mtime(file_config("newsfeeds.conf"));
	if (t!=feed_mtime) {
		imsg("newsfeeds.conf changed %d!=%d\n",t,feed_mtime);
		do_reload(); done=TRUE;
		/**s = 0; *s = 1;*/
	}
	feed_mtime = t;

	t = file_mtime(file_dnews());
	if (!done) if (t!=dnews_mtime) {
		imsg("dnews.conf changed %d!=%d\n",t,dnews_mtime);
		do_reload();
	}
	dnews_mtime = t;
}
void do_reload(void)
{
	stats_reset();
	imsg("Reload: Reloading as dnews.conf or newsfeeds.conf changed\n");
	feeds_exit();
	imsg("Reload: Loading dnews.conf settings\n");
	ini_load();
	imsg("Reload: Loading newsfeeds.conf settings\n");
	feeds_load();
	imsg("Reload: Reload complete\n");
}
void dfeed_idle(void)
{
	feeds_idle();
	dfeed_idle_20();
}
void dfeed_status(void)
{
	static time_t last;
	FILE *f;

	if (last==time(NULL)) return;
	last = time(NULL);
	f = fopen(file_log("dfeed.status"),"w");
	if (f==NULL) {
		imsg("Cannot write %s %s\n",file_log("dfeed.status"),strerror(errno));
		return;
	}
	stats_status(f);
	feeds_status(f);
	fclose(f);
}
void sig_init(void)
{
#ifdef isunix
        signal(SIGPIPE,SIG_IGN);
        signal(SIGIOT,SIG_IGN);
        signal(SIGFPE,SIG_IGN); 
#endif
}
