#![feature(yggdrasil_os, rustc_private)]

use std::{io, path::Path, process::ExitCode};

use clap::{Parser, Subcommand};
use cross::net::LocalPacketSocket;

#[derive(Debug, Parser)]
struct Args {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    #[command(arg_required_else_help = true)]
    Start { name: Vec<String> },
}

fn send_message(msg: init::InitMsg) -> io::Result<()> {
    let path = Path::new("/init.sock");
    let socket = LocalPacketSocket::new()?;
    let msg = serde_json::to_vec(&msg).unwrap();
    socket.send_to(&msg, path)?;
    Ok(())
}

fn run(command: Command) -> io::Result<()> {
    match command {
        Command::Start { name } => {
            let Some((binary, args)) = name.split_first() else {
                return Ok(());
            };
            let msg = init::InitMsg::StartService(init::StartService {
                binary: binary.to_owned(),
                args: args.into(),
            });

            send_message(msg)
        }
    }
}

fn main() -> ExitCode {
    let args = Args::parse();

    match run(args.command) {
        Ok(_) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("{}", e);
            ExitCode::FAILURE
        }
    }
}
