//
// Syd: rock-solid unikernel
// src/syd-fork.rs: Fork fast in an infinite loop.
//
// Copyright (c) 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{env, process::ExitCode};

use getargs::{Opt, Options};
use syd::err::SydResult;

// Set global allocator to mimalloc.
#[global_allocator]
static GLOBAL: mimalloc2_rust::GlobalMiMalloc = mimalloc2_rust::GlobalMiMalloc;

fn main() -> SydResult<ExitCode> {
    syd::set_sigpipe_dfl()?;

    // Configure mimalloc.
    syd::configure_mimalloc();

    let args = env::args().skip(1).collect::<Vec<_>>();
    let args: &'static Vec<String> = Box::leak(Box::new(args));
    let mut opts = Options::new(args.iter().map(String::as_str));

    #[allow(clippy::never_loop)]
    while let Some(opt) = opts.next_opt()? {
        match opt {
            Opt::Short('h') => {
                help();
                return Ok(ExitCode::SUCCESS);
            }
            Opt::Short(opt) => {
                eprintln!("Unknown option: -{opt}!");
                help();
                return Ok(ExitCode::FAILURE);
            }
            Opt::Long(opt) => {
                eprintln!("Unknown option: --{opt}!");
                help();
                return Ok(ExitCode::FAILURE);
            }
        }
    }

    // SAFETY: Do not try this at home!
    loop {
        unsafe { syd::fork_fast() };
    }
}

fn help() {
    println!("Usage: syd-fork [-h]");
    println!("Fork fast in an infinite loop.");
    println!("WARNING: DO NOT TRY THIS AT HOME!");
    println!("WARNING: USE THIS AT YOUR OWN RISK!");
    println!("WARNING: USE THIS ONLY TO STRESS-TEST YOUR PID-LIMITER!");
}
