//
// Syd: rock-solid application kernel
// 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

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};

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

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

    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)
}
