/* 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 "testnet.h"
#include <agent.h>
#include <sys/stat.h>
#include <unistd.h>

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

static int test_agent_stop(void)
{
	state_t state = {0};
	char *argv[] = { PACKAGE_NAME, "stop", "-v", NULL };
	int argc = sizeof argv / sizeof argv[0] - 1;
	int rc;
	rc = agent(&state, argc, argv);
	test_assert(rc == EXIT_SUCCESS, "(stop) agent() returned %i", rc);
	return test_status;
}

static int test_agent_start(state_t *state)
{
	char *argv[] = { PACKAGE_NAME, "start", "-v", NULL };
	int argc = sizeof argv / sizeof argv[0] - 1;
	int rc;
	rc = agent(state, argc, argv);
	test_assert(rc == EXIT_SUCCESS, "(start) agent() returned %i", rc);
	return test_status;
}

static int test_onstart(void)
{
	state_t state = {0};
	struct stat sb;
	char fakehome[] = "0000-0028-XXXXXX";
	char cmd[128];
	char *channame[] = { "one", "two" };
	int channels = sizeof channame / sizeof channame[0];
	int rc;

	if (create_fakehome(fakehome)) return test_status;

	state.logfile = strdup("lastlog.log");

	state_defaults_set(&state);
	STATE_SET(&state, STATE_DEBUG);
	for (int i = 0; i < channels; i++) {
		state_push_channel(&state, channame[i]);
		if (i) state.chan_head->flags |= CHAN_ONSTART;
		snprintf(cmd, sizeof cmd, "touch \"%s\"", channame[i]);
		state_push_command(&state, cmd, 0);
	}

	/* start agent */
	test_agent_start(&state);

	/* wait a moment for onstart events to run */
	usleep(100000);

	/* stop agent */
	test_agent_stop();

	/* change to fake home directory to verify results */
	rc = chdir(fakehome);
	if (!test_assert(rc == 0, "chdir() returned %i", rc)) return test_status;

	/* ensure file "one" was NOT created */
	rc = stat(channame[0], &sb);
	test_assert(errno == ENOENT, "errno == ENOENT");
	test_assert(rc == -1, "stat '%s' returned %i", channame[0], rc);

	/* ensure file "two" exists */
	rc = stat(channame[1], &sb);
	test_assert(rc == 0, "stat '%s' returned %i", channame[1], rc);

	return test_status;
}

int main(void)
{
	char name[] = "event: onstart";

	test_name(name);
	test_require_net(TEST_NET_BASIC);

	if (test_onstart()) return test_status;

	return test_status;
}
