/*
 *  nwsfind.c
 *
 *  Find a NetWare server and open a route to it.
 *  This tool can safely be setuid root, if normal users should be able to
 *  access any NetWare server.
 *
 *  Copyright (C) 1996 by Volker Lendecke
 *
 */

#include "ncplib.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>

static char *progname;

static void
usage(void)
{
	fprintf(stderr, "usage: %s [server]\n", progname);
}

static void
help(void)
{
        printf("\n");
        printf("usage: %s [server]\n", progname);
        printf("\n"
	       "-t             Server type, default: File server\n"
	       "-h             Print this help text\n"
	       "\n");
}

static void
swallow_error(const char * name, long code, const char *format, va_list arg)
{
	printf("%s ", error_message(code));
	vfprintf(stdout, format, arg);
	putchar('\n');
	return;
}

int
main(int argc, char *argv[])
{
	char *server = NULL;
	int object_type = NCP_BINDERY_FSERVER;
	struct sockaddr_ipx *result;
	long err;

	int opt;

	progname = argv[0];

	set_com_err_hook(swallow_error);

	while ((opt = getopt(argc, argv, "t:")) != EOF)
	{
		switch(opt) {
		case 't':
			object_type = atoi(optarg);
			break;
		case 'h':
		case '?':
			help();
			exit(1);
		default:
			usage();
			exit(1);
		}
	}

	if (optind < argc-1)
	{
		usage();
		exit(1);
	}

	if (optind == argc-1)
	{
		server = argv[optind];
		if (strlen(server) >= NCP_BINDERY_NAME_LEN)
		{
			com_err(argv[0], ENAMETOOLONG, "server name too long");
			exit(1);
		}
	}		

	result = ncp_find_server(&server, object_type, &err);

	if (result == NULL)
	{
		com_err(argv[0], err, "when trying to find server");
		exit(1);
	}

	ipx_print_saddr(result);
	printf(" %s\n", server);
	return 0;
}
