/*
 * fd/netbsd.cc: support for NetBSD
 *
 * as with OpenBSD, completely untested
 */
#include "animone/fd/bsd.h"
#include "animone.h"
#include "animone/fd.h"

#include <sys/file.h>
#include <sys/filedesc.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/vnode.h>

#include <string>

namespace animone::internal::netbsd {

static std::string Basename(const std::string& name) {
	size_t s = name.find_last_of('/');

	if (s == std::string::npos)
		return name;

	return name.substr(s, name.size());
}

bool GetProcessName(pid_t pid, std::string& name) {
	static const int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};

	struct kinfo_proc result;

	size_t length = 1;
	if (sysctl((int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, &result, &length, NULL, 0) == -1)
		return false;

	name = Basename(result.ki_comm);

	return true;
}

bool EnumerateOpenProcesses(process_proc_t process_proc) {
	static const int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
	size_t length = 0;

	sysctl((int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, NULL, &length, NULL, 0);

	std::unique_ptr<struct kinfo_proc[]> result;
	result.reset(new struct kinfo_proc[length]);

	if (!result.get())
		return false;

	/* actually get our results */
	if (sysctl((const int*)mib, (sizeof(mib) / sizeof(*mib)) - 1, result.get(), &length, NULL, 0) == ENOMEM)
		return false;

	if (length < sizeof(struct kinfo_proc))
		return false;

	for (int i = 0; i < length / sizeof(result[0]); i++)
		if (!process_proc({.platform = ExecutablePlatform::Posix, .pid = result[i].ki_pid, .comm = result[i].ki_comm}))
			return false;

	return true;
}

bool EnumerateOpenFiles(const std::set<pid_t>& pids, open_file_proc_t open_file_proc) {
	/* I don't think NetBSD actually provides a real API for this. */
	return false;
}

} // namespace animone::internal::netbsd
