#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <stdint.h>
#include <cmocka.h>

#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

static int setup(void **state)
{
	(void) state; /* unused */

	setenv("PRIV_WRAPPER", "1", 1);

	return 0;
}

static void test_pledge(void **state)
{
	int rc;

	(void) state; /* unused */

	setenv("PRIV_WRAPPER_PLEDGE_DISABLE", "1", 1);

	rc = pledge("stdio", NULL);
	assert_return_code(rc, errno);

	rc = pledge("cpath", NULL);
	assert_return_code(rc, errno);

	unsetenv("PRIV_WRAPPER_PLEDGE_DISABLE");
}

static void test_pledge_fail(void **state)
{
	int rc;

	(void) state; /* unused */

	rc = pledge("stdio", NULL);
	assert_return_code(rc, errno);

	rc = pledge("cpath", NULL); /* Attempting to increase permissions */
	assert_int_equal(rc, -1);
	assert_int_equal(errno, EPERM);
}

int main(void)
{
	const struct CMUnitTest tests[] = {
		cmocka_unit_test(test_pledge),
		cmocka_unit_test(test_pledge_fail),
	};

	return cmocka_run_group_tests(tests, setup, NULL);
}
