//! /system/services/init — the first user-space program, PID 1. Built as its own
//! freestanding binary (see build.zig), shipped on the boot volume at /system/services/init,
//! loaded by the bootloader, and started in ring 3 as a scheduled process by the
//! kernel (system/kernel/process.zig). It links against the shared user runtime
//! library `runtime` and talks to the kernel only through `runtime`'s system_call wrappers.
//!
//! It proves the C-convention heap works, then — as PID 1 — acts as the system's
//! **service supervisor**: it spawns the user-space services danos brings up at boot
//! (the VFS server, the device manager), and settles into an event loop as the root
//! of user space. Drivers are *not* its job: the device manager discovers the
//! hardware and spawns those. This is the service half of the service/driver spawn
//! split (docs/driver-model.md).
//!
//! M21: init also owns **orderly shutdown**. It supervises its children (keeping
//! their ids and an exit endpoint), subscribes to the power service, and on a
//! power-button event runs the stop sequence over its children in reverse order
//! before asking the power service to enter S5 — lifecycle (M17) and events (M21)
//! composing into a clean poweroff.

const std = @import("std");
const runtime = @import("runtime");
const power = runtime.power_protocol;
const build_options = @import("build_options");

/// The system services init brings up at boot, in order, by binary path. This is
/// init's policy — the microkernel keeps such choices in user space, not the
/// kernel. Drivers are absent on purpose: the device manager owns those. (A
/// future init reads this from a manifest under /system/services instead of a
/// hardcoded list.)
const boot_services = if (build_options.diagnose) [_][]const u8{
    // The diagnose boot: no display service, so the kernel's on-screen boot
    // transcript is never suppressed — the timestamped timeline (USB bring-up,
    // storage, logger) stays readable on real hardware with no serial.
    "/system/services/input",
    "/system/services/device-manager",
    "/system/services/fat",
    "/system/services/logger",
} else [_][]const u8{
    "/system/services/input",
    "/system/services/device-manager",
    "/system/services/fat",
    "/system/services/display",
    "/system/services/display-demo",
    // Last: at shutdown children stop in reverse order, so the logger goes down
    // FIRST — its final drain still has the fat server (and the whole storage
    // chain) alive underneath it.
    "/system/services/logger",
};

/// The live process id of each boot service (0 = not running), indexed by its position
/// in `boot_services`, plus how many times init has restarted it. init supervises these:
/// it spawns them against `supervision_endpoint` and, on a child's death, restarts it (up
/// to `maximum_restarts`) — the reincarnation half of resilience (docs/resilience.md), the
/// service-level counterpart to the device manager's driver restarts.
var child_ids: [boot_services.len]u32 = .{0} ** boot_services.len;
var restart_counts: [boot_services.len]u32 = .{0} ** boot_services.len;
var shutting_down = false;
var supervision_endpoint: runtime.ipc.Handle = 0;

/// Give up restarting a service after this many crashes — a crash-loop cap, so a service
/// that faults immediately on every spawn doesn't respawn forever.
const maximum_restarts = 3;

pub fn main() void {
    // Prove the heap end to end: allocate through the runtime allocator (which
    // mmaps pages from the kernel and carves them with the free list), write into
    // that heap buffer (exercising the widened debug_write bounds check), and
    // free it. A fault here would kill init before it heartbeats — so the init
    // test doubles as the heap regression test. (C code links the same heap via
    // the extern malloc/free symbols; Zig code uses this allocator.)
    const gpa = runtime.allocator();
    if (gpa.alloc(u8, 64)) |buffer| {
        const message = "/system/services/init: heap ok\n";
        @memcpy(buffer[0..message.len], message);
        _ = runtime.system.write(buffer[0..message.len]);
        gpa.free(buffer);
    } else |_| {}

    // One endpoint carries everything init waits on: children's exit
    // notifications (they are spawned supervised against it), init's own
    // signals, and power events it subscribes to. All arrive in the loop below.
    supervision_endpoint = runtime.ipc.createIpcEndpoint() orelse {
        _ = runtime.system.write("/system/services/init: no endpoint\n");
        return;
    };
    _ = runtime.process.bindSignals(supervision_endpoint);

    // Bring up the boot services, supervised so init can stop them cleanly.
    // Best-effort and silent: each service announces its own readiness, and in
    // an isolation test with no initial-ramdisk the spawns simply no-op.
    for (boot_services, 0..) |service, i| {
        if (runtime.system.spawnSupervised(service, &.{}, supervision_endpoint)) |id| child_ids[i] = id;
    }

    // Subscribe to power events (retry: the power service registers well after
    // init starts). Best-effort — without it, a `terminate` signal still
    // triggers the same shutdown path.
    subscribePower();

    // A re-arming timer drives the liveness heartbeat — proof PID 1 is alive (the
    // init test's marker) and a -Dserial diagnostic. It is a serial/test-build-only
    // concern: a flashable (serial-off) image runs a purely event-driven PID 1 that
    // wakes only for real work (signals, power events, children's exits), never for a
    // periodic beat. `build_options.serial` is comptime, so the heartbeat — its timer
    // and the handler below — folds away entirely when serial is off.
    if (build_options.serial) _ = runtime.system.timerOnce(supervision_endpoint, 1000);

    var receive: [power.message_maximum]u8 = undefined;
    while (true) {
        const got = runtime.ipc.replyWait(supervision_endpoint, &.{}, &receive, null);
        if (runtime.process.signalsFrom(got.badge)) |signals| {
            if (signals.has(.terminate)) shutDown();
            continue;
        }
        if (build_options.serial and got.isTimer()) {
            _ = runtime.system.write("/system/services/init: heartbeat\n");
            _ = runtime.system.timerOnce(supervision_endpoint, 1000);
            continue;
        }
        if (got.isMessage() and got.len >= 2 and receive[0] == @intFromEnum(power.Operation.event)) {
            // A power event (the only buffered messages init receives).
            if (receive[1] == @intFromEnum(power.Event.power_button)) shutDown();
            continue;
        }
        if (got.isChildExit()) {
            restartChild(got.childProcessId());
            continue;
        }
        // Anything else: keep waiting.
        if (got.isNotification()) continue;
    }
}

/// A supervised boot service died. Find which one and restart it — unless it exited
/// cleanly (it chose to stop, e.g. a driver with no hardware) or has hit the crash-loop
/// cap. Reclaiming the dead process is already the kernel's job (docs/process-lifecycle.md
/// iron rule 1); init only decides whether to bring it back.
fn restartChild(id: u32) void {
    if (shutting_down) return; // deaths during the stop sequence are expected, not crashes
    for (boot_services, 0..) |service, i| {
        if (child_ids[i] != id) continue;
        child_ids[i] = 0;
        // An unknown reason (the record aged out) is treated as a crash worth restarting.
        const reason = runtime.process.exitReason(id) orelse .fault;
        if (reason == .exited) {
            std.log.info("{s} exited cleanly; not restarting", .{service});
            return;
        }
        restart_counts[i] += 1;
        if (restart_counts[i] > maximum_restarts) {
            std.log.info("{s} keeps crashing; giving up after {d} restarts", .{ service, maximum_restarts });
            return;
        }
        std.log.info("{s} died ({s}); restarting ({d}/{d})", .{ service, @tagName(reason), restart_counts[i], maximum_restarts });
        if (runtime.system.spawnSupervised(service, &.{}, supervision_endpoint)) |new_id| child_ids[i] = new_id;
        return;
    }
    // An untracked child (e.g. the log-flush one-shot): nothing to restart.
}

/// Look up the power service and subscribe our endpoint (handed over as the
/// call's capability) so events arrive as buffered messages here.
fn subscribePower() void {
    var handle: ?runtime.ipc.Handle = null;
    var tries: u32 = 0;
    while (handle == null and tries < 200) : (tries += 1) {
        handle = runtime.ipc.lookup(.power);
        if (handle == null) runtime.system.sleep(20);
    }
    // A missing power service is not fatal — init proceeds to its heartbeat and
    // a `terminate` signal still drives shutdown. Silent so the no-ramdisk init
    // test's heartbeat marker is the next line written.
    const h = handle orelse return;
    const request = power.Subscribe{};
    var reply: [power.message_maximum]u8 = undefined;
    _ = runtime.ipc.callCap(h, std.mem.asBytes(&request), &reply, supervision_endpoint) catch {};
}

/// The stop sequence: persist the log while storage is still up, then terminate
/// each child in reverse spawn order (vfs last — other services may flush through
/// it), waiting up to a deadline for each to exit before killing it, then ask the
/// power service to enter S5.
fn shutDown() void {
    shutting_down = true; // the stop loop below kills children — those deaths aren't crashes
    _ = runtime.system.write("/system/services/init: shutting down\n");
    // Log persistence is the logger service's job: it is the LAST boot service,
    // so the reverse-order stop below terminates it first and its final drain
    // runs while the whole storage chain is still alive.
    var i = boot_services.len;
    while (i > 0) {
        i -= 1;
        if (child_ids[i] != 0) runtime.process.stop(child_ids[i], 2000, supervision_endpoint);
    }
    if (runtime.ipc.lookup(.power)) |h| {
        const request = power.Shutdown{};
        var reply: [power.message_maximum]u8 = undefined;
        _ = runtime.ipc.call(h, std.mem.asBytes(&request), &reply) catch {};
    }
    // If S5 did not take, init has nothing left to do but idle.
    while (true) runtime.system.sleep(1000);
}
