/* 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>
#include <unistd.h>

static int test_agent_stop(state_t *state)
{
	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);

	/* try to start agent again, fail with EWOULDBLOCK */
	rc = agent(state, argc, argv);
	test_assert(errno == EWOULDBLOCK, "EWOULDBLOCK");
	if (!test_assert(rc == EXIT_FAILURE, "(start again) agent() returned %i", rc))
		return test_status;

	/* check pidfile */
	if (!test_assert(state->lockfd > 0, "state->lockfd = %i", state->lockfd)) return test_status;
	char pidbuf[21] = {0}; /* fits UINT64_MAX + NUL */
	lseek(state->lockfd, 0, SEEK_SET);
	if (!test_assert(read(state->lockfd, pidbuf, sizeof pidbuf) > 0, "read pidfile")) {
		perror("read");
		return test_status;
	}
	if (!test_assert(atoi(pidbuf) == state->pid, "lockfile pid set")) return test_status;

	return test_status;
}

int main(void)
{
	char name[] = PACKAGE_NAME " start/stop";
	char fakehome[] = "0000-0022-XXXXXX";
	state_t state = {0};

	test_name(name);

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

	if (test_agent_start(&state)) return test_status;
	if (test_agent_stop(&state)) return test_status;

	return test_status;
}
