/*
 *  nwpasswd.c
 *
 *  Change a bindery object's password
 *
 *  Copyright (C) 1996 by Volker Lendecke
 *
 */

#include "ncplib.h"
#include <unistd.h>
#include <stdlib.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");
}
	

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;
	unsigned char ncp_key[8];
	struct ncp_bindery_object user;
	long err;

	char *str;

	char oldpass[200], newpass1[200], newpass2[200];
	
	int opt;

	progname = argv[0];

	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, "trying to find server");
		exit(1);
	}

	spec->login_type = object_type;

	printf("Changing password for user %s on server %s\n",
	       spec->user, spec->server);

	str = getpass("Enter old password: ");
	if (strlen(str) >= sizeof(oldpass))
	{
		printf("Password too long\n");
		exit(1);
	}
	strcpy(oldpass, str);

	str = getpass("Enter new password: ");
	if (strlen(str) >= sizeof(newpass1))
	{
		printf("Password too long\n");
		exit(1);
	}
	strcpy(newpass1, str);

	str = getpass("Re-Enter new password: ");
	if (strlen(str) >= sizeof(newpass2))
	{
		printf("Password too long\n");
		exit(1);
	}
	strcpy(newpass2, str);

	str_upper(oldpass);
	str_upper(newpass1);
	str_upper(newpass2);

	if (strcmp(newpass1, newpass2) != 0)
	{
		printf("You mistype the new password, try again\n");
		exit(1);
	}

	strcpy(spec->password, oldpass);

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

	if (   ((err = ncp_get_encryption_key(conn, ncp_key)) != 0)
	    || ((err = ncp_get_bindery_object_id(conn, 1, spec->user,
						 &user)) != 0)
	    || ((err = ncp_change_login_passwd(conn, &user, ncp_key,
					   oldpass, newpass1)) != 0))
	{
		com_err(argv[0], err, "trying to change password");
	}

	ncp_close(conn);
	return 0;
}
