//! /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 ipc = @import("ipc");
const process = @import("process");
const time = @import("time");
const memory = @import("memory");
const logging = @import("logging");
const power_protocol = @import("power-protocol");
const build_options = @import("build_options");
const fs = @import("file-system");
const csv = @import("csv");

/// The system services init brings up at boot are init's policy, not the kernel's —
/// and that policy is now data: `/system/configuration/init.csv` (see `loadServices`), read at
/// startup instead of a hardcoded list. Drivers are absent on purpose: the device
/// manager owns those.
///
/// The most services `/system/configuration/init.csv` can list, and the most argv entries (beyond the
/// path) each may carry. Fixed caps because init parses the list into static storage —
/// the freestanding, no-allocator counterpart to the device manager's registry table.
const max_services = 16;
const max_service_args = 4;

/// One service init starts, parsed from a row of `/system/configuration/init.csv`: its binary path
/// and argv, both slices into `init_csv` (held for the life of the process).
const Service = struct {
    path: []const u8 = "",
    arg_buffer: [max_service_args][]const u8 = undefined,
    arg_count: usize = 0,
    fn arguments(self: *const Service) []const []const u8 {
        return self.arg_buffer[0..self.arg_count];
    }
};

/// The `/system/configuration/init.csv` bytes, held because the parsed services slice into them.
var init_csv: [4096]u8 = undefined;
var services: [max_services]Service = .{Service{}} ** max_services;
var service_count: usize = 0;

/// The live process id of each service (0 = not running) and its restart count,
/// indexed by position in `services`. 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: [max_services]u32 = .{0} ** max_services;
var restart_counts: [max_services]u32 = .{0} ** max_services;
var shutting_down = false;
var supervision_endpoint: ipc.Handle = 0;

/// Parse `/system/configuration/init.csv` into `services`, in file order (startup order; shutdown is
/// the reverse). Each row is a binary path followed by its argv, comma-separated;
/// `#` comments and blank lines are ignored. The file lives in the initial ramdisk,
/// which the kernel serves directly, so init — PID 1, running before any filesystem
/// service — reads it with a plain fs.open, the same mechanism the device manager
/// uses for /system/configuration/devices.csv. A missing file means no services (the no-ramdisk
/// isolation test): loud, but not fatal.
fn loadServices() void {
    var file = fs.open("/system/configuration/init.csv", .{}) orelse {
        _ = logging.write("/system/services/init: /system/configuration/init.csv missing — no services started\n");
        return;
    };
    defer file.close();
    var used: usize = 0;
    while (used < init_csv.len) {
        const n = file.read(init_csv[used..]) orelse break;
        if (n == 0) break;
        used += n;
    }
    var lines = std.mem.splitScalar(u8, init_csv[0..used], '\n');
    while (lines.next()) |line| {
        const body = csv.stripComment(line);
        if (body.len == 0) continue;
        if (service_count >= services.len) {
            _ = logging.write("/system/services/init: /system/configuration/init.csv has more services than the table holds\n");
            break;
        }
        var it = csv.fields(body);
        const path = it.next() orelse continue;
        if (path.len == 0) continue;
        var service: Service = .{ .path = path };
        while (it.next()) |argument| {
            if (argument.len == 0) continue; // padding, or a trailing comma
            if (service.arg_count >= max_service_args) break;
            service.arg_buffer[service.arg_count] = argument;
            service.arg_count += 1;
        }
        services[service_count] = service;
        service_count += 1;
    }
}

/// 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 = memory.allocator();
    if (gpa.alloc(u8, 64)) |buffer| {
        const message = "/system/services/init: heap ok\n";
        @memcpy(buffer[0..message.len], message);
        _ = logging.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 = ipc.createIpcEndpoint() orelse {
        _ = logging.write("/system/services/init: no endpoint\n");
        return;
    };
    _ = process.bindSignals(supervision_endpoint);

    // Load the service list, then bring each up supervised so init can stop them
    // cleanly. Best-effort and silent: each service announces its own readiness,
    // and with no /system/configuration/init.csv (an isolation test) the loop starts nothing.
    loadServices();
    for (services[0..service_count], 0..) |*service, i| {
        if (process.spawnSupervised(service.path, service.arguments(), 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) _ = time.timerOnce(supervision_endpoint, 1000);

    var receive: [power_protocol.message_maximum]u8 = undefined;
    while (true) {
        const got = ipc.replyWait(supervision_endpoint, &.{}, &receive, null);
        if (process.signalsFrom(got.badge)) |signals| {
            if (signals.has(.terminate)) shutDown();
            continue;
        }
        if (build_options.serial and got.isTimer()) {
            _ = logging.write("/system/services/init: heartbeat\n");
            _ = time.timerOnce(supervision_endpoint, 1000);
            continue;
        }
        if (got.isMessage() and got.len >= 2 and receive[0] == @intFromEnum(power_protocol.Operation.event)) {
            // A power event (the only buffered messages init receives).
            if (receive[1] == @intFromEnum(power_protocol.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 (services[0..service_count], 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 = process.exitReason(id) orelse .fault;
        if (reason == .exited) {
            std.log.info("{s} exited cleanly; not restarting", .{service.path});
            return;
        }
        restart_counts[i] += 1;
        if (restart_counts[i] > maximum_restarts) {
            std.log.info("{s} keeps crashing; giving up after {d} restarts", .{ service.path, maximum_restarts });
            return;
        }
        std.log.info("{s} died ({s}); restarting ({d}/{d})", .{ service.path, @tagName(reason), restart_counts[i], maximum_restarts });
        if (process.spawnSupervised(service.path, service.arguments(), 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: ?ipc.Handle = null;
    var tries: u32 = 0;
    while (handle == null and tries < 200) : (tries += 1) {
        handle = ipc.lookup(.power);
        if (handle == null) time.sleepMillis(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_protocol.Subscribe{};
    var reply: [power_protocol.message_maximum]u8 = undefined;
    _ = 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
    _ = logging.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 = service_count;
    while (i > 0) {
        i -= 1;
        if (child_ids[i] != 0) process.stop(child_ids[i], 2000, supervision_endpoint);
    }
    if (ipc.lookup(.power)) |h| {
        const request = power_protocol.Shutdown{};
        var reply: [power_protocol.message_maximum]u8 = undefined;
        _ = ipc.call(h, std.mem.asBytes(&request), &reply) catch {};
    }
    // If S5 did not take, init has nothing left to do but idle.
    while (true) time.sleepMillis(1000);
}
