use anyhow::{Context, Result};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
pub fn ensure_shim_dir(flags: &[String]) -> Result<PathBuf> {
let dir = shim_dir_path();
fs::create_dir_all(&dir).with_context(|| format!("creating shim dir {dir:?}"))?;
let burn_exe = env::current_exe().context("locating burn binary")?;
write_node_shim(&dir, &burn_exe, flags)?;
Ok(dir)
}
fn shim_dir_path() -> PathBuf {
let pid = std::process::id();
env::temp_dir().join(format!("burn-shim-{pid}"))
}
#[cfg(unix)]
fn write_node_shim(dir: &Path, burn_exe: &Path, flags: &[String]) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let shim_path = dir.join("node");
let burn_str = burn_exe.to_string_lossy();
let sq = |s: &str| s.replace('\'', r"'\''");
let escaped = sq(&burn_str);
let baked: String = flags.iter().map(|f| format!(" '{}'", sq(f))).collect();
let body = format!("#!/usr/bin/env sh\nexec '{escaped}'{baked} \"$@\"\n");
fs::write(&shim_path, body).with_context(|| format!("writing {shim_path:?}"))?;
let mut perms = fs::metadata(&shim_path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&shim_path, perms).with_context(|| format!("chmod +x {shim_path:?}"))?;
Ok(())
}
#[cfg(windows)]
fn write_node_shim(dir: &Path, burn_exe: &Path, flags: &[String]) -> Result<()> {
let shim_path = dir.join("node.cmd");
let burn_str = burn_exe.to_string_lossy();
let baked: String = flags.iter().map(|f| format!(" \"{f}\"")).collect();
let body = format!("@\"{burn_str}\"{baked} %*\r\n");
fs::write(&shim_path, body).with_context(|| format!("writing {shim_path:?}"))?;
Ok(())
}