#![cfg_attr(docsrs, feature(doc_cfg))]

use std::{
  env,
  process::{Command, Stdio},
};

pub fn get() -> std::io::Result<Command> {
  let program = env::current_exe()?;
  let args: Vec<String> = env::args().skip(1).collect();
  let mut cmd = Command::new(program);
  cmd.args(args);
  cmd.stdin(Stdio::inherit());
  cmd.stdout(Stdio::inherit());
  cmd.stderr(Stdio::inherit());

  #[cfg(target_os = "linux")]
  {
    use std::os::unix::io::{FromRawFd, OwnedFd};

    use command_fds::CommandFdExt;

    let fd = 3;
    if unsafe { libc::fcntl(fd, libc::F_GETFD) } >= 0 {
      unsafe {
        let fd3 = OwnedFd::from_raw_fd(fd);
        cmd.preserved_fds(vec![fd3]);
      }
      cmd.env("LISTEN_FDS", "1");
      cmd.env_remove("LISTEN_PID");
    }
  }
  Ok(cmd)
}
