static char *RCSid = "$Header: file.c,v 1.5 89/09/28 03:07:26 mr-frog Exp $";

/*
 * file.c
 *
 * create all the misc files except sctfil
 *
 * from PSL Empire, 1985
 */

#include <sys/types.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <sys/file.h>

#include "options.h"
#include "misc.h"
#include "var.h"
#include "sect.h"
#include "nat.h"
#include "ship.h"
#include "plane.h"
#include "nuke.h"
#include "power.h"
#include "trade.h"
#include "file.h"
#include "tel.h"

char	*program = "file";
int	(*leprfunc)();

main()
{
	extern	char infodir[];
	extern	char commfil[];
	extern	char datadir[];
	extern	char gamedir[];
	extern	struct empfile empfile[];
	char	buf[255];
	char   *filename;
	int	x;
	struct	natstr nat;
	int	i;

#ifndef linux
	if ((access(gamedir, F_OK) < 0 && mkdir(gamedir, 0750) < 0) ||
	    (access(datadir, F_OK) < 0 && mkdir(datadir, 0750) < 0)) {
		perror(datadir);
		printf("Can't make game directory\n");
		exit(1);
	}
#endif
	printf("WARNING: this blasts the existing game (if any)\n");
	printf("continue? ");
	gets(buf);
	if (*buf != 'y' && *buf != 'Y')
		exit(1);
	for (i=0; i < EF_MAX; i++) {
		if (ef_open(i, O_RDWR|O_CREAT|O_TRUNC, 0) < 0) {
			perror("ef_open");
			exit(1);
		}
	}
	bzero(&nat, sizeof(nat));
	if (nat.nat_cnam[0] == 0)
		copy("POGO", nat.nat_cnam);
	if (nat.nat_pnam[0] == 0)
		copy("peter", nat.nat_pnam);
	nat.nat_stat = STAT_INUSE|STAT_NORM|STAT_GOD|STAT_ABS;
	nat.nat_btu = 255;
	nat.nat_money = 123456789;
#ifdef BUDGET
	for(x=0;x<SCT_MAXDEF+6;x++)
		nat.nat_priorities[x] = -1;
#endif /* BUDGET */
	ef_nbwrite(EF_NATION, 0, &nat);
	printf("All praise to %s!\n", nat.nat_cnam);
	bzero(&nat, sizeof(nat));
#ifdef BUDGET
	for(x=0;x<SCT_MAXDEF+6;x++)
		nat.nat_priorities[x] = -1;
#endif /* BUDGET */
	for (i = 1; i < MAXNOC; i++)
		ef_nbwrite(EF_NATION, i, &nat);
	ef_close(EF_NATION);
	comminit(make(commfil));
	for (x = MAXNOC - 1; x >= 0; x--) {
		filename = mailbox(x);
		close(creat(filename, 0600));
		chmod(filename, 0600);
#ifdef WIRE
		filename = wirebox(x);
		close(creat(filename, 0600));
#endif
		sprintf(buf,"%s/bigmap%02d",datadir,x);
		unlink(buf);
	}
	chmod(gamedir, 0750);
	chmod(infodir, 0750);
	chmod(datadir, 0770);
	exit(0);
}

quit()
{
	printf("bye-bye...\n");
}

int
make(filename)
	char   *filename;
{
	register int fd;

	fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
	if (fd < 0)
		printf("Creation of %s failed.\n", filename);
	return fd;
}


/*
 * commodity trading file special initialization
 */
float	comm[MAXNOC][I_MAX+1];
float	price[MAXNOC][I_MAX+1];
float	mult[MAXNOC][MAXNOC];

static	struct iovec tradevec[3] = {
	(caddr_t)comm,	sizeof(comm),
	(caddr_t)price,	sizeof(price),
	(caddr_t)mult,	sizeof(mult),
};

comminit(fd)
	int	fd;
{
	int	i;
	int	j;

	for (i=0; i<MAXNOC; i++)
		for (j=0; j<MAXNOC; j++)
			mult[i][j] = 1.0;
	writev(fd, tradevec, 3);
	close(fd);
}

/*ARGSUSED*/
recvclient(cmd, buf)
	int	cmd;
	char	*buf;
{
	return gets(buf);
}
