/*
 * Copyright (c) 2004-2006 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: t-getgroup.c,v 1.6 2006/01/05 18:18:01 ca Exp $")
#include "sm/assert.h"
#include "sm/error.h"
#include "sm/test.h"
#include "sm/io.h"
#include "sm/pwd.h"
#include "sm/grp.h"
#include "sm/sysexits.h"

static int Verbose = 0;

static void
sm_getgr(char *group)
{
	struct group *grp;

	grp = getgrnam(group);
	SM_TEST(grp != NULL);
	if (grp == NULL)
	{
		if (Verbose)
			sm_io_fprintf(smioerr, "errno=%d\n", errno);
		return;
	}
	sm_io_fprintf(smioout, "%d\n", grp->gr_gid);
	return;
}

static void
sm_getpw(char *name, bool gid)
{
	struct passwd *pw;

	pw = getpwnam(name);
	SM_TEST(pw != NULL);
	if (pw == NULL)
	{
		if (Verbose)
			sm_io_fprintf(smioerr, "errno=%d\n", errno);
		return;
	}
	if (gid)
		sm_io_fprintf(smioout, "%d\n", pw->pw_gid);
	else
		sm_io_fprintf(smioout, "%d\n", pw->pw_uid);
	return;
}

int
main(int argc, char *argv[])
{
	int c;
	bool pw, gid;
	char *name;

	pw = false;
	gid = false;
	while ((c = getopt(argc, argv, "gpV")) != -1)
	{
		switch (c)
		{
		  case 'g':
			gid = true;
			break;
		  case 'p':
			pw = true;
			break;
		  case 'V':
			++Verbose;
			break;
		  default:
			/* usage(argv[0]); */
			return EX_USAGE;
		}
	}

	sm_test_begin(argc, argv, "test getgrnam/getpwnam");
	argc -= optind;
	argv += optind;
	for (c = 0; c < argc; c++)
	{
		name = argv[c];
		if (name == NULL || *name == '\0')
			continue;
		if (pw)
			sm_getpw(name, gid);
		else
			sm_getgr(name);
	}
	sm_io_flush(smioout);
	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1