/*
 *  nwauth.c
 *
 *  Check a user/passwd against a 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 [options]\n", progname);
}

static void
help(void)
{
        printf("\n");
        printf("usage: %s [options]\n", progname);
        printf("\n"
	       "-h             Print this help text\n"
	       "-S server      Server name to be used\n"
               "-U username    Username sent to server\n"
	       "-t type        Object type (decimal value)\n"
	       "\n");
}

static void
swallow_error(const char * s, long x, const char *t, va_list arg)
{
	return;
}

int
main(int argc, char *argv[])
{
	struct ncp_conn_spec *spec;
	struct ncp_conn *conn;
	char *server = NULL;
	char *object_name = NULL;
	int object_type = NCP_BINDERY_USER;
	long err;

	char *str;

	int opt;

	progname = argv[0];

	if (!isatty(0))
	{
		set_com_err_hook(swallow_error);
	}

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

	spec = ncp_find_conn_spec(server, object_name, "",
				  1, getuid(), &err);

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

	if (ncp_find_fileserver(spec->server, &err) == NULL)
	{
		com_err(argv[0], err, "when trying to find server");
		exit(1);
	}

	spec->login_type = object_type;
	memset(spec->password, 0, sizeof(spec->password));

	if (isatty(0))
	{
		str = getpass("Enter password: ");
		if (strlen(str) >= sizeof(spec->password))
		{
			printf("Password too long\n");
			exit(1);
		}
		strcpy(spec->password, str);
	}
	else
	{
		fgets(spec->password, sizeof(spec->password), stdin);
	}

	str_upper(spec->password);

	if ((conn = ncp_open(spec, &err)) == NULL)
	{
		com_err(argv[0], err, "when trying to open connection");
		exit(1);
	}
	ncp_close(conn);
	return 0;
}
