/*
 * BSD initgroups() emulation. Written by Kay Roemer.
 */

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <grp.h>
#include <osbind.h>

#ifndef Psetgroups
#define Psetgroups(a,b)	trap_1_wwl (0x148, (short)a, (long)b)
#define Pgetgroups(a,b)	trap_1_wwl (0x147, (short)a, (long)b)
#endif

#undef  NGROUPS_MAX
#define NGROUPS_MAX	8

extern int errno;

int
initgroups (user, group)
	char *user;
	gid_t group;
{
	static short groups[NGROUPS_MAX];
	short ngroups = 0;
	struct group *gre;
	char **names;
	long r;

	setgrent ();
	while ((gre = getgrent ()) != NULL) {
		for (names = gre->gr_mem; *names; ++names) {
			if (strcmp (*names, user))
				continue;
			if (ngroups >= NGROUPS_MAX)
				continue;
			groups[ngroups++] = gre->gr_gid;
		}
	}
	endgrent ();
	if (ngroups > 0) {
		r = Psetgroups (ngroups, groups);
		if (r < 0) {
			errno = -r;
			return -1;
		}
	}
	return 0;
}
