// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{Arg, ArgAction, Command};
use std::io::{self, Write as _};
use uucore::{crate_version, translate};

// uucore::main does not support no-result
pub fn uumain(mut args: impl uucore::Args) -> i32 {
    // skip binary name
    let (Some(flag), None) = (args.nth(1), args.next()) else {
        return 0;
    };

    let res = if flag == "--help" {
        uu_app().print_help()
    } else if flag == "--version" {
        // avoid uu_app for smaller binary size
        writeln!(io::stdout(), "true {}", crate_version!())
    } else {
        return 0;
    };

    if let Err(e) = res
        && e.kind() != io::ErrorKind::BrokenPipe
    {
        // Try to display this error.
        let _ = writeln!(io::stderr(), "true: {}", uucore::error::strip_errno(&e));
        // Mirror GNU options. When failing to print warnings or version flags, then we exit
        // with FAIL. This avoids allocation some error information which may result in yet
        // other types of failure.
        return 1;
    }
    0
}

pub fn uu_app() -> Command {
    Command::new("true")
        .version(crate_version!())
        .help_template(uucore::localized_help_template("true"))
        .about(translate!("true-about"))
        // We provide our own help and version options, to ensure maximum compatibility with GNU.
        .disable_help_flag(true)
        .disable_version_flag(true)
        .arg(
            Arg::new("help")
                .long("help")
                .help(translate!("true-help-text"))
                .action(ArgAction::Help),
        )
        .arg(
            Arg::new("version")
                .long("version")
                .help(translate!("true-version-text"))
                .action(ArgAction::Version),
        )
}
