/*
 * Logserver
 * Copyright (C) 2017-2025 Joel Reardon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <set>
#include <string>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <fcntl.h>
#include <vector>
#include <unistd.h>
#include <csignal>
#include <sys/types.h>

#include "log_lines.h"
#include "interface.h"

using namespace std;
namespace fs = filesystem;

int stdin_process(int data_fd, int shutdown_fd) {
	constexpr size_t BUF_SIZE = 4096;
	char buf[BUF_SIZE];
	setpgid(0, 0);

	while (true) {
		fd_set fds;
		FD_ZERO(&fds);
		FD_SET(STDIN_FILENO, &fds);
		FD_SET(shutdown_fd, &fds);
		int maxfd = max(STDIN_FILENO, shutdown_fd);
		int ret = select(maxfd + 1, &fds, nullptr, nullptr, nullptr);
		if (ret == 0) continue;
		if (ret == -1) {
			cerr << "select: " << strerror(errno) << endl;
			::close(data_fd);
			::close(shutdown_fd);
			return 0;
		}
		if (FD_ISSET(shutdown_fd, &fds)) {
			::close(data_fd);
			::close(shutdown_fd);
			::close(STDIN_FILENO);
			return 0;
		}
		assert(FD_ISSET(STDIN_FILENO, &fds));
		ssize_t read_ret = ::read(STDIN_FILENO, buf, BUF_SIZE);
		if (read_ret == 0) {
			// EOF
			::close(data_fd);
			return 0;
		}
		if (read_ret < 0) {
			if (errno == EINTR) continue;
			cerr << "read: " << strerror(errno) << endl;
			::close(data_fd);
			return 1;
		}

		assert(read_ret > 0);
		ssize_t total_written = 0;
		while (total_written < read_ret) {
			ssize_t write_ret = ::write(data_fd, buf + total_written,
						read_ret - total_written);
			if (write_ret < 0) {
				if (errno == EINTR) continue;
				cerr << "write: " << strerror(errno) << endl;
				::close(data_fd);
				return 1;
			}
			assert(write_ret > 0);
			total_written += write_ret;
		}
	}
	return 0;
}

int main(int argc, char** argv) {
	CursesWrapper::start_win();
	unique_ptr<LogLines> ll;
#ifdef __USE_GEB__
	unique_ptr<TGraph> graph;
#endif
	pid_t pid = 0;
	int data_pipe[2] = {0, 0};
	int shutdown_pipe[2] = {0, 0};

	string cwd = G::realpath(".");
	Config::_()->set("initcwd", cwd);
	if (argc >= 2) {
		fs::path file_path = argv[1];
		if (access(argv[1], R_OK)) {
			cerr << "Failed to open: " << strerror(errno) << endl;
			return -1;
		} else if (fs::is_directory(file_path)) {
			string dirname = G::realpath(argv[1]);
			ll.reset(new LogLines(dirname));
		} else {
			string filename = G::realpath(argv[1]);
#ifdef __USE_GEB__
			Run magic("file " + filename);
			magic();
			string result = magic.read();
			if (result.find("GNU dbm") != string::npos) {
				// is a GDB database
				graph.reset(new TGraph(filename));
				graph->load_db();
				TGraph::Node* node = nullptr;
				if (argc > 2) node = graph->lookup(argv[2]);

				ll.reset(new LogLines(graph.get(),
						      filename,
						      node));
			} else {
				ll.reset(new LogLines(filename));
			}
#else  // not __USE_GEB__
                        ll.reset(new LogLines(filename));
#endif  // __USE_GEB__
		}
	} else {
		/* ncurses and stdin */
		int r = pipe(data_pipe);
		if (r == -1) {
			throw G::errno_string("pipe(): failed", errno);
		}
		r = pipe(shutdown_pipe);
		pid = fork();
		if (pid == -1) throw G::errno_string("fork(): failed", errno);
		if (pid == 0) {
			close(data_pipe[0]);
			return stdin_process(data_pipe[1], shutdown_pipe[0]);
		}
		close(data_pipe[1]);
		close(shutdown_pipe[0]);
		ll.reset(new LogLines(data_pipe[0]));
	}
	Interface interface(ll.release());
#ifdef __FUZZ_IX__
	interface.fuzz(50);
#else  // not __FUZZ_IX__
	interface.run();
#endif  // __FUZZ_IX__
	close(data_pipe[0]);
	int status;
	pid_t fd_pid = waitpid(pid, &status, WNOHANG);
	if (fd_pid == 0) {
		int r = write(shutdown_pipe[1], "byebye", 6);
		if (r == -1) {
			throw G::errno_string("unable to write to pipe", errno);
		}
	}
	close(shutdown_pipe[1]);
	return 0;
}
