/*
 * testinit.c --
 *	Standard stand alone C code test driver.
 *
 * Note:
 *	Just create TestMain() in a separate file and link.
 */

#ifndef lint
static	char
	testinit_c[] = "$Header: /private/postgres/src/test/RCS/testinit.c,v 1.6 1990/02/12 19:52:03 cimarron Version_2 $";
#endif	/* !defined(lint) */

#include <signal.h>
#include <stdio.h>
#include <setjmp.h>
#include <strings.h>
#include "log.h"
#include "bufmgr.h"
#include "xcxt.h"

extern void	TestMain();

static	char	Buf[MAXPGPATH];
jmp_buf	Warn_restart;

handle_warn()
{
	extern	jmp_buf	Warn_restart;

	longjmp(Warn_restart);
}

/* exit gracefully */
die()
{
	exitpg(0);
}

main(argc, argv)
int	argc;
char	*argv[];
{
	char		*datname;
	extern	jmp_buf	Warn_restart;
	int		geteuid(), setuid();			/* uid_t */
	int		chdir(), setjmp(), fprintf();
	char		*getenv();
	extern		exitpg();
	extern		resetmmgr();

	if (argc > 2) {
		fprintf(stderr, "Usage: %s [datname]\n", rindex(argv[0], '/') ?
			rindex(argv[0], '/') + 1 : argv[0]);
		exitpg(1);
	}
	if (argc == 2)
		datname = argv[1];
	else if ((datname = getenv("USER")) == (char *)NULL) {
		fprintf(stderr, "failed getenv(\"USER\")");
		exitpg(1);
	}

	signal(SIGHUP, die);
	signal(SIGINT, die);
	signal(SIGTERM, die);

	InitPostgres(Buf, datname);

	if (chdir(Buf) < 0) {
	        elog(FATAL, "chdir(\"%s\"): %m", Buf);
	}

	setuid(geteuid());
	signal(SIGHUP, handle_warn);

	if (setjmp(Warn_restart) != NULL) {
		AbortCurrentTransaction();
	}

	TestMain();
}
