/* 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 <state.h>
#include <assert.h>
#include <sys/stat.h>

static int check_rcfile(state_t *state, char *home)
{
	char *rcfile;
	int rc;
	rc = snprintf(NULL, 0, "%s/%s", home, LCAGENTRC);
	if (!test_assert(rc > 0, "snprintf returned %i", rc)) return test_status;
	rcfile = malloc(rc + 1);
	if (!test_assert(rcfile != NULL, "malloc() rcfile")) return test_status;
	if (!test_assert(snprintf(rcfile, rc + 1, "%s/%s", home, LCAGENTRC) == rc,
			"snprintf()")) goto free_rcfile;
	test_expect(rcfile, state->rcfile);
free_rcfile:
	free(rcfile);
	return test_status;
}

static int check_path(char *ptr, char *fakehome, char *stub, char *name)
{
	char pathbuf[1024];
	struct stat sb;
	int rc = snprintf(pathbuf, sizeof pathbuf, "%s/%s", fakehome, stub);
	assert(rc < (int)sizeof pathbuf);
	/* check state variable is set */
	test_assert(!strcmp(ptr, pathbuf), "%s = '%s'", name, ptr);
	/* check directory path has been created */
	rc = stat(pathbuf, &sb);
	test_assert(rc == 0, "stat '%s'", pathbuf);
	return test_status;
}

int main(void)
{
	char name[] = "state_dirs()";
	char fakehome[] = "0000-0005-XXXXXX";
	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 = state_dirs(&state, fakehome);
	if (!test_assert(rc == 0, "state_dirs() returned %i", rc))
		goto err_free_statedirs;

	test_assert(!strcmp(state.dir_home, fakehome), "state.dir_home = '%s'", state.dir_home);

	check_path(state.dir_cache, fakehome, ".cache/lcagent", "dir_cache");
	check_path(state.dir_config, fakehome, ".config/lcagent", "dir_config");
	check_path(state.dir_data, fakehome, ".local/share/lcagent", "dir_data");
	check_path(state.dir_state, fakehome, ".local/state/lcagent", "dir_state");
	check_rcfile(&state, fakehome);

err_free_statedirs:
	free_state(&state);
	return test_status;
}
