/* hk_qemu_init.c v4 — for BUILT-IN Harakiri (no module load).
 * Just mounts proc, runs the scheduler proof test, halts.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/reboot.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <errno.h>

static int read_nice(pid_t pid)
{
	int n;
	errno = 0;
	n = getpriority(PRIO_PROCESS, pid);
	if (n == -1 && errno != 0)
		return 99;
	return n;
}

static void write_file(const char *path, const char *data)
{
	FILE *f = fopen(path, "w");
	if (f) { fputs(data, f); fclose(f); }
	else printf("WARN: cannot open %s\n", path);
}

static void dump_status(void)
{
	FILE *f = fopen("/proc/harakiri/status", "r");
	char buf[256];
	if (!f) { printf("WARN: cannot open /proc/harakiri/status\n"); return; }
	printf("--- /proc/harakiri/status ---\n");
	while (fgets(buf, sizeof(buf), f))
		printf("%s", buf);
	printf("--- end status ---\n");
	fclose(f);
}

int main(void)
{
	printf("\n=== HARAKIRI QEMU TEST v4 (built-in) ===\n");

	mkdir("/proc", 0755);
	if (mount("proc", "/proc", "proc", 0, NULL) != 0)
		printf("WARN: proc mount failed\n");

	/* Harakiri is built-in — check it's alive */
	dump_status();

	/* --- scheduler proof test --- */
	{
		char tagbuf[32];
		pid_t spin;
		int nice_before, nice_after, nice_restored;

		spin = fork();
		if (spin == 0) {
			while (1) {
				volatile int i;
				for (i = 0; i < 100000; i++)
					;
				usleep(10000);
			}
		}

		printf("[*] spinner pid: %d\n", spin);
		nice_before = read_nice(spin);
		printf("[*] nice before: %d\n", nice_before);

		write_file("/proc/harakiri/mode", "gaming");
		snprintf(tagbuf, sizeof(tagbuf), "%d 5", spin);
		write_file("/proc/harakiri/tag", tagbuf);
		sleep(1);
		nice_after = read_nice(spin);
		printf("[*] nice after tag (gaming+brood): %d\n", nice_after);

		snprintf(tagbuf, sizeof(tagbuf), "%d", spin);
		write_file("/proc/harakiri/untag", tagbuf);
		sleep(1);
		nice_restored = read_nice(spin);
		printf("[*] nice after untag: %d\n", nice_restored);

		printf("[*] RESULT: %d -> %d -> %d %s\n",
		       nice_before, nice_after, nice_restored,
		       (nice_before == 0 && nice_after == -10 &&
			nice_restored == 0) ? "PASS" : "FAIL");

		kill(spin, 9);
	}

	printf("\n=== TEST COMPLETE ===\n");
	fflush(stdout);
	sleep(1);
	reboot(RB_POWER_OFF);
	return 0;
}
