/*
 *  nwgrant.c
 *
 *  Add trustee rights to file or directory
 *
 *  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] file/directory\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"
               "-P password    Use this password\n"
               "-n             Do not use any password\n"
               "-C             Don't convert password to uppercase\n"
	       "\n"
	       "-o object_name Name of object added as trustee\n"
	       "-t type        Object type (decimal value)\n"
	       "-r rights      Rights mask (see manual page)\n"
	       "\n"
	       "directory\n"
	       "\n");
}

int
main(int argc, char *argv[])
{
	struct ncp_conn *conn;
	char *object_name = NULL;
	int object_type = -1;
	struct ncp_bindery_object o;
	int rights = -1;
	char *path = NULL;
	long err;
	int result = 1;
	int opt;

	progname = argv[0];

	if ((conn = ncp_initialize(&argc, argv, 1, &err)) == NULL)
	{
		com_err(argv[0], err, "when initializing");
		goto finished;
	}

	while ((opt = getopt(argc, argv, "h?o:t:r:")) != EOF)
	{
		switch(opt) {
		case 'o':
			object_name = optarg;
			str_upper(object_name);
			break;
		case 't':
			object_type = atoi(optarg);
			break;
		case 'r':
			rights = strtol(optarg, NULL, 16);
			break;
		case 'h':
		case '?':
			help();
			goto finished;
		default:
			usage();
			goto finished;
		}
	}

	if (object_type < 0)
	{
		fprintf(stderr, "%s: You must specify an object type\n",
			argv[0]);
		goto finished;
	}

	if (object_name == NULL)
	{
		fprintf(stderr, "%s: You must specify an object name\n",
			argv[0]);
		goto finished;
	}

	if (rights < 0)
	{
		fprintf(stderr, "%s: You must specify a rights mask\n",
			progname);
		goto finished;
	}

	if (optind != argc-1)
	{
		fprintf(stderr, "%s: You must specify a directory\n",
			progname);
		goto finished;
	}
	path = argv[optind];

	if (ncp_get_bindery_object_id(conn, object_type, object_name, &o) != 0)
	{
		fprintf(stderr, "%s: Could not find object %s\n",
			progname, object_name);
		goto finished;
	}

	if (ncp_add_trustee(conn, 0, path, o.object_id, rights) != 0)
	{
		fprintf(stderr, "%s: Could not add trustee rights\n",progname);
		goto finished;
	}

	result = 0;

 finished:
	ncp_close(conn);
	return result;
}
