#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <unistd.h>
#include <stdlib.h>
#include <grp.h>
#include <errno.h>

static void test_nwrap_initgroups(void **state)
{
	gid_t gid = 10000;
	int ret, i;
	int ngroups;
	const char *env = getenv("UID_WRAPPER");

	(void)state; /* unused */

	/* initgroups() sets {10000, 1000, 1002, 100010, 100011, 100012} */
	ret = initgroups("alice", gid);
	assert_return_code(ret, errno);

	/*
	 * nss_wrapper() in nwrap_initgroups() makes early return if UID_WRAPPER
	 * is not present. The reason is that we need privilege for setgroups()
	 * called from initgroups() and we get it only with UID_WRAPPER
	 */
	if (env != NULL && env[0] == '1') {
		gid_t groups1[6] = {10000, 1000, 1002, 100010, 100011, 100012};
		gid_t *groups2 = malloc(10 * sizeof(gid_t));

		assert_non_null(groups2);
		ngroups = getgroups(10, groups2); /* room for 10, expect 6 */
		assert_int_equal(ngroups, 6);
		for (i = 0; i < 6; i++) {
			assert_int_equal(groups1[i], groups2[i]);
		}
		free(groups2);
	}
}

int main(void)
{
	int rc;

	const struct CMUnitTest tests[] = {
		cmocka_unit_test(test_nwrap_initgroups)
	};

	rc = cmocka_run_group_tests(tests, NULL, NULL);

	return rc;
}
