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

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

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

// Set global allocator to GrapheneOS allocator.
#[cfg(all(
    not(coverage),
    not(feature = "prof"),
    not(target_os = "android"),
    target_page_size_4k,
    target_pointer_width = "64"
))]
#[global_allocator]
static GLOBAL: hardened_malloc::HardenedMalloc = hardened_malloc::HardenedMalloc;

// Set global allocator to tcmalloc if profiling is enabled.
#[cfg(feature = "prof")]
#[global_allocator]
static GLOBAL: tcmalloc::TCMalloc = tcmalloc::TCMalloc;

syd::main! {
    syd::set_sigpipe_dfl()?;

    // Configure syd::proc.
    syd::config::proc_init_simple()?;

    let pid = match std::env::args().nth(1).map(|arg| arg.parse::<pid_t>()) {
        Some(Ok(pid)) => Pid::from_raw(pid),
        None => Pid::this(),
        Some(Err(_)) => {
            help();
            return Ok(ExitCode::SUCCESS);
        }
    };

    match proc_tty(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));
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn help() {
    println!("Usage: syd-tty [PID]");
    println!("Print the controlling terminal of the given process.");
}
