#include <stdio.h>
#include <stdlib.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xauth.h>
#include <string.h>
#include <errno.h>

#include "remove_xhosts.h"

EVENT *ev_head, *ev_tail;
char *programname;
Display *display;
XHostAddress *hostlist;
int hosts, access_control;
int (*olderrorhandler)(Display *, XErrorEvent *);
char *displayname;

void program_init(int argc, char *argv[])
{
	/* Find the program name for error reporting */
	if (!argv[0]) argv[0]="remove_xhosts"; /* Shouldn't happen */
	programname=strrchr(argv[0], '/');
	if (programname) programname++; else programname=argv[0];

	/* XDisplayName is fails to return NULL if DISPLAY isn't set */
	displayname=getenv("DISPLAY");
	if (!displayname)
	{
		fprintf(stderr, "Error: Please set and export $DISPLAY.\n");
		exit(1);
	}
	olderrorhandler=XSetErrorHandler(myerrorhandler);
}

int main(int argc, char *argv[])
{
	int i;

	program_init(argc, argv);

	display_init();
	hosts_init();
	if (!access_control) hosts_enableaccesscontrol();
	if (hosts) hosts_removeall(); /* Can fail without triggering error */
	hosts_done();
	display_done(); /* Avoid broken Xlib caching by closing connection */
	
	if (hosts || !access_control)
	{
		display_init(); /* Reopen connection */
		hosts_init();
		if (access_control)
			fprintf(stderr, "Error: Couldn't enable access"
				"control; unauthorized clients can connect\n");

		for (i=0; i<hosts; i++) /* Remove hosts individually */
			hosts_remove(&hostlist[i]);
		hosts_done();
		display_done();
	}

	if (hosts)
	{
		display_init();
		hosts_init();
		if (hosts) /* Report errors for anything that's left */
		{
			for (i=0; i<hosts; i++)
				fprintf(stderr, "Error: Can't remove host "
					"%s:%s from access control list for "
					"display %s.\n", 
					XFamilyName(hostlist[i].family),
					XHostName(&hostlist[i]),
					displayname);
		}
		hosts_done();
		display_done();
	}

	return !access_control || hosts;
}

