/* 
 *    Force.c - Force update from empire.
 *
*/

#include <stdio.h>
#include <sys/types.h>
#include "user.h"
#include "misc.h"
#include "file.h"
#include "tm.h"
#include "keyword.h"
#include "wantupd.h"
#include "nat.h"

#include <fcntl.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/wait.h>
#include <signal.h>

force()
{
	extern  char *argp[];
	extern  char updatebin[];
	int     etu_per_update, etu=0;
	int     pid;
	float   time_to_update;
	char    *what;
	unsigned int seconds;
	natid   n;
	struct  natstr *np;
	char    *p;
	char    *argv[4];
	char    av2[32];

	argv[0] = "update";
	argv[1] = "produce";
	if (p = kw_find("etu_per_update"))
                kw_parse(CF_VALUE, p, &etu_per_update);
	argv[3] = 0;

	if ((seconds = onearg(argp[1], "Time till Update(Seconds) (1 = NOW)1? ")) == 0)
		return RET_SYN;
	if ((etu = onearg(argp[2], "Number of ETU's? ")) == 0)
		return RET_SYN;
	if(etu > 0) etu_per_update = etu;
	sprintf(av2,"%d", etu_per_update);
	argv[2] = av2;
	argv[3] = 0;
	if ((what = getstarg(argp[3],
                "Should Countries be Notified (Y/N)? ")) == 0)
                return RET_SYN;
	switch(what[0]) {
	case 'Y':
	case 'y':
		for (n=0; np = getnatp(n); n++) {	
			if ((np->nat_stat & STAT_NORM) == 0)
                         	continue;
			time_to_update = seconds/60;
			if(seconds != 1) 
				wu((natid)0, n,
                           		fmt("\007 ***WARNING*** Deity Forced UPDATE. \n\n     Will occur in %2.2f Minutes. \n", time_to_update));
			else {
				wu((natid)0, n,
                           		fmt("\007 ***WARNING*** Deity Forced UPDATE. \n\n   NOW!!! \n"));
			}	
		}
	case 'N':
	case 'n':
		if((pid = fork()) < 0) {
       		  logerror("fork error");
                  return 0;
        	}
        	if (pid != 0) {
		   sleep(seconds);	
		   execv(updatebin, argv);
		   exit(1);
		}
	}
}
