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

#include "test.h"
#include "key.h"

int main(void)
{
	char name[] = "key_load_default()";
	key_combo_t keyring[2];
	char fakehome[] = "0000-0009-XXXXXX";
	int rc;

	test_name(name);

	/* create fake home directory */
	if (!test_assert(mkdtemp(fakehome) != NULL, "mkdtemp()")) {
		perror("mkdtemp");
		return test_status;
	}

	/* randomize key buffers */
	for (int i = 0; i < 2; i++) {
		arc4random_buf(keyring[i].phex, KEY_PUBLIC_HEXLEN + 1);
		arc4random_buf(keyring[i].shex, KEY_SECRET_HEXLEN + 1);
	}

	/* first, call key_load_default() with no key (create) */
	state_t state = { .dir_home = fakehome };
	rc = key_load_default(&state, &keyring[0]);
	test_assert(rc == 0, "key_load_default() - no key, create");

	/* now, call key_load_default() again to load previous key (load) */
	rc = key_load_default(&state, &keyring[1]);
	test_assert(rc == 0, "key_load_default() - load default key");

	test_log("public[0]: %s %i bytes\n", keyring[0].phex, KEY_PUBLIC_HEXLEN);
	test_log("public[1]: %s\n", keyring[1].phex);

	test_log("KEY_PUBLIC_HEXLEN = %i\n", KEY_PUBLIC_HEXLEN);
	test_log("KEY_SECRET_HEXLEN = %i\n", KEY_SECRET_HEXLEN);

	test_assert(memcmp(keyring[0].phex, keyring[1].phex, KEY_PUBLIC_HEXLEN) == 0, "public keys match");
	test_assert(memcmp(keyring[0].phex, keyring[1].phex, KEY_SECRET_HEXLEN) == 0, "secret keys match");

	return test_status;
}
