//
// jja: swiss army knife for chess file formats
// src/reexec.rs: Reexecuting Self for fun and profit
//
// Copyright (c) 2023 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{borrow::Cow, env::current_exe, process::Command};

use shell_escape::escape;

/// Creates a closure that returns a `Command` which re-executes the current
/// executable with the provided arguments.
///
/// This function takes a slice of `&str` representing the command line
/// arguments to pass to the re-executed program. The command with properly
/// quoted and escaped arguments will be printed to stderr before the closure
/// is returned.
///
/// # Arguments
///
/// * `args` - A slice of string references representing the command line
///   arguments to pass to the re-executed program.
///
/// # Returns
///
/// A boxed closure that, when called, returns a `Command` configured to
/// re-execute the current executable with the provided arguments.
pub fn jja_call<'a>(args: &'a [&'a str]) -> Box<dyn Fn() -> Command + 'a> {
    let jja = current_exe().expect("jja");
    let escaped_args = args
        .iter()
        .map(|s| escape(Cow::Borrowed(s)))
        .map(|cow| cow.into_owned())
        .collect::<Vec<String>>();
    eprintln!("+ {} {}", jja.display(), escaped_args.join(" "));
    Box::new(move || {
        let mut cmd = Command::new(jja.as_path());
        cmd.args(args);
        cmd
    })
}
