/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2025 Brett A C Sheffield <bacs@librecast.net> */

#include "test.h"
#include <agent.h>

#define REDIRECT_BUF f = freopen("/dev/null", "a", stdout); assert(f); setbuf(stdout, buf);
#define REDIRECT_OUT setbuf(stdout, NULL);

int main(void)
{
	char name[] = PACKAGE_NAME " whoami";
	char fakehome[] = "0000-0016-XXXXXX";
	char *argv[] = { PACKAGE_NAME, "whoami", NULL };
	int argc = sizeof argv / sizeof argv[0] - 1;
	char buf[BUFSIZ];
	FILE *f;
	state_t state = {0};
	int rc;

	test_name(name);

	/* create fake home directory */
	if (!test_assert(mkdtemp(fakehome) != NULL, "mkdtemp()")) {
		perror("mkdtemp");
		return test_status;
	}
	rc = setenv("HOME", fakehome, 1);
	if (!test_assert(rc == 0, "set HOME")) return test_status;

	/* run once,  verify keys generated, whoami output */
	memset(&state, 0, sizeof state);
	memset(buf, 0, sizeof buf); /* clear output buffer */
	REDIRECT_BUF
	rc = agent(&state, argc, argv);
	REDIRECT_OUT
	test_assert(rc == EXIT_SUCCESS, "agent_run() returned %i", rc);

	/* verify keys generated */
	char *phex = strdup(state.defaults.keyring.phex);
	test_assert(strlen(state.defaults.keyring.phex) > 0, "combo key generated");

	/* verify cmd output */
	test_log("buf: '%s'\n", buf);
	test_assert(strstr(buf, phex) != NULL, "combo key found in command output (1)");

	/* run again, verify keys unchanged, whoami output */
	memset(&state, 0, sizeof state);
	memset(buf, 0, sizeof buf); /* clear output buffer */
	REDIRECT_BUF
	rc = agent(&state, argc, argv);
	REDIRECT_OUT
	test_assert(rc == 0, "agent_run() returned %i", rc);

	/* verify keys loaded into state */
	test_assert(strlen(state.defaults.keyring.phex) > 0, "combo key loaded");
	test_expect(phex, state.defaults.keyring.phex); /* key same as last */

	/* verify cmd output */
	test_log("buf: '%s'\n", buf);
	test_assert(strstr(buf, phex) != NULL, "combo key found in command output (2)");

	free(phex);

	return test_status;
}
