use anyhow::{Context, Result};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
pub fn ensure_shim_dir() -> 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)?;
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) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let shim_path = dir.join("node");
let burn_str = burn_exe.to_string_lossy();
let escaped = burn_str.replace('\'', r"'\''");
let body = format!("#!/usr/bin/env sh\nexec '{escaped}' \"$@\"\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) -> Result<()> {
let shim_path = dir.join("node.cmd");
let burn_str = burn_exe.to_string_lossy();
let body = format!("@\"{burn_str}\" %*\r\n");
fs::write(&shim_path, body).with_context(|| format!("writing {shim_path:?}"))?;
Ok(())
}