#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAS_SYSLOG
#include <syslog.h>
#endif
#include <sysexits.h>
#include <sys/param.h>
#include "getopt.h"
#include "lutil.h"
#include "xutil.h"
#include "ftn.h"
#include "nodelist.h"
#include "config.h"
#include "version.h"
#include "trap.h"

#define	MAX_MX		16

extern	int lookup_node_mxes(char *, char *, char **, int);

void usage()
{
	confusage("-d<domain> -f<boss> -n <node>\n");
	fprintf (stderr, _("-d<domain>\tspecify top level domain for routing\n"));
	fprintf (stderr, _("-f<boss>\tspecify fallback node\n"));
	fprintf (stderr, _("-n\t\tdo not use nodelist when MX ok\n"));
	fprintf (stderr, _("  <node>\tin domain form, e.g. f11.n22.z3\n"));
	fprintf (stderr, "Changes copyright (c) Ruslan Belkin <rus@ua.net>\n");
}

static	char *mxbuf[MAX_MX];	/* returned MX RRs */
static	char  hostname[MAXHOSTNAMELEN];

int main (argc, argv)
	int argc;
	char *argv[];
{
	int nolist_flag = 0;
	int c,rc;
	faddr *adr = NULL, *raddr = NULL;
	node  *nlent ;
	char  *domain   = NULL;	/* default local domain for FIDO */
	char  *fallback = NULL; /* fallback node */

#if defined(HAS_SYSLOG) && defined(CICOLOG)
	logfacility=CICOLOG;
#endif

	setmyname(argv[0]);
	catch(myname);

	while ((c = getopt(argc,argv,"hx:l:d:f:n")) != -1)
	if (confopt(c,optarg)) switch (c) {
		case 'd':
			domain = optarg;
			break;
		case 'f':
			fallback = optarg;
			break;
		case 'n':
			nolist_flag = 1;
			break;
		default:
			usage(argv[0]); 
			exit(EX_USAGE);
	}

	if (readconfig())
	{
		fprintf(stderr, "Error getting configuration, aborting\n");
		exit(EX_DATAERR);
	}

	rc = 1;
	if (argv[optind] == NULL)
	{
		usage();
		rc=EX_USAGE;
	} else if ((adr=parsefaddr(argv[optind])) == NULL) {
		logerr("unrecognizable address \"%s\"",argv[optind]);
		rc=EX_USAGE;
	} else if (gethostname(hostname, sizeof(hostname) - 1) != 0) {
		logerr("cannot get hostname");
		rc=EX_NOHOST;
	} else { 
		if (!lookup_node_mxes(ascinode(adr, 0x2|0x4|0x8), domain, mxbuf, MAX_MX)) {
		    int i;
		
		    for (i = 0; i < MAX_MX && mxbuf[i] != NULL; i++) {
			 if ((raddr = parsefaddr(mxbuf[i])) != NULL) {
			     raddr->domain = NULL;
			     nlent = getnlent(raddr);
		             if (nlent->pflag != NL_DUMMY || nolist_flag) {
			         printf("%s\n", ascinode (raddr, 0x3e));
			         rc = 0;
			         break;
			     }
			 }
			 else if (!strncasecmp(mxbuf[i], "direct", 6) ||
			          !strcasecmp(mxbuf[i], hostname)) {
			        printf("%s\n", ascinode (adr, 0x3e));
			        rc = 0;
			 	break;
			}
		    }
		}
		if (rc == 1) {
		    nlent = getnlent(adr);
		    if ((nlent->pflag != NL_DUMMY) || 
		        (fallback != NULL &&
		          (adr = parsefaddr(fallback)) != NULL)) {
			printf("%s\n", ascinode(adr, 0x3e));
			rc = 0;
		    } else {
			rc = EX_NOHOST;
		    }
		}
	}
	return rc;
}
