//
// Syd: rock-solid application kernel
// src/syd-read.rs: Print the canonicalized path name followed by a newline and exit.
//
// Copyright (c) 2024, 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{io::Write, process::ExitCode};

use nix::unistd::Pid;
use syd::{
    err::SydResult,
    fs::{safe_canonicalize, FsFlags},
    path::XPath,
    sandbox::Flags,
};

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

    let mut args = std::env::args();

    match args.nth(1).as_deref() {
        None | Some("-h") => {
            println!("Usage: syd-read path");
            println!("Print the canonicalized path name followed by a newline and exit.");
        }
        Some(path) => {
            let path = match safe_canonicalize(
                Pid::this(),
                None,
                XPath::new(path),
                FsFlags::NO_FOLLOW_LAST | FsFlags::NO_RESOLVE_PATH | FsFlags::NO_RESOLVE_PROC,
                Flags::empty(),
            ) {
                Ok(path) => path.take(),
                Err(error) => {
                    eprintln!("Error canonicalizing path: {error}!");
                    return Ok(ExitCode::FAILURE);
                }
            };
            std::io::stdout().write_all(path.as_bytes())?;
            println!();
        }
    }

    Ok(ExitCode::SUCCESS)
}
