//
// Syd: rock-solid unikernel
// src/syd-tty.rs: Print the controlling terminal of the given process.
//
// Copyright (c) 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{
    io::{stdout, Write},
    os::unix::ffi::OsStrExt,
    process::ExitCode,
};

use nix::{libc::pid_t, unistd::Pid};
use syd::{err::SydResult, proc::proc_tty};

// 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();

    match std::env::args().nth(1).map(|arg| arg.parse::<pid_t>()) {
        Some(Ok(pid)) => match proc_tty(Pid::from_raw(pid)) {
            Ok(path) => {
                let path = path.as_os_str().as_bytes();
                stdout().write_all(path)?;
            }
            Err(errno) => {
                eprintln!("syd-tty: {errno}");
                return Ok(ExitCode::from(errno as u8));
            }
        },
        _ => {
            println!("Usage: syd-tty pid");
            println!("Print the controlling terminal of the given process.");
            return Ok(ExitCode::FAILURE);
        }
    }

    Ok(ExitCode::SUCCESS)
}
