Skip to main content

thunderstore_engine/profile/
launch.rs

1//! Compute how to launch a game with a target directory's mods applied.
2//!
3//! The engine produces a [`LaunchPlan`](crate::profile::launch::LaunchPlan) — the program to start, its argv, its
4//! environment, and a working directory — and the **caller** spawns it. The engine
5//! never discovers a game directory, never reads the host platform, and never
6//! starts a process; platform facts arrive as explicit [`LaunchContext`](crate::profile::launch::LaunchContext) fields so
7//! every combination is testable.
8//!
9//! Injection is command-line arguments, not config files: a loader package ships
10//! its own `doorstop_config.ini` / proxy DLL / `run_bepinex.sh` into the target at
11//! install time, and the arguments computed here override that ini at runtime.
12//!
13//! Argv is returned as a real argv vector and is **never shell-quoted** — pass it
14//! to `Command::args`, not to a shell.
15
16#![deny(missing_docs)]
17
18use crate::ecosystem::{Ecosystem, GameProfile, InstanceType, LoaderKind};
19use crate::error::{Error, Result};
20use std::path::{Path, PathBuf};
21
22mod prepare;
23
24pub use prepare::{LaunchNotice, prepare_plan_from};
25#[cfg(feature = "io")]
26pub use prepare::{PreparedLaunch, prepare_launch};
27
28/// The operating system the game will run on.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum HostOs {
32  /// Windows. Loader paths handed to the game are Windows-shaped natively.
33  Windows,
34  /// Linux. The only host where [`LaunchPlan::steam_wrapper`] can apply, and the
35  /// only one where [`Runtime::Proton`] is meaningful.
36  Linux,
37  /// macOS. Rejected by [`launch_plan_in`], which cannot compute a correct plan
38  /// because r2modman injects through a compiled proxy binary with no available
39  /// source.
40  MacOs,
41}
42
43impl HostOs {
44  /// The operating system this build is running on, or `None` where launching is
45  /// not supported.
46  ///
47  /// Reads the compile-time target rather than a runtime probe, because a build
48  /// cannot run on a platform it was not compiled for.
49  pub fn detect() -> Option<Self> {
50    if cfg!(target_os = "windows") {
51      Some(Self::Windows)
52    } else if cfg!(target_os = "linux") {
53      Some(Self::Linux)
54    } else if cfg!(target_os = "macos") {
55      Some(Self::MacOs)
56    } else {
57      None
58    }
59  }
60}
61
62/// How the game is distributed, which decides what process is started.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum StorePlatform {
66  /// Launch through Steam (`-applaunch <id>`).
67  Steam,
68  /// A Steam copy launched by executing the game binary directly.
69  SteamDirect,
70  /// Any other store: execute the game binary directly.
71  Other,
72}
73
74impl std::str::FromStr for StorePlatform {
75  type Err = Error;
76
77  /// Parses the spelling a client's configuration uses.
78  fn from_str(value: &str) -> Result<Self> {
79    match value {
80      "steam" => Ok(Self::Steam),
81      "steam-direct" => Ok(Self::SteamDirect),
82      "other" => Ok(Self::Other),
83      other => Err(Error::Profile(format!(
84        "{other:?} is not a known store platform; expected steam, steam-direct, \
85         or other"
86      ))),
87    }
88  }
89}
90
91/// Whether the game runs natively or under Proton/Wine.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum Runtime {
95  /// The game runs as a native binary for [`HostOs`].
96  Native,
97  /// The game is a Windows build running under Proton or Wine, so paths handed
98  /// to it are Windows-shaped.
99  Proton,
100}
101
102impl std::str::FromStr for Runtime {
103  type Err = Error;
104
105  /// Parses the spelling a client's configuration uses.
106  fn from_str(value: &str) -> Result<Self> {
107    match value {
108      "native" => Ok(Self::Native),
109      "proton" => Ok(Self::Proton),
110      other => Err(Error::Profile(format!(
111        "{other:?} is not a known runtime; expected native or proton"
112      ))),
113    }
114  }
115}
116
117/// Launch with mods applied, or without.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum LaunchMode {
121  /// Inject the loader so the target directory's mods are applied.
122  Modded,
123  /// Start the game with the loader explicitly disabled.
124  ///
125  /// Installed files stay on disk untouched, so this is a per-launch toggle
126  /// rather than an uninstall. Most loaders take an explicit off switch here
127  /// (`--vanilla`, `-vanilla`, `--gdweave-disable`) rather than simply omitting
128  /// the on switch, because a loader already staged into the game directory
129  /// would otherwise still initialise.
130  Vanilla,
131}
132
133/// The process the caller should start.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum LaunchProgram {
137  /// Execute the game binary. The caller resolves which of `exe_names` exists in
138  /// its game directory.
139  GameExe {
140    /// Candidate binary names, in preference order.
141    exe_names: Vec<String>,
142  },
143  /// Execute Steam with `-applaunch <steam_app_id>`.
144  Steam {
145    /// The Steam application id to hand to `-applaunch`.
146    steam_app_id: u32,
147  },
148  /// Execute a script the loader package shipped into the target directory (one
149  /// of [`LOADER_SCRIPTS`]), passing the game binary and then [`LaunchPlan::args`]
150  /// after it. The caller resolves which of `exe_names` exists in its game
151  /// directory, exactly as for [`LaunchProgram::GameExe`].
152  ProfileScript {
153    /// The loader script inside the target directory to execute.
154    path: PathBuf,
155    /// Candidate game binary names, in preference order, passed to the script
156    /// ahead of [`LaunchPlan::args`].
157    exe_names: Vec<String>,
158  },
159}
160
161/// What a caller needs to install the wrapper script for a Linux native Steam
162/// launch, carried by [`LaunchPlan::steam_wrapper`] when that combination applies.
163///
164/// Steam's launch options are a single fixed `%command%` string, so a file must sit
165/// between Steam and the game; [`LaunchPlan::program`] alone cannot express that.
166/// Neither [`write_wrapper_script`] nor [`steam_launch_options`] needs anything
167/// from here — both take only a path, because the script names no target and the
168/// options string names no loader. This type is what tells a caller the wrapper is
169/// required at all.
170///
171/// The wrapper is written **once** and never rewritten: it resolves its target at
172/// run time from [`WRAPPER_TARGET_FLAG`], which [`launch_plan_in`] has already
173/// appended to [`LaunchPlan::args`] whenever it populates this field. A caller
174/// spawns the plan as computed and the correct target follows automatically, so
175/// the launch-options string a user pasted stays valid across every target.
176#[derive(Debug, Clone, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct SteamWrapper {
179  /// The target directory the wrapper chainloads from, which reaches it as a
180  /// run-time argument already present in [`LaunchPlan::args`]. Reported here so
181  /// a caller can display or log it, not because the wrapper needs writing for it.
182  pub target_dir: PathBuf,
183  /// The loader this target injects through, reported for display and logging.
184  ///
185  /// No longer feeds [`steam_launch_options`], which dropped its `WINEDLLOVERRIDES`
186  /// and with it the need for a loader. [`proxy_dll`] still maps this to a DLL name
187  /// for a caller setting up a Wine prefix by hand.
188  pub loader: LoaderKind,
189}
190
191/// A fully computed launch invocation.
192///
193/// `#[non_exhaustive]`: fields may be added as more platforms are supported.
194#[derive(Debug, Clone, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct LaunchPlan {
197  /// What to execute.
198  pub program: LaunchProgram,
199  /// Arguments, in order, already resolved. Never shell-quoted.
200  pub args: Vec<String>,
201  /// Environment variables to set for the child process.
202  ///
203  /// **Only honoured for a program the caller spawns directly.** When
204  /// [`Self::program`] is [`LaunchProgram::Steam`], these are set on the
205  /// short-lived `steam` process, and `steam -applaunch <id>` merely messages an
206  /// already-running Steam client, which starts the game with *its own*
207  /// environment. Nothing here reaches the game in that case. The visible
208  /// consequence is a Proton + Steam launch silently starting unmodded: without
209  /// `WINEDLLOVERRIDES`, Wine loads its builtin proxy instead of the loader's and
210  /// BepInEx never initialises, leaving no log to explain why. A caller needing the
211  /// override under Steam must put it in the Wine prefix ([`proxy_dll`] gives the
212  /// name), not here.
213  pub env: Vec<(String, String)>,
214  /// Working directory, when it matters.
215  pub working_dir: Option<PathBuf>,
216  /// `Some` when starting [`Self::program`] is not sufficient on its own: a Linux
217  /// native Steam launch injects through a loader script that Steam will not run
218  /// unless a wrapper script is installed in its launch options. See
219  /// [`SteamWrapper`], [`write_wrapper_script`], and [`steam_launch_options`].
220  pub steam_wrapper: Option<SteamWrapper>,
221}
222
223/// The platform facts a launch computation needs, supplied by the caller.
224#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub struct LaunchContext {
227  /// The operating system the game will run on. Supplied rather than detected so
228  /// every combination stays testable; [`HostOs::detect`] is the caller's opt-in.
229  pub os: HostOs,
230  /// How the game is distributed, which decides what process is started and
231  /// whether the environment in [`LaunchPlan::env`] can reach the game at all.
232  pub store: StorePlatform,
233  /// Whether the game runs natively or under Proton/Wine, which decides whether
234  /// paths in the computed argv are Unix- or Windows-shaped.
235  pub runtime: Runtime,
236  /// Whether to inject the loader or start the game vanilla.
237  pub mode: LaunchMode,
238  /// Caller/user-supplied arguments, appended after the loader's own.
239  pub extra_args: Vec<String>,
240}
241
242impl LaunchContext {
243  /// Builds a [`LaunchContext`] with an empty `extra_args`.
244  ///
245  /// `LaunchContext` is `#[non_exhaustive]`, so outside this crate it cannot be
246  /// built with a struct literal, nor updated with functional-update (`..`)
247  /// syntax — both are struct-literal forms and `#[non_exhaustive]` forbids both
248  /// from other crates. This constructor is the supported way for a downstream
249  /// crate (including this crate's own `tests/*.rs`, which compile as separate
250  /// crates) to construct one; use [`Self::with_extra_args`] to add extras.
251  pub fn new(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> Self {
252    Self {
253      os,
254      store,
255      runtime,
256      mode,
257      extra_args: Vec::new(),
258    }
259  }
260
261  /// Returns `self` with `extra_args` replaced, for chaining after [`Self::new`].
262  pub fn with_extra_args(self, extra_args: Vec<String>) -> Self {
263    Self { extra_args, ..self }
264  }
265}
266
267/// Preloader assembly names a BepInEx package may ship, in the order r2modman
268/// lists them. The first one present in `<target>/BepInEx/core` wins.
269pub const PRELOADER_CANDIDATES: [&str; 5] = [
270  "BepInEx.Unity.Mono.Preloader.dll",
271  "BepInEx.Unity.IL2CPP.dll",
272  "BepInEx.Preloader.dll",
273  "BepInEx.IL2CPP.dll",
274  "BepInEx.NET.CoreCLR.dll",
275];
276
277/// The loader scripts a BepInEx/BepisLoader package may ship into the target, in
278/// precedence order. Both the resolver behind [`launch_plan_in`] and the wrapper
279/// script from [`wrapper_script_contents`] chainload the first one present, so the
280/// two agree by construction.
281///
282/// `start_server_bepinex.sh` is only ever selected for an
283/// [`InstanceType::Server`] profile — running it for a game instance would start a
284/// dedicated server. The wrapper, which has no ecosystem profile to consult at run
285/// time, gates it on the `TS_START_SERVER` environment variable instead.
286pub const LOADER_SCRIPTS: [&str; 3] = [
287  "start_server_bepinex.sh",
288  "run_bepinex.sh",
289  "start_game_bepinex.sh",
290];
291
292/// The dedicated-server entry of [`LOADER_SCRIPTS`].
293const SERVER_SCRIPT: &str = LOADER_SCRIPTS[0];
294
295/// The refusal both [`launch_plan_in`] and [`stage_for_launch_in`] return for macOS:
296/// no plan can be computed, so nothing may be written into a game directory either.
297const MACOS_UNSUPPORTED: &str =
298  "macOS launch is not supported: the injection chain requires r2modman's closed-source proxy";
299
300/// What the launch planner needs to know about a target directory's contents.
301///
302/// [`launch_plan_from`] and [`loader_args_from`] decide from these instead of
303/// reading the target. With the `io` feature, `LaunchFacts::read` gathers them
304/// from disk. A caller that already knows them starts from
305/// [`LaunchFacts::default`], which describes an empty target, and sets the fields
306/// that differ.
307///
308/// # Examples
309///
310/// ```
311/// use thunderstore_engine::profile::launch::{LaunchFacts, LOADER_SCRIPTS};
312///
313/// let mut facts = LaunchFacts::default();
314///
315/// facts.doorstop_version = 4;
316/// facts.loader_scripts = vec![LOADER_SCRIPTS[1].to_string()];
317///
318/// assert_eq!(facts.preloader, None);
319/// ```
320#[derive(Debug, Clone, PartialEq, Eq)]
321#[non_exhaustive]
322pub struct LaunchFacts {
323  /// The Doorstop major version recorded in `.doorstop_version`, or `3` when the
324  /// file is missing, unparseable, or below 3. A major of `4` or higher selects
325  /// the v4 argument spellings.
326  pub doorstop_version: u32,
327  /// The first [`PRELOADER_CANDIDATES`] entry present in `BepInEx/core`, by file
328  /// name.
329  pub preloader: Option<String>,
330  /// Whether an `unstripped_corlib` directory exists, which needs a Doorstop
331  /// search-path override.
332  pub has_corlibs: bool,
333  /// The [`LOADER_SCRIPTS`] present as files in the target root, by name.
334  pub loader_scripts: Vec<String>,
335  /// Whether MelonLoader's `Assembly-CSharp.dll` exists in either its 0.5
336  /// (`MelonLoader/Managed`) or 0.6 (`MelonLoader/Il2CppAssemblies`) layout. When
337  /// neither does, MelonLoader is asked to regenerate its assembly cache.
338  pub melonloader_assemblies: bool,
339  /// The loader kinds whose files from [`LOADER_FILES`] are in the target.
340  /// BepInEx and BepisLoader are found through [`Self::preloader`] instead.
341  pub loaders: Vec<LoaderKind>,
342  /// The package names recorded in the target's `mods.yml`, which name the
343  /// loader pack the engine or r2modman installed.
344  pub recorded: Vec<String>,
345}
346
347impl Default for LaunchFacts {
348  fn default() -> Self {
349    Self {
350      doorstop_version: 3,
351      preloader: None,
352      has_corlibs: false,
353      loader_scripts: Vec::new(),
354      melonloader_assemblies: false,
355      loaders: Vec::new(),
356      recorded: Vec::new(),
357    }
358  }
359}
360
361/// MelonLoader's own assembly in the 0.5 layout and the 0.6 and 0.7 runtimes.
362const MELONLOADER_FILES: [&str; 4] = [
363  "MelonLoader/MelonLoader.dll",
364  "MelonLoader/net35/MelonLoader.dll",
365  "MelonLoader/net472/MelonLoader.dll",
366  "MelonLoader/net6/MelonLoader.dll",
367];
368
369/// Files that show a loader is installed in a target, any one of them enough.
370///
371/// Each path is where r2modman's installer for that loader puts a file from
372/// the loader's Thunderstore pack. Lovely, GodotMl, and ReturnOfModding have no
373/// entry because their paths are unverified, so they are found only through
374/// the loader pack recorded in `mods.yml` ([`LaunchFacts::recorded`]).
375pub const LOADER_FILES: [(LoaderKind, &[&str]); 7] = [
376  (LoaderKind::Umm, &["UMM/Core/UnityModManager.dll"]),
377  (LoaderKind::MelonLoader, &MELONLOADER_FILES),
378  (LoaderKind::RecursiveMelonLoader, &MELONLOADER_FILES),
379  (
380    LoaderKind::GdWeave,
381    &["GDWeave/core/GDWeave.dll", "winmm.dll"],
382  ),
383  (
384    LoaderKind::Northstar,
385    &["R2Northstar/Northstar.dll", "NorthstarLauncher.exe"],
386  ),
387  (LoaderKind::Rivet, &["Rivet/Loader.dll"]),
388  (LoaderKind::Shimloader, &["dwmapi.dll", "ue4ss.dll"]),
389];
390
391#[cfg(feature = "io")]
392impl LaunchFacts {
393  /// Reads every fact from `target_dir`. A missing or unreadable file counts as
394  /// absent, so this never fails.
395  pub fn read(target_dir: &Path) -> Self {
396    let loader_scripts = LOADER_SCRIPTS
397      .iter()
398      .filter(|name| target_dir.join(name).is_file())
399      .map(|name| name.to_string())
400      .collect();
401    let melonloader_assemblies = target_dir
402      .join("MelonLoader/Managed/Assembly-CSharp.dll")
403      .is_file()
404      || target_dir
405        .join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll")
406        .is_file();
407    let loaders = LOADER_FILES
408      .iter()
409      .filter(|(_, files)| files.iter().any(|file| target_dir.join(file).is_file()))
410      .map(|(loader, _)| *loader)
411      .collect();
412    let recorded = crate::profile::modlist::read(target_dir)
413      .map(|mods| mods.into_iter().map(|entry| entry.name).collect())
414      .unwrap_or_default();
415
416    Self {
417      doorstop_version: doorstop_version(target_dir),
418      preloader: find_preloader(target_dir),
419      has_corlibs: has_corlibs(target_dir),
420      loader_scripts,
421      melonloader_assemblies,
422      loaders,
423      recorded,
424    }
425  }
426}
427
428/// Reads the Doorstop major version from `<target_dir>/.doorstop_version`,
429/// defaulting to `3` when the file is missing or unparseable.
430///
431/// A major of `4` or higher selects the v4 argument spellings. r2modman instead
432/// falls back to v3 for anything above 4, which mis-launches a future Doorstop;
433/// we deliberately do not reproduce that.
434#[cfg(feature = "io")]
435pub fn doorstop_version(target_dir: &Path) -> u32 {
436  let path = target_dir.join(".doorstop_version");
437
438  let text = match std::fs::read_to_string(&path) {
439    Ok(text) => text,
440    Err(_) => return 3,
441  };
442
443  let major = text
444    .trim()
445    .split('.')
446    .next()
447    .and_then(|part| part.parse::<u32>().ok());
448
449  match major {
450    Some(version) if version >= 3 => version,
451    _ => 3,
452  }
453}
454
455/// Renders `path` for a Wine/Proton prefix: forward slashes, `Z:` root mapping.
456fn wine_path(path: &Path) -> String {
457  format!("Z:{}", path.to_string_lossy().replace('\\', "/"))
458}
459
460/// Locates the BepInEx preloader assembly inside `<target_dir>/BepInEx/core`.
461///
462/// Under [`Runtime::Proton`] the path is rendered for the Wine prefix (`Z:` +
463/// forward slashes), which is how the Windows-side Doorstop resolves a Linux path.
464#[cfg(feature = "io")]
465pub fn bepinex_preloader(target_dir: &Path, runtime: Runtime) -> Result<String> {
466  render_preloader(target_dir, find_preloader(target_dir).as_deref(), runtime)
467}
468
469/// The first [`PRELOADER_CANDIDATES`] entry present in `<target_dir>/BepInEx/core`.
470#[cfg(feature = "io")]
471fn find_preloader(target_dir: &Path) -> Option<String> {
472  let core = target_dir.join("BepInEx").join("core");
473
474  PRELOADER_CANDIDATES
475    .iter()
476    .find(|name| core.join(name).is_file())
477    .map(|name| name.to_string())
478}
479
480/// Renders the path of `preloader` inside `<target_dir>/BepInEx/core` as a
481/// Doorstop target, erroring when there is none.
482fn render_preloader(
483  target_dir: &Path,
484  preloader: Option<&str>,
485  runtime: Runtime,
486) -> Result<String> {
487  let core = target_dir.join("BepInEx").join("core");
488
489  let found = preloader
490    .map(|name| core.join(name))
491    .ok_or_else(|| Error::Profile(format!("no BepInEx preloader found in {}", core.display())))?;
492
493  let rendered = match runtime {
494    Runtime::Proton => wine_path(&found),
495    Runtime::Native => found.to_string_lossy().replace('\\', "/"),
496  };
497
498  Ok(rendered)
499}
500
501/// Whether the target ships unstripped corlibs, which need a Doorstop search-path
502/// override.
503#[cfg(feature = "io")]
504pub fn has_corlibs(target_dir: &Path) -> bool {
505  target_dir.join("unstripped_corlib").is_dir()
506}
507
508/// Renders a target-relative path as an argument value, using forward slashes so
509/// a Windows-side loader reads it consistently.
510fn arg_path(target_dir: &Path, relative: &str) -> String {
511  target_dir
512    .join(relative)
513    .to_string_lossy()
514    .replace('\\', "/")
515}
516
517/// The loader's own arguments for the requested mode, before any caller-supplied
518/// extras. An unrecognized loader contributes nothing rather than erroring, so a
519/// newer ecosystem schema degrades to a vanilla launch.
520///
521/// Reads the target's [`LaunchFacts`] and computes with [`loader_args_from`].
522#[cfg(feature = "io")]
523pub fn loader_args(
524  target_dir: &Path,
525  profile: &GameProfile,
526  ctx: &LaunchContext,
527) -> Result<Vec<String>> {
528  loader_args_from(target_dir, &LaunchFacts::read(target_dir), profile, ctx)
529}
530
531/// The loader's own arguments for the requested mode, computed from `facts`
532/// about `target_dir` without touching disk. An unrecognized loader contributes
533/// nothing rather than erroring, so a newer ecosystem schema degrades to a
534/// vanilla launch.
535///
536/// For [`LoaderKind::BepInEx`] and [`LoaderKind::Umm`], the Doorstop flag
537/// spellings depend on more than [`LaunchFacts::doorstop_version`]: a present
538/// loader script forces the v4 spellings regardless of the detected version
539/// (see `doorstop_args`'s doc comment).
540///
541/// # Errors
542///
543/// [`Error::Profile`] when a modded BepInEx or BepisLoader launch has no
544/// [`LaunchFacts::preloader`].
545pub fn loader_args_from(
546  target_dir: &Path,
547  facts: &LaunchFacts,
548  profile: &GameProfile,
549  ctx: &LaunchContext,
550) -> Result<Vec<String>> {
551  let target = target_dir.to_string_lossy().replace('\\', "/");
552
553  let args = match profile.package_loader {
554    LoaderKind::BepInEx => {
555      let script_injected = is_script_injected(target_dir, facts, profile, ctx);
556
557      doorstop_args(
558        target_dir,
559        facts,
560        profile,
561        ctx,
562        DoorstopTarget::BepInEx,
563        script_injected,
564      )?
565    }
566    LoaderKind::BepisLoader => bepis_args(target_dir, facts, profile, ctx)?,
567    LoaderKind::Umm => {
568      let script_injected = is_script_injected(target_dir, facts, profile, ctx);
569
570      doorstop_args(
571        target_dir,
572        facts,
573        profile,
574        ctx,
575        DoorstopTarget::Umm,
576        script_injected,
577      )?
578    }
579    LoaderKind::MelonLoader | LoaderKind::RecursiveMelonLoader => {
580      melonloader_args(facts, ctx, &target)
581    }
582    LoaderKind::GdWeave => match ctx.mode {
583      LaunchMode::Modded => vec![format!(
584        "--gdweave-folder-override={}",
585        arg_path(target_dir, "GDWeave")
586      )],
587      LaunchMode::Vanilla => vec!["--gdweave-disable".to_string()],
588    },
589    LoaderKind::Lovely => match ctx.mode {
590      LaunchMode::Modded => vec!["--mod-dir".to_string(), arg_path(target_dir, "mods")],
591      LaunchMode::Vanilla => vec!["--vanilla".to_string()],
592    },
593    LoaderKind::Northstar => match ctx.mode {
594      LaunchMode::Modded => vec![
595        "-northstar".to_string(),
596        format!("-profile={}", arg_path(target_dir, "R2Northstar")),
597      ],
598      LaunchMode::Vanilla => vec!["-vanilla".to_string()],
599    },
600    LoaderKind::GodotMl => match ctx.mode {
601      LaunchMode::Modded => vec![
602        "--script".to_string(),
603        "res://addons/mod_loader/mod_loader_setup.gd".to_string(),
604        "--enable-mods".to_string(),
605        "--mods-path".to_string(),
606        arg_path(target_dir, "mods"),
607      ],
608      LaunchMode::Vanilla => Vec::new(),
609    },
610    LoaderKind::Shimloader => match ctx.mode {
611      LaunchMode::Modded => vec![
612        "--mod-dir".to_string(),
613        arg_path(target_dir, "shimloader/mod"),
614        "--pak-dir".to_string(),
615        arg_path(target_dir, "shimloader/pak"),
616        "--cfg-dir".to_string(),
617        arg_path(target_dir, "shimloader/cfg"),
618        "--overlay-dir".to_string(),
619        arg_path(target_dir, "shimloader/overlay"),
620      ],
621      LaunchMode::Vanilla => Vec::new(),
622    },
623    LoaderKind::ReturnOfModding => match ctx.mode {
624      LaunchMode::Modded => vec!["--rom_modding_root_folder".to_string(), target.clone()],
625      LaunchMode::Vanilla => vec!["--rom_enabled".to_string(), "false".to_string()],
626    },
627    LoaderKind::Rivet => match ctx.mode {
628      LaunchMode::Modded => vec![
629        "-rivetEnable".to_string(),
630        "true".to_string(),
631        "-rivetTarget".to_string(),
632        arg_path(target_dir, "Rivet/Loader.dll"),
633        "-rivetDirectory".to_string(),
634        arg_path(target_dir, "Rivet/Mods"),
635      ],
636      LaunchMode::Vanilla => vec!["-rivetEnable".to_string(), "false".to_string()],
637    },
638    // `None`, `Other`, and any loader a newer schema adds inject nothing: their
639    // files simply sit in the game directory.
640    _ => Vec::new(),
641  };
642
643  Ok(args)
644}
645
646/// Which assembly a Doorstop-based loader targets.
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648enum DoorstopTarget {
649  BepInEx,
650  Umm,
651}
652
653/// Builds Doorstop arguments for BepInEx or UMM, using the flag spellings of the
654/// version detected in the target.
655///
656/// Unlike r2modman, the *vanilla* flag matches the detected version too (r2modman
657/// emits the v3 spelling even under v4).
658///
659/// `script_injected` overrides that version match: when this argv is headed for
660/// the loader script (`run_bepinex.sh` / `start_game_bepinex.sh` /
661/// `start_server_bepinex.sh`) rather than straight to Doorstop's own
662/// command-line parser, the v4 spellings are used unconditionally, regardless
663/// of what `.doorstop_version` says. That script is a Doorstop-v4-style front
664/// end no matter which Doorstop generation it wraps: verified against BepInEx's
665/// source, it recognizes only the v4 flags (`--doorstop-enabled`,
666/// `--doorstop-target-assembly`, `--doorstop-mono-dll-search-path-override`,
667/// …) and silently drops the v3 spellings (`--doorstop-enable`,
668/// `--doorstop-target`, `--doorstop-dll-search-override`) as unmatched
669/// passthrough arguments before `exec`-ing the game. Keeping the version-matched
670/// v3 spelling here for a v3-detected target would leave the script's own
671/// `enabled` default (`"1"`) in effect and its own default target assembly
672/// unset by us — silently launching modded when vanilla was requested, and the
673/// wrong assembly when modded was requested. This exception does not apply
674/// off the script path (Windows, Proton, or a Linux native direct-exe launch),
675/// where the version match above is intentional and must be preserved.
676fn doorstop_args(
677  target_dir: &Path,
678  facts: &LaunchFacts,
679  profile: &GameProfile,
680  ctx: &LaunchContext,
681  target: DoorstopTarget,
682  script_injected: bool,
683) -> Result<Vec<String>> {
684  let v4 = script_injected || facts.doorstop_version >= 4;
685
686  let (enable_flag, target_flag, search_flag) = if v4 {
687    (
688      "--doorstop-enabled",
689      "--doorstop-target-assembly",
690      "--doorstop-mono-dll-search-path-override",
691    )
692  } else {
693    (
694      "--doorstop-enable",
695      "--doorstop-target",
696      "--doorstop-dll-search-override",
697    )
698  };
699
700  if ctx.mode == LaunchMode::Vanilla {
701    return Ok(vec![enable_flag.to_string(), "false".to_string()]);
702  }
703
704  let assembly = match target {
705    DoorstopTarget::BepInEx => {
706      render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?
707    }
708    DoorstopTarget::Umm => arg_path(target_dir, "UMM/Core/UnityModManager.dll"),
709  };
710
711  let mut args = vec![
712    enable_flag.to_string(),
713    "true".to_string(),
714    target_flag.to_string(),
715    assembly,
716  ];
717
718  if target == DoorstopTarget::BepInEx && profile.instance_type == InstanceType::Server {
719    args.push("--server".to_string());
720  }
721
722  if facts.has_corlibs {
723    args.push(search_flag.to_string());
724    args.push(arg_path(target_dir, "unstripped_corlib"));
725  }
726
727  Ok(args)
728}
729
730/// BepisLoader (Resonite): a hookfxr hook plus a hardcoded Doorstop v4 target.
731fn bepis_args(
732  target_dir: &Path,
733  facts: &LaunchFacts,
734  profile: &GameProfile,
735  ctx: &LaunchContext,
736) -> Result<Vec<String>> {
737  if ctx.mode == LaunchMode::Vanilla {
738    return Ok(vec![
739      "--hookfxr-disable".to_string(),
740      "--doorstop-enabled".to_string(),
741      "false".to_string(),
742    ]);
743  }
744
745  let mut args = vec![
746    "--hookfxr-enable".to_string(),
747    "--bepinex-target".to_string(),
748    arg_path(target_dir, "BepInEx"),
749    "--doorstop-enabled".to_string(),
750    "true".to_string(),
751    "--doorstop-target-assembly".to_string(),
752    render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?,
753  ];
754
755  if profile.instance_type == InstanceType::Server {
756    args.push("--server".to_string());
757  }
758
759  if facts.has_corlibs {
760    args.push("--doorstop-mono-dll-search-path-override".to_string());
761    args.push(arg_path(target_dir, "unstripped_corlib"));
762  }
763
764  Ok(args)
765}
766
767/// MelonLoader: point it at the target, and ask it to regenerate its assembly
768/// cache when neither the ML 0.5 nor the ML 0.6 assembly layout is present.
769fn melonloader_args(facts: &LaunchFacts, ctx: &LaunchContext, target: &str) -> Vec<String> {
770  if ctx.mode == LaunchMode::Vanilla {
771    return vec!["--no-mods".to_string()];
772  }
773
774  let mut args = vec!["--melonloader.basedir".to_string(), target.to_string()];
775
776  if !facts.melonloader_assemblies {
777    args.push("--melonloader.agfregenerate".to_string());
778  }
779
780  args
781}
782
783/// The Wine proxy DLL a loader hooks through under Proton.
784pub fn proxy_dll(loader: LoaderKind) -> &'static str {
785  match loader {
786    LoaderKind::GdWeave => "winmm",
787    _ => "winhttp",
788  }
789}
790
791/// Whether this launch injects through a loader script, and which one.
792///
793/// The single fact both `resolve_program` and [`stage_for_launch_in`] decide
794/// from, so a plan can never assume script injection while staging assumes the
795/// proxy-DLL path, or the reverse.
796#[derive(Debug, Clone, PartialEq, Eq)]
797enum ScriptInjection {
798  /// Not a script-injected combination: the proxy DLL beside the executable does
799  /// the injecting, and staging must put it there.
800  NotApplicable,
801  /// Script injection applies and the target ships this script.
802  Found(PathBuf),
803  /// Script injection applies but the target ships none of the scripts looked for.
804  Missing,
805}
806
807impl ScriptInjection {
808  /// Whether script injection applies at all — true even for [`Self::Missing`],
809  /// because a Linux native script-injected launch never wants proxy files copied
810  /// into its game directory regardless of which scripts the target happens to
811  /// ship.
812  fn applies(&self) -> bool {
813    !matches!(self, Self::NotApplicable)
814  }
815}
816
817/// The scripts to look for, in precedence order, for this profile's instance type.
818fn script_candidates(profile: &GameProfile) -> Vec<&'static str> {
819  match profile.instance_type {
820    InstanceType::Server => LOADER_SCRIPTS.to_vec(),
821    _ => LOADER_SCRIPTS
822      .iter()
823      .copied()
824      .filter(|name| *name != SERVER_SCRIPT)
825      .collect(),
826  }
827}
828
829/// Resolves whether this loader injects through a shell script the package ships
830/// into the target, rather than through a proxy DLL next to the executable, and
831/// which script that is.
832///
833/// The store is deliberately *not* part of this decision: under Steam the same
834/// script is chainloaded, just by the wrapper Steam invokes rather than by the
835/// caller (see [`SteamWrapper`]).
836fn script_injection(
837  target_dir: &Path,
838  facts: &LaunchFacts,
839  profile: &GameProfile,
840  ctx: &LaunchContext,
841) -> ScriptInjection {
842  if !script_injection_applies(profile, ctx) {
843    return ScriptInjection::NotApplicable;
844  }
845
846  let found = script_candidates(profile)
847    .into_iter()
848    .find(|name| facts.loader_scripts.iter().any(|present| present == name));
849
850  match found {
851    Some(name) => ScriptInjection::Found(target_dir.join(name)),
852    None => ScriptInjection::Missing,
853  }
854}
855
856/// Whether this loader, host, and runtime inject through a loader script at all,
857/// whichever scripts the target ships.
858fn script_injection_applies(profile: &GameProfile, ctx: &LaunchContext) -> bool {
859  let script_loader = matches!(
860    profile.package_loader,
861    LoaderKind::BepInEx | LoaderKind::BepisLoader
862  );
863
864  script_loader && ctx.os == HostOs::Linux && ctx.runtime == Runtime::Native
865}
866
867/// Whether `doorstop_args` must use the v4 flag spellings unconditionally
868/// because a loader script — not Doorstop's own parser — is what will read
869/// this argv. See `doorstop_args`'s doc comment for why that overrides the
870/// version match.
871///
872/// `false` for [`ScriptInjection::Missing`] as well as [`ScriptInjection::NotApplicable`]:
873/// when the target ships none of [`LOADER_SCRIPTS`], the argv reaches the game
874/// (or, under Steam, the wrapper's `exec "$@"` fallthrough) directly, so the
875/// version-matched spelling is the correct one there too.
876fn is_script_injected(
877  target_dir: &Path,
878  facts: &LaunchFacts,
879  profile: &GameProfile,
880  ctx: &LaunchContext,
881) -> bool {
882  matches!(
883    script_injection(target_dir, facts, profile, ctx),
884    ScriptInjection::Found(_)
885  )
886}
887
888/// Computes the launch invocation for `target_dir`.
889///
890/// The caller supplies the platform facts in `ctx` and spawns the returned
891/// [`LaunchPlan`]; the engine neither detects the host nor starts a process.
892///
893/// A Linux native Steam launch cannot be expressed by [`LaunchPlan::program`]
894/// alone — that plan carries a [`LaunchPlan::steam_wrapper`] the user must install
895/// into Steam's launch options first, and the caller need not re-derive when.
896/// Whenever that field is populated, [`wrapper_target_args`] is already appended
897/// to [`LaunchPlan::args`], so the once-pasted wrapper resolves this call's
898/// `target_dir` and not whichever one was current when it was written.
899///
900/// Under [`LaunchMode::Modded`], a combination that injects through a loader script
901/// whose target ships none of [`LOADER_SCRIPTS`] is an error, not a silent
902/// fallthrough to a proxy-DLL plan that would launch the game unmodded.
903///
904/// macOS is not supported: r2modman injects through a compiled proxy binary with
905/// no available source, so a correct plan cannot be computed (see the design
906/// spec's non-goals).
907///
908/// # Errors
909///
910/// - [`Error::UnknownGame`] or [`Error::NoGameProfile`] if `eco` has no
911///   profile for `game`.
912/// - [`Error::Profile`] if `ctx.os` is [`HostOs::MacOs`], or if a
913///   [`LaunchMode::Modded`] plan needs a loader script that `target_dir` does
914///   not contain.
915///
916/// # Examples
917///
918/// The engine computes the invocation; the caller spawns it:
919///
920/// ```no_run
921/// use std::path::Path;
922/// use std::process::Command;
923/// use thunderstore_engine::ecosystem::Ecosystem;
924/// use thunderstore_engine::profile::launch::{
925///   HostOs, LaunchContext, LaunchMode, Runtime, StorePlatform, launch_plan_in,
926/// };
927///
928/// let eco = Ecosystem::bundled();
929///
930/// let ctx = LaunchContext::new(
931///   HostOs::Linux,
932///   StorePlatform::SteamDirect,
933///   Runtime::Proton,
934///   LaunchMode::Modded,
935/// );
936///
937/// let plan = launch_plan_in(Path::new("/games/valheim/profile"), &eco, "valheim", &ctx)?;
938///
939/// let mut command = plan.to_command(Path::new("/games/valheim"))?;
940///
941/// command.spawn()?;
942/// # Ok::<(), thunderstore_engine::Error>(())
943/// ```
944///
945/// Reads the target's [`LaunchFacts`] and computes with [`launch_plan_from`].
946#[cfg(feature = "io")]
947pub fn launch_plan_in(
948  target_dir: &Path,
949  eco: &Ecosystem,
950  game: &str,
951  ctx: &LaunchContext,
952) -> Result<LaunchPlan> {
953  launch_plan_from(target_dir, &LaunchFacts::read(target_dir), eco, game, ctx)
954}
955
956/// Computes the launch invocation for `target_dir` from `facts` about its
957/// contents, without touching disk.
958///
959/// The rules and errors are `launch_plan_in`'s; this only takes the target's
960/// contents as [`LaunchFacts`] instead of reading them. `target_dir` is used only
961/// to render paths into the plan.
962///
963/// # Examples
964///
965/// ```
966/// use std::path::Path;
967/// use thunderstore_engine::ecosystem::Ecosystem;
968/// use thunderstore_engine::profile::launch::{
969///   HostOs, LaunchContext, LaunchFacts, LaunchMode, LaunchProgram, Runtime, StorePlatform,
970///   launch_plan_from,
971/// };
972///
973/// let eco = Ecosystem::bundled();
974/// let ctx = LaunchContext::new(
975///   HostOs::Windows,
976///   StorePlatform::SteamDirect,
977///   Runtime::Native,
978///   LaunchMode::Modded,
979/// );
980/// let mut facts = LaunchFacts::default();
981///
982/// facts.preloader = Some("BepInEx.Preloader.dll".to_string());
983///
984/// let plan = launch_plan_from(Path::new("C:/profiles/main"), &facts, &eco, "valheim", &ctx)?;
985///
986/// assert!(matches!(plan.program, LaunchProgram::GameExe { .. }));
987/// assert!(plan.args.contains(&"C:/profiles/main/BepInEx/core/BepInEx.Preloader.dll".to_string()));
988/// # Ok::<(), thunderstore_engine::Error>(())
989/// ```
990pub fn launch_plan_from(
991  target_dir: &Path,
992  facts: &LaunchFacts,
993  eco: &Ecosystem,
994  game: &str,
995  ctx: &LaunchContext,
996) -> Result<LaunchPlan> {
997  if ctx.os == HostOs::MacOs {
998    return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
999  }
1000
1001  let profile = eco.require_profile(game)?;
1002
1003  // Computed before the argv so the loader-script decision is available for
1004  // `loader_args_from` to fold into its Doorstop flag spellings (see
1005  // `is_script_injected`), not just for `resolve_program` below.
1006  let injection = script_injection(target_dir, facts, profile, ctx);
1007  let mut args = loader_args_from(target_dir, facts, profile, ctx)?;
1008
1009  args.extend(ctx.extra_args.iter().cloned());
1010
1011  let program = resolve_program(&injection, target_dir, profile, ctx)?;
1012  let needs_wrapper = injection.applies() && ctx.store == StorePlatform::Steam;
1013
1014  // The wrapper is written once and never rewritten, so it learns its target from
1015  // this argv rather than from its own contents. Appending here — rather than
1016  // documenting that the caller must — is what keeps a stale paste in Steam's
1017  // launch options from silently launching the previous target's mods.
1018  if needs_wrapper {
1019    args.extend(wrapper_target_args(target_dir));
1020  }
1021
1022  let steam_wrapper = needs_wrapper.then(|| SteamWrapper {
1023    target_dir: target_dir.to_path_buf(),
1024    loader: profile.package_loader,
1025  });
1026
1027  let mut env = Vec::new();
1028
1029  if ctx.runtime == Runtime::Proton {
1030    env.push((
1031      "WINEDLLOVERRIDES".to_string(),
1032      format!("{}=n,b", proxy_dll(profile.package_loader)),
1033    ));
1034  }
1035
1036  Ok(LaunchPlan {
1037    program,
1038    args,
1039    env,
1040    working_dir: None,
1041    steam_wrapper,
1042  })
1043}
1044
1045/// Chooses what process to start for this store/platform combination.
1046///
1047/// Under Steam the loader script is not started directly even when one is present:
1048/// Steam's launch options are a fixed `%command%` string, so the wrapper script
1049/// reported through [`LaunchPlan::steam_wrapper`] is what chainloads it.
1050fn resolve_program(
1051  injection: &ScriptInjection,
1052  target_dir: &Path,
1053  profile: &GameProfile,
1054  ctx: &LaunchContext,
1055) -> Result<LaunchProgram> {
1056  if *injection == ScriptInjection::Missing && ctx.mode == LaunchMode::Modded {
1057    return Err(Error::Profile(format!(
1058      "modded launch injects through a loader script, but none of {} exist in {}",
1059      script_candidates(profile).join(", "),
1060      target_dir.display(),
1061    )));
1062  }
1063
1064  if let ScriptInjection::Found(path) = injection
1065    && ctx.store != StorePlatform::Steam
1066  {
1067    return Ok(LaunchProgram::ProfileScript {
1068      path: path.clone(),
1069      exe_names: profile.exe_names.clone(),
1070    });
1071  }
1072
1073  if ctx.store == StorePlatform::Steam {
1074    let steam_app_id = profile.steam_app_id().ok_or_else(|| {
1075      Error::Profile("Steam launch requested but the game has no Steam app id".to_string())
1076    })?;
1077
1078    return Ok(LaunchProgram::Steam { steam_app_id });
1079  }
1080
1081  Ok(LaunchProgram::GameExe {
1082    exe_names: profile.exe_names.clone(),
1083  })
1084}
1085
1086/// Computes the launch invocation for an r2modman-layout profile.
1087/// See [`launch_plan_in`].
1088#[cfg(feature = "io")]
1089pub fn launch_plan(
1090  base: &Path,
1091  game: &str,
1092  profile_name: &str,
1093  eco: &Ecosystem,
1094  ctx: &LaunchContext,
1095) -> Result<LaunchPlan> {
1096  launch_plan_in(
1097    &crate::profile::layout::profile_dir(base, game, profile_name),
1098    eco,
1099    game,
1100    ctx,
1101  )
1102}
1103
1104/// The flag that tells a generated wrapper which target directory to chainload.
1105///
1106/// Appended, with the target directory after it, to the argv a caller sends
1107/// through Steam — see [`wrapper_target_args`]. The wrapper consumes both words
1108/// and forwards everything else untouched, so the game never sees this flag.
1109pub const WRAPPER_TARGET_FLAG: &str = "--ts-target";
1110
1111/// The arguments that make a generated wrapper chainload `target_dir`.
1112///
1113/// [`launch_plan_in`] already appends these to [`LaunchPlan::args`] whenever it
1114/// populates [`LaunchPlan::steam_wrapper`], so a caller spawning a computed plan
1115/// never needs to call this itself. It is public for callers assembling an argv
1116/// by hand, and for tests.
1117pub fn wrapper_target_args(target_dir: &Path) -> Vec<String> {
1118  vec![
1119    WRAPPER_TARGET_FLAG.to_string(),
1120    target_dir.to_string_lossy().replace('\\', "/"),
1121  ]
1122}
1123
1124/// Builds the POSIX shell wrapper that Steam invokes on Linux native launches.
1125///
1126/// Steam launch options are a single fixed `%command%` string, so a file must sit
1127/// between Steam and the game. Steam also stores exactly **one** such string per
1128/// game, so this script is written once and must stay correct for every target
1129/// afterwards. It therefore carries no target of its own — nothing about it is
1130/// specific to a profile, which is why it never needs regenerating:
1131///
1132/// - `--ts-target <dir>` ([`WRAPPER_TARGET_FLAG`]) anywhere in the argv Steam
1133///   forwards selects that directory. [`launch_plan_in`] appends it for the
1134///   caller, so switching targets needs no change to the script or to Steam.
1135/// - Absent that flag — a bare launch straight from Steam, with no manager
1136///   involved — the game starts **unmodded**. There is no default profile: a
1137///   wrapper that quietly loaded one would make "launch from Steam" mean
1138///   whichever target happened to be baked in, which is the ambiguity this whole
1139///   mechanism exists to remove. A value that names something other than a
1140///   directory is likewise treated as no target at all rather than chainloaded
1141///   blindly, so a deleted profile yields a vanilla launch, not a broken one.
1142///
1143/// This matches r2modman's `linux_wrapper.sh` — which reads `--r2profile` from
1144/// argv and launches vanilla without it — with one deliberate difference: it
1145/// passes a profile *name* and rebuilds `<root>/profiles/<name>`, assuming the
1146/// r2modman layout, whereas this takes a resolved absolute directory and so also
1147/// serves a bare target such as a dedicated server's game directory.
1148///
1149/// The flag and its value are consumed here, never forwarded; every other
1150/// argument reaches the loader script in its original order, quoted, so a target
1151/// or game argument containing spaces survives.
1152///
1153/// The branches are generated from [`LOADER_SCRIPTS`], the same list the resolver
1154/// behind [`launch_plan_in`] searches, so the wrapper and the plan cannot disagree
1155/// about which scripts count. Falls through to `exec "$@"` — a vanilla launch —
1156/// when the resolved target ships none of them.
1157pub fn wrapper_script_contents() -> String {
1158  let mut branches = String::new();
1159
1160  for (index, name) in LOADER_SCRIPTS.iter().enumerate() {
1161    let keyword = if index == 0 { "if" } else { "elif" };
1162    // The wrapper has no ecosystem profile at run time, so an env var stands in
1163    // for `InstanceType::Server`.
1164    let server_gate = if *name == SERVER_SCRIPT {
1165      r#" && [ -n "$TS_START_SERVER" ]"#
1166    } else {
1167      ""
1168    };
1169
1170    branches.push_str(&format!(
1171      "{keyword} [ -f \"$TARGET/{name}\" ]{server_gate}; then\n  exec \"$TARGET/{name}\" \"$@\"\n"
1172    ));
1173  }
1174
1175  // The loop rotates the positional parameters exactly `$#` times: each argument
1176  // is shifted off the front and, unless it is the flag or the flag's value,
1177  // appended to the back. `remaining` counts only the not-yet-inspected ones, so
1178  // already-appended arguments are never re-inspected and the surviving argv ends
1179  // up in its original order. This is the POSIX way to filter "$@" without
1180  // arrays and without `eval`.
1181  format!(
1182    r#"#!/bin/sh
1183# Generated by thunderstore-engine. Chainloads the mod loader for a target.
1184#
1185# Paste this into Steam's launch options once; it never needs regenerating, and
1186# it names no profile. The target directory is read from
1187# `{WRAPPER_TARGET_FLAG} <dir>` when a manager appends it to the launch
1188# arguments. Without it — launching straight from Steam — the game starts
1189# unmodded. The flag is consumed here and never reaches the game.
1190TARGET=""
1191
1192remaining=$#
1193
1194while [ "$remaining" -gt 0 ]; do
1195  argument="$1"
1196  shift
1197  remaining=$((remaining - 1))
1198
1199  if [ "$argument" = "{WRAPPER_TARGET_FLAG}" ]; then
1200    if [ "$remaining" -gt 0 ]; then
1201      candidate="$1"
1202      shift
1203      remaining=$((remaining - 1))
1204
1205      if [ -d "$candidate" ]; then
1206        TARGET="$candidate"
1207      fi
1208    fi
1209
1210    continue
1211  fi
1212
1213  set -- "$@" "$argument"
1214done
1215
1216if [ -z "$TARGET" ]; then
1217  exec "$@"
1218fi
1219
1220{branches}else
1221  exec "$@"
1222fi
1223"#
1224  )
1225}
1226
1227/// Writes the wrapper script to `script_path`, marking it executable on Unix (the
1228/// loader scripts fail to chainload otherwise).
1229///
1230/// The script names no target, so this is written once per game and never
1231/// rewritten — see [`wrapper_script_contents`].
1232#[cfg(feature = "io")]
1233pub fn write_wrapper_script(script_path: &Path) -> Result<()> {
1234  if let Some(parent) = script_path.parent() {
1235    std::fs::create_dir_all(parent)
1236      .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1237  }
1238
1239  std::fs::write(script_path, wrapper_script_contents())
1240    .map_err(|e| Error::Profile(format!("writing {}: {}", script_path.display(), e)))?;
1241
1242  #[cfg(unix)]
1243  {
1244    use std::os::unix::fs::PermissionsExt;
1245
1246    let permissions = std::fs::Permissions::from_mode(0o755);
1247
1248    std::fs::set_permissions(script_path, permissions)
1249      .map_err(|e| Error::Profile(format!("chmod {}: {}", script_path.display(), e)))?;
1250  }
1251
1252  Ok(())
1253}
1254
1255/// Marks every [`LOADER_SCRIPTS`] entry present in `target_dir` executable,
1256/// returning the paths whose mode this call actually changed.
1257///
1258/// Thunderstore loader packages ship these scripts **without** an execute bit:
1259/// `BepInExPack_Valheim` 5.4.2333 records `start_game_bepinex.sh` as `0666` in its
1260/// archive. Both [`LaunchProgram::ProfileScript`] and the wrapper from
1261/// [`wrapper_script_contents`] `exec` one of them directly, so without this that
1262/// `exec` fails with `Permission denied`, and under Steam that error reaches only
1263/// Steam's own console log: the launch presents to the user as the game silently
1264/// never starting. The bit therefore has to come from the manager, exactly as
1265/// r2modman sets it. Preserving the archive's recorded mode is no substitute,
1266/// because there is no execute bit in the archive to preserve.
1267///
1268/// Applied at launch time rather than at install time so a target that arrived by
1269/// any route is covered, whether that is a fresh install, an import, an export
1270/// round-trip, a restored backup, or one already on disk from an older version,
1271/// instead of only freshly installed ones. Kept out of [`launch_plan_in`], which
1272/// stays a pure computation, so the caller decides when the target is written to.
1273/// Keyed on the same [`LOADER_SCRIPTS`] list the plan and the wrapper both resolve
1274/// from, so all three agree about which files have to be runnable.
1275///
1276/// A script that is already executable is left untouched, so repeated launches do
1277/// not rewrite modes.
1278#[cfg(feature = "io")]
1279pub fn ensure_loader_scripts_executable(target_dir: &Path) -> Result<Vec<PathBuf>> {
1280  let mut changed = Vec::new();
1281
1282  for name in LOADER_SCRIPTS {
1283    let path = target_dir.join(name);
1284
1285    if !path.is_file() {
1286      continue;
1287    }
1288
1289    if make_executable(&path)? {
1290      changed.push(path);
1291    }
1292  }
1293
1294  Ok(changed)
1295}
1296
1297/// Grants the execute bit to exactly those classes that can already read `path`,
1298/// returning whether the mode changed. A no-op off Unix, where there is no such
1299/// bit to set.
1300///
1301/// Mirroring the read bits rather than forcing `0o755` keeps a deliberately
1302/// private script private: `0o640` becomes `0o750`, not world-readable. It can only
1303/// ever *add* execute bits, never widen read or write access.
1304#[cfg(feature = "io")]
1305fn make_executable(path: &Path) -> Result<bool> {
1306  #[cfg(unix)]
1307  {
1308    use std::os::unix::fs::PermissionsExt;
1309
1310    let metadata = std::fs::metadata(path)
1311      .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
1312    let mode = metadata.permissions().mode();
1313    let wanted = mode | ((mode & 0o444) >> 2);
1314
1315    if wanted == mode {
1316      return Ok(false);
1317    }
1318
1319    std::fs::set_permissions(path, std::fs::Permissions::from_mode(wanted))
1320      .map_err(|e| Error::Profile(format!("chmod {}: {}", path.display(), e)))?;
1321
1322    Ok(true)
1323  }
1324
1325  #[cfg(not(unix))]
1326  {
1327    let _ = path;
1328
1329    Ok(false)
1330  }
1331}
1332
1333/// Files Shimloader stages, and only these, into the UE binaries folder.
1334const SHIMLOADER_STAGED: [&str; 3] = ["ue4ss.dll", "dwmapi.dll", "ue4ss-settings.ini"];
1335
1336/// Where a profile-root file belongs in the game directory, or `None` when it is
1337/// not staged at all. Pure — no filesystem access.
1338pub fn stage_destination(
1339  loader: LoaderKind,
1340  file_name: &str,
1341  game_dir: &Path,
1342  data_folder: Option<&str>,
1343) -> Option<PathBuf> {
1344  let lowercased = file_name.to_ascii_lowercase();
1345
1346  if lowercased == "mods.yml" {
1347    return None;
1348  }
1349
1350  match loader {
1351    LoaderKind::Shimloader => {
1352      if !SHIMLOADER_STAGED.iter().any(|name| *name == lowercased) {
1353        return None;
1354      }
1355
1356      let data = data_folder?;
1357
1358      Some(
1359        game_dir
1360          .join(data)
1361          .join("Binaries")
1362          .join("Win64")
1363          .join(file_name),
1364      )
1365    }
1366    LoaderKind::Rivet => {
1367      if lowercased != "version.dll" {
1368        return None;
1369      }
1370
1371      Some(game_dir.join("Release").join(file_name))
1372    }
1373    _ => Some(game_dir.join(file_name)),
1374  }
1375}
1376
1377/// Copies the target's root-level loader files into `game_dir` so the proxy sits
1378/// beside the executable, returning the absolute paths written.
1379///
1380/// This is the only place the engine writes into a game directory, and it does so
1381/// only against an explicitly supplied `game_dir` — never one it discovered. Only
1382/// root-level *files* are staged; subdirectories (`BepInEx/`, `mods/`, …) stay in
1383/// the target, which is where the loader reads them from. Staging is skipped
1384/// entirely for a Linux native script-injected loader, whose game directory must
1385/// stay untouched.
1386///
1387/// `target_dir` and `game_dir` are frequently the same directory — a consumer
1388/// with no r2modman profile layout (e.g. one installing mods straight into the
1389/// game directory) always calls this with the two equal — and for most loaders
1390/// that makes a file's computed destination the exact file already sitting in
1391/// the target. `stage_one_file` detects that case by filesystem identity, not
1392/// path text, so it survives a `.`/`..`-relative `game_dir` or one reached
1393/// through a symlinked directory too, and leaves the file untouched rather than
1394/// copying it onto itself (which would truncate it to zero bytes). A file left
1395/// in place this way is **not** included in the returned `Vec<PathBuf>`: this
1396/// call did not write it, so reporting it as written would let a caller that
1397/// later deletes everything in that list destroy a file it never created. Note
1398/// that this per-file check is what actually matters — Shimloader routes into
1399/// `<game_dir>/<dataFolderName>/Binaries/Win64` and Rivet into
1400/// `<game_dir>/Release`, so even with `target_dir == game_dir` those
1401/// destinations genuinely differ from their sources and must still be copied.
1402///
1403/// A destination that is already a symlink is refused rather than followed, so a
1404/// pre-planted link cannot redirect a write outside `game_dir` (final path
1405/// component only, matching [`crate::install::apply_install`]) — including when
1406/// the symlink happens to point back at the source file itself; that refusal is
1407/// checked before the same-file identity check, so it always wins.
1408///
1409/// macOS is rejected here for the same reason [`launch_plan_in`] rejects it: no
1410/// correct launch can be computed for it, so the game directory must not be
1411/// touched on its behalf either.
1412///
1413/// This does not itself detect "nothing to stage": when `game_dir` does not
1414/// exist yet, listing it fails and that `read_dir` error is returned as is,
1415/// even for a loader whose destinations are identical to their sources. A
1416/// caller should check [`crate::profile::target::InstallTarget::needs_staging`]
1417/// first rather than rely on this function to turn that case into an empty
1418/// list.
1419#[cfg(feature = "io")]
1420pub fn stage_for_launch_in(
1421  target_dir: &Path,
1422  eco: &Ecosystem,
1423  game: &str,
1424  game_dir: &Path,
1425  ctx: &LaunchContext,
1426) -> Result<Vec<PathBuf>> {
1427  let staged = stage_files_in(target_dir, eco, game, game_dir, ctx)?;
1428  let mut written = staged.created;
1429
1430  written.extend(staged.replaced);
1431  written.sort();
1432
1433  Ok(written)
1434}
1435
1436/// [`stage_for_launch_in`], keeping files it created apart from files it
1437/// overwrote.
1438///
1439/// Files are staged in name order. When one fails, the files this call created
1440/// are removed before the error is returned, so a failed staging leaves no
1441/// new file behind; a file it had already overwritten keeps the new copy.
1442#[cfg(feature = "io")]
1443pub(crate) fn stage_files_in(
1444  target_dir: &Path,
1445  eco: &Ecosystem,
1446  game: &str,
1447  game_dir: &Path,
1448  ctx: &LaunchContext,
1449) -> Result<StagedFiles> {
1450  if ctx.os == HostOs::MacOs {
1451    return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
1452  }
1453
1454  let profile = eco.require_profile(game)?;
1455
1456  if script_injection_applies(profile, ctx) {
1457    return Ok(StagedFiles::default());
1458  }
1459
1460  let mut copies = Vec::new();
1461
1462  for entry in std::fs::read_dir(target_dir)
1463    .map_err(|e| Error::Profile(format!("reading {}: {}", target_dir.display(), e)))?
1464  {
1465    let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
1466    let metadata = std::fs::symlink_metadata(entry.path())
1467      .map_err(|e| Error::Profile(format!("inspecting {}: {}", entry.path().display(), e)))?;
1468
1469    if !metadata.is_file() {
1470      continue;
1471    }
1472
1473    let file_name = match entry.file_name().to_str() {
1474      Some(name) => name.to_string(),
1475      None => continue,
1476    };
1477
1478    let dest = match stage_destination(
1479      profile.package_loader,
1480      &file_name,
1481      game_dir,
1482      profile.data_folder_name.as_deref(),
1483    ) {
1484      Some(dest) => dest,
1485      None => continue,
1486    };
1487
1488    copies.push((entry.path(), dest));
1489  }
1490
1491  copies.sort();
1492
1493  let mut staged = StagedFiles::default();
1494
1495  for (source, dest) in copies {
1496    match stage_one_file(&source, &dest) {
1497      Ok(StagedFile::InPlace) => {}
1498      Ok(StagedFile::Created) => staged.created.push(dest),
1499      Ok(StagedFile::Replaced) => staged.replaced.push(dest),
1500      Err(error) => {
1501        for created in &staged.created {
1502          let _ = std::fs::remove_file(created);
1503        }
1504
1505        return Err(error);
1506      }
1507    }
1508  }
1509
1510  staged.created.sort();
1511  staged.replaced.sort();
1512
1513  Ok(staged)
1514}
1515
1516/// Stages an r2modman-layout profile's loader files into `game_dir`.
1517/// See [`stage_for_launch_in`].
1518#[cfg(feature = "io")]
1519pub fn stage_for_launch(
1520  base: &Path,
1521  game: &str,
1522  profile_name: &str,
1523  eco: &Ecosystem,
1524  game_dir: &Path,
1525  ctx: &LaunchContext,
1526) -> Result<Vec<PathBuf>> {
1527  stage_for_launch_in(
1528    &crate::profile::layout::profile_dir(base, game, profile_name),
1529    eco,
1530    game,
1531    game_dir,
1532    ctx,
1533  )
1534}
1535
1536/// Copies one staged file, creating parent directories and refusing to write
1537/// through a pre-existing symlink at the destination.
1538///
1539/// Returns what happened to `dest`: [`StagedFile::InPlace`] means `source` and
1540/// `dest` were already [`same_file`], so nothing was written.
1541/// [`stage_for_launch_in`] uses that to decide whether `dest` belongs in its
1542/// returned `Vec<PathBuf>`; see that function's doc comment for why an
1543/// already-in-place file must not be reported as written.
1544///
1545/// The symlink refusal is checked first and unconditionally, before the
1546/// same-file check: a destination symlink that happens to point at `source`
1547/// must still be refused rather than treated as "already in place", so a
1548/// pre-planted link can never be silently followed.
1549#[cfg(feature = "io")]
1550fn stage_one_file(source: &Path, dest: &Path) -> Result<StagedFile> {
1551  let existing = std::fs::symlink_metadata(dest).ok();
1552
1553  if existing
1554    .as_ref()
1555    .is_some_and(|metadata| metadata.file_type().is_symlink())
1556  {
1557    return Err(Error::Profile(format!(
1558      "refusing to stage through a symlink at {}",
1559      dest.display()
1560    )));
1561  }
1562
1563  if crate::util::same_file(source, dest) {
1564    return Ok(StagedFile::InPlace);
1565  }
1566
1567  if let Some(parent) = dest.parent() {
1568    std::fs::create_dir_all(parent)
1569      .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1570  }
1571
1572  std::fs::copy(source, dest)
1573    .map_err(|e| Error::Profile(format!("staging {}: {}", dest.display(), e)))?;
1574
1575  match existing {
1576    Some(_) => Ok(StagedFile::Replaced),
1577    None => Ok(StagedFile::Created),
1578  }
1579}
1580
1581/// What staging did to one destination.
1582#[cfg(feature = "io")]
1583enum StagedFile {
1584  /// The destination is the source itself, so nothing was written.
1585  InPlace,
1586  /// The destination did not exist and now holds a copy.
1587  Created,
1588  /// The destination already held a file, now overwritten with a copy.
1589  Replaced,
1590}
1591
1592/// The game-folder files one staging wrote, split by whether they existed
1593/// before it.
1594#[cfg(feature = "io")]
1595#[derive(Debug, Default)]
1596pub(crate) struct StagedFiles {
1597  /// Files this staging created.
1598  pub(crate) created: Vec<PathBuf>,
1599  /// Files that were already there and were overwritten.
1600  pub(crate) replaced: Vec<PathBuf>,
1601}
1602
1603/// The string a user pastes into Steam's launch options for a Linux native launch.
1604///
1605/// The engine only computes this: Steam stores launch options in `localconfig.vdf`,
1606/// which no manager writes (r2modman reads it to verify, never writes it), so
1607/// installing this is necessarily a user action.
1608///
1609/// This is the **Linux native** string, and only that, matching r2modman's
1610/// `WrapperArguments.ts` exactly. It carries no `WINEDLLOVERRIDES`: that is a Wine
1611/// setting, and no Wine is in this launch path. Nor could adding it buy Proton
1612/// coverage — what `script_path` names is a POSIX shell script, which is not a
1613/// valid `%command%` front end for a Windows binary in a Wine prefix regardless of
1614/// what environment variables precede it. A Proton launch cannot reach this
1615/// function anyway: [`LaunchPlan::steam_wrapper`] is populated only when
1616/// `script_injection` applies, which requires [`Runtime::Native`].
1617///
1618/// Under Proton the override *is* required — Wine prefers its own builtin
1619/// `winhttp` over the loader's, so the proxy never loads without it — but launch
1620/// options are the wrong channel for it. [`LaunchPlan::env`] carries it for the
1621/// direct-spawn path, and [`proxy_dll`] exposes the name for a caller writing it
1622/// into a prefix itself, as r2modman does via `user.reg`.
1623pub fn steam_launch_options(script_path: &Path) -> String {
1624  format!(
1625    r#""{script}" %command%"#,
1626    script = script_path.to_string_lossy().replace('\\', "/"),
1627  )
1628}
1629
1630/// The first of `exe_names` present in `game_dir`.
1631#[cfg(feature = "io")]
1632pub fn resolve_game_exe(game_dir: &Path, exe_names: &[String]) -> Result<PathBuf> {
1633  exe_names
1634    .iter()
1635    .map(|name| game_dir.join(name))
1636    .find(|candidate| candidate.is_file())
1637    .ok_or_else(|| {
1638      Error::Profile(format!(
1639        "no game executable found in {}: none of {} exist",
1640        game_dir.display(),
1641        exe_names.join(", ")
1642      ))
1643    })
1644}
1645
1646/// Where a game's Steam wrapper script is written.
1647///
1648/// One shared file for every target rather than one per profile: the script
1649/// resolves which directory to chainload from its argv at run time, and Steam
1650/// stores exactly one launch-options string per game naming this path. A
1651/// per-profile path would go stale the moment a user switched profiles.
1652pub fn wrapper_path(base: &Path, game: &str) -> PathBuf {
1653  base.join(game).join("steam-wrapper.sh")
1654}
1655
1656/// Builds the invocation that asks a running Steam client to start
1657/// `steam_app_id`.
1658///
1659/// Takes the program as a parameter rather than resolving it, so the argv this
1660/// produces can be asserted on any host — including one with no Steam installed,
1661/// which is every CI runner this crate is tested on.
1662///
1663/// Sets no environment: `steam -applaunch <id>` only messages an already-running
1664/// client, which starts the game with its own environment, so anything set here
1665/// would silently reach nothing. See [`LaunchPlan::env`].
1666#[cfg(feature = "io")]
1667fn steam_command(program: &Path, steam_app_id: u32) -> std::process::Command {
1668  let mut command = std::process::Command::new(program);
1669
1670  command.arg("-applaunch").arg(steam_app_id.to_string());
1671
1672  command
1673}
1674
1675#[cfg(feature = "io")]
1676impl LaunchPlan {
1677  /// Translates this plan into the process to spawn.
1678  ///
1679  /// Always an argv array, never a shell, so a path containing spaces or quotes
1680  /// cannot become an injection. Separate from spawning so the program,
1681  /// arguments, and environment can be asserted without starting anything.
1682  ///
1683  /// Every [`LaunchProgram`] variant is handled, with no wildcard arm.
1684  /// `LaunchProgram` is `#[non_exhaustive]`, but that only constrains other
1685  /// crates, so a wildcard here would be an unreachable pattern and fail
1686  /// `-D warnings`. Adding a variant therefore breaks this build deliberately,
1687  /// which is the point: a new launch shape must be translated, not silently
1688  /// rejected at run time.
1689  ///
1690  /// This is where the host is read, which is why the two variants that need a
1691  /// real path both resolve one here rather than in [`launch_plan_in`]: the plan
1692  /// stays a pure computation, and translating it into a process is the step
1693  /// allowed to look at the machine. [`LaunchProgram::GameExe`] and
1694  /// [`LaunchProgram::ProfileScript`] resolve their binary out of `game_dir`, and
1695  /// [`LaunchProgram::Steam`] resolves the Steam client through
1696  /// [`crate::steam::steam_exe`] — a bare `steam` resolves on Linux but never on
1697  /// Windows, whose Steam installer adds nothing to `PATH`.
1698  pub fn to_command(&self, game_dir: &Path) -> Result<std::process::Command> {
1699    let mut command = match &self.program {
1700      LaunchProgram::GameExe { exe_names } => {
1701        std::process::Command::new(resolve_game_exe(game_dir, exe_names)?)
1702      }
1703      LaunchProgram::Steam { steam_app_id } => {
1704        steam_command(&crate::steam::steam_exe(), *steam_app_id)
1705      }
1706      LaunchProgram::ProfileScript { path, exe_names } => {
1707        let mut command = std::process::Command::new(path);
1708
1709        command.arg(resolve_game_exe(game_dir, exe_names)?);
1710
1711        command
1712      }
1713    };
1714
1715    command.args(&self.args);
1716
1717    for (key, value) in &self.env {
1718      command.env(key, value);
1719    }
1720
1721    if let Some(dir) = &self.working_dir {
1722      command.current_dir(dir);
1723    }
1724
1725    Ok(command)
1726  }
1727}
1728
1729#[cfg(all(test, feature = "io"))]
1730mod tests {
1731  use super::*;
1732
1733  /// Asserts `options` is `script` quoted, then `%command%`. On Unix that is
1734  /// `script` exactly; on Windows it holds no `\` and names the same file.
1735  pub(super) fn assert_options_name_script(options: &str, script: &Path) {
1736    let quoted = options
1737      .strip_suffix(" %command%")
1738      .and_then(|rest| rest.strip_prefix('"'))
1739      .and_then(|rest| rest.strip_suffix('"'))
1740      .unwrap_or_else(|| panic!("not a quoted path then %command%: {options}"));
1741
1742    #[cfg(unix)]
1743    assert_eq!(quoted, script.to_str().unwrap());
1744
1745    #[cfg(not(unix))]
1746    {
1747      assert!(!quoted.contains('\\'), "{quoted}");
1748      assert_eq!(
1749        std::fs::canonicalize(quoted).unwrap(),
1750        std::fs::canonicalize(script).unwrap()
1751      );
1752    }
1753  }
1754
1755  #[test]
1756  fn doorstop_version_reads_major_and_defaults_to_three() {
1757    let dir = tempfile::tempdir().unwrap();
1758    let root = dir.path();
1759
1760    // Missing file => v3.
1761    assert_eq!(doorstop_version(root), 3);
1762
1763    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1764    assert_eq!(doorstop_version(root), 4);
1765
1766    std::fs::write(root.join(".doorstop_version"), "3.7.1").unwrap();
1767    assert_eq!(doorstop_version(root), 3);
1768
1769    // r2modman falls back to v3 for major >= 5; we treat it as v4 (its own bug).
1770    std::fs::write(root.join(".doorstop_version"), "5.1.0").unwrap();
1771    assert_eq!(doorstop_version(root), 5);
1772
1773    // Unparseable => v3.
1774    std::fs::write(root.join(".doorstop_version"), "garbage").unwrap();
1775    assert_eq!(doorstop_version(root), 3);
1776  }
1777
1778  #[test]
1779  fn bepinex_preloader_finds_candidate_and_prefixes_under_proton() {
1780    let dir = tempfile::tempdir().unwrap();
1781    let root = dir.path();
1782    let core = root.join("BepInEx/core");
1783
1784    std::fs::create_dir_all(&core).unwrap();
1785    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1786    std::fs::write(core.join("Unrelated.dll"), b"x").unwrap();
1787
1788    let native = bepinex_preloader(root, Runtime::Native).unwrap();
1789
1790    assert!(native.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1791    assert!(!native.starts_with("Z:"));
1792
1793    let proton = bepinex_preloader(root, Runtime::Proton).unwrap();
1794
1795    assert!(proton.starts_with("Z:"));
1796    assert!(proton.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1797  }
1798
1799  #[test]
1800  fn bepinex_preloader_errors_when_absent() {
1801    let dir = tempfile::tempdir().unwrap();
1802
1803    assert!(bepinex_preloader(dir.path(), Runtime::Native).is_err());
1804  }
1805
1806  #[test]
1807  fn has_corlibs_detects_the_directory() {
1808    let dir = tempfile::tempdir().unwrap();
1809    let root = dir.path();
1810
1811    assert!(!has_corlibs(root));
1812
1813    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
1814
1815    assert!(has_corlibs(root));
1816  }
1817
1818  fn ctx(mode: LaunchMode) -> LaunchContext {
1819    LaunchContext {
1820      os: HostOs::Windows,
1821      store: StorePlatform::Steam,
1822      runtime: Runtime::Native,
1823      mode,
1824      extra_args: Vec::new(),
1825    }
1826  }
1827
1828  fn profile_with(loader: LoaderKind) -> GameProfile {
1829    let eco = Ecosystem::bundled();
1830    let mut profile = eco.game("valheim").unwrap().profile().unwrap().clone();
1831    profile.package_loader = loader;
1832
1833    profile
1834  }
1835
1836  #[test]
1837  fn bepinex_v3_and_v4_use_the_right_flag_spellings() {
1838    let dir = tempfile::tempdir().unwrap();
1839    let root = dir.path();
1840    let core = root.join("BepInEx/core");
1841
1842    std::fs::create_dir_all(&core).unwrap();
1843    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1844
1845    let profile = profile_with(LoaderKind::BepInEx);
1846
1847    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1848
1849    assert_eq!(v3[0], "--doorstop-enable");
1850    assert_eq!(v3[1], "true");
1851    assert_eq!(v3[2], "--doorstop-target");
1852
1853    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1854
1855    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1856
1857    assert_eq!(v4[0], "--doorstop-enabled");
1858    assert_eq!(v4[2], "--doorstop-target-assembly");
1859
1860    // Vanilla uses the matching spelling for the detected version — r2modman
1861    // emits the v3 spelling here even on v4, which we deliberately correct.
1862    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
1863
1864    assert_eq!(
1865      vanilla,
1866      vec!["--doorstop-enabled".to_string(), "false".to_string()]
1867    );
1868  }
1869
1870  #[test]
1871  fn melonloader_adds_regenerate_only_when_assemblies_are_absent() {
1872    let dir = tempfile::tempdir().unwrap();
1873    let root = dir.path();
1874    let profile = profile_with(LoaderKind::MelonLoader);
1875
1876    let bare = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1877
1878    assert_eq!(bare[0], "--melonloader.basedir");
1879    assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
1880
1881    let managed = root.join("MelonLoader/Managed");
1882    std::fs::create_dir_all(&managed).unwrap();
1883    std::fs::write(managed.join("Assembly-CSharp.dll"), b"x").unwrap();
1884
1885    let with_assembly = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1886
1887    assert!(!with_assembly.contains(&"--melonloader.agfregenerate".to_string()));
1888    assert_eq!(
1889      loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap(),
1890      vec!["--no-mods".to_string()]
1891    );
1892  }
1893
1894  #[test]
1895  fn single_element_flags_stay_single_elements() {
1896    let dir = tempfile::tempdir().unwrap();
1897    let root = dir.path();
1898
1899    let gdweave = loader_args(
1900      root,
1901      &profile_with(LoaderKind::GdWeave),
1902      &ctx(LaunchMode::Modded),
1903    )
1904    .unwrap();
1905
1906    assert_eq!(gdweave.len(), 1);
1907    assert!(gdweave[0].starts_with("--gdweave-folder-override="));
1908    assert!(gdweave[0].ends_with("/GDWeave"));
1909
1910    let northstar = loader_args(
1911      root,
1912      &profile_with(LoaderKind::Northstar),
1913      &ctx(LaunchMode::Modded),
1914    )
1915    .unwrap();
1916
1917    assert_eq!(northstar[0], "-northstar");
1918    assert!(northstar[1].starts_with("-profile="));
1919  }
1920
1921  #[test]
1922  fn shimloader_and_rivet_and_rom_shapes() {
1923    let dir = tempfile::tempdir().unwrap();
1924    let root = dir.path();
1925
1926    let shim = loader_args(
1927      root,
1928      &profile_with(LoaderKind::Shimloader),
1929      &ctx(LaunchMode::Modded),
1930    )
1931    .unwrap();
1932
1933    assert_eq!(shim.len(), 8);
1934    assert_eq!(shim[0], "--mod-dir");
1935    assert!(shim.contains(&"--overlay-dir".to_string()));
1936
1937    let rivet = loader_args(
1938      root,
1939      &profile_with(LoaderKind::Rivet),
1940      &ctx(LaunchMode::Modded),
1941    )
1942    .unwrap();
1943
1944    assert_eq!(rivet[0], "-rivetEnable");
1945    assert_eq!(rivet[1], "true");
1946    assert!(rivet.contains(&"-rivetDirectory".to_string()));
1947    assert_eq!(
1948      loader_args(
1949        root,
1950        &profile_with(LoaderKind::Rivet),
1951        &ctx(LaunchMode::Vanilla)
1952      )
1953      .unwrap(),
1954      vec!["-rivetEnable".to_string(), "false".to_string()]
1955    );
1956
1957    let rom = loader_args(
1958      root,
1959      &profile_with(LoaderKind::ReturnOfModding),
1960      &ctx(LaunchMode::Modded),
1961    )
1962    .unwrap();
1963
1964    assert_eq!(rom[0], "--rom_modding_root_folder");
1965  }
1966
1967  #[test]
1968  fn unknown_and_none_loaders_produce_no_args() {
1969    let dir = tempfile::tempdir().unwrap();
1970    let root = dir.path();
1971
1972    assert!(
1973      loader_args(
1974        root,
1975        &profile_with(LoaderKind::None),
1976        &ctx(LaunchMode::Modded)
1977      )
1978      .unwrap()
1979      .is_empty()
1980    );
1981    assert!(
1982      loader_args(
1983        root,
1984        &profile_with(LoaderKind::Other),
1985        &ctx(LaunchMode::Modded)
1986      )
1987      .unwrap()
1988      .is_empty()
1989    );
1990  }
1991
1992  #[test]
1993  fn server_instance_appends_server_flag_for_bepinex() {
1994    let dir = tempfile::tempdir().unwrap();
1995    let root = dir.path();
1996    let core = root.join("BepInEx/core");
1997
1998    std::fs::create_dir_all(&core).unwrap();
1999    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2000
2001    let mut profile = profile_with(LoaderKind::BepInEx);
2002    profile.instance_type = InstanceType::Server;
2003
2004    let args = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2005
2006    assert!(args.contains(&"--server".to_string()));
2007  }
2008
2009  #[test]
2010  fn umm_uses_doorstop_flags_and_never_gets_server_flag() {
2011    let dir = tempfile::tempdir().unwrap();
2012    let root = dir.path();
2013    let profile = profile_with(LoaderKind::Umm);
2014
2015    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2016
2017    assert_eq!(v3[0], "--doorstop-enable");
2018    assert_eq!(v3[1], "true");
2019    assert_eq!(v3[2], "--doorstop-target");
2020    assert!(v3[3].ends_with("UMM/Core/UnityModManager.dll"));
2021
2022    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2023
2024    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2025
2026    assert_eq!(v4[0], "--doorstop-enabled");
2027    assert_eq!(v4[2], "--doorstop-target-assembly");
2028    assert!(v4[3].ends_with("UMM/Core/UnityModManager.dll"));
2029
2030    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2031
2032    assert_eq!(
2033      vanilla,
2034      vec!["--doorstop-enabled".to_string(), "false".to_string()]
2035    );
2036
2037    // Unlike BepInEx, UMM's `DoorstopTarget` arm never appends `--server`, even
2038    // when the profile's instance type is `Server`.
2039    let mut server_profile = profile_with(LoaderKind::Umm);
2040    server_profile.instance_type = InstanceType::Server;
2041
2042    let server_args = loader_args(root, &server_profile, &ctx(LaunchMode::Modded)).unwrap();
2043
2044    assert!(!server_args.contains(&"--server".to_string()));
2045  }
2046
2047  #[test]
2048  fn bepis_loader_modded_and_vanilla_shapes() {
2049    let dir = tempfile::tempdir().unwrap();
2050    let root = dir.path();
2051    let core = root.join("BepInEx/core");
2052
2053    std::fs::create_dir_all(&core).unwrap();
2054    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2055
2056    let profile = profile_with(LoaderKind::BepisLoader);
2057
2058    let modded = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2059
2060    assert_eq!(modded[0], "--hookfxr-enable");
2061    assert_eq!(modded[1], "--bepinex-target");
2062    assert!(modded.contains(&"--doorstop-enabled".to_string()));
2063    assert!(modded.contains(&"--doorstop-target-assembly".to_string()));
2064
2065    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2066
2067    assert_eq!(
2068      vanilla,
2069      vec![
2070        "--hookfxr-disable".to_string(),
2071        "--doorstop-enabled".to_string(),
2072        "false".to_string()
2073      ]
2074    );
2075  }
2076
2077  #[test]
2078  fn lovely_modded_and_vanilla_shapes() {
2079    let dir = tempfile::tempdir().unwrap();
2080    let root = dir.path();
2081
2082    let modded = loader_args(
2083      root,
2084      &profile_with(LoaderKind::Lovely),
2085      &ctx(LaunchMode::Modded),
2086    )
2087    .unwrap();
2088
2089    assert_eq!(modded[0], "--mod-dir");
2090    assert!(modded[1].ends_with("/mods"));
2091
2092    let vanilla = loader_args(
2093      root,
2094      &profile_with(LoaderKind::Lovely),
2095      &ctx(LaunchMode::Vanilla),
2096    )
2097    .unwrap();
2098
2099    assert_eq!(vanilla, vec!["--vanilla".to_string()]);
2100  }
2101
2102  #[test]
2103  fn godot_ml_modded_and_vanilla_shapes() {
2104    let dir = tempfile::tempdir().unwrap();
2105    let root = dir.path();
2106
2107    let modded = loader_args(
2108      root,
2109      &profile_with(LoaderKind::GodotMl),
2110      &ctx(LaunchMode::Modded),
2111    )
2112    .unwrap();
2113
2114    assert_eq!(modded[0], "--script");
2115    assert_eq!(modded[1], "res://addons/mod_loader/mod_loader_setup.gd");
2116    assert!(modded.contains(&"--mods-path".to_string()));
2117
2118    let vanilla = loader_args(
2119      root,
2120      &profile_with(LoaderKind::GodotMl),
2121      &ctx(LaunchMode::Vanilla),
2122    )
2123    .unwrap();
2124
2125    assert!(vanilla.is_empty());
2126  }
2127
2128  #[test]
2129  fn corlib_override_appends_search_flag_pair_matching_version() {
2130    let dir = tempfile::tempdir().unwrap();
2131    let root = dir.path();
2132    let core = root.join("BepInEx/core");
2133
2134    std::fs::create_dir_all(&core).unwrap();
2135    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2136    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
2137
2138    let profile = profile_with(LoaderKind::BepInEx);
2139
2140    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2141    let v3_idx = v3
2142      .iter()
2143      .position(|a| a == "--doorstop-dll-search-override")
2144      .unwrap();
2145
2146    assert!(v3[v3_idx + 1].ends_with("/unstripped_corlib"));
2147
2148    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2149
2150    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2151    let v4_idx = v4
2152      .iter()
2153      .position(|a| a == "--doorstop-mono-dll-search-path-override")
2154      .unwrap();
2155
2156    assert!(v4[v4_idx + 1].ends_with("/unstripped_corlib"));
2157
2158    // BepisLoader hardcodes the v4 search-flag spelling regardless of the
2159    // detected `.doorstop_version`.
2160    std::fs::remove_file(root.join(".doorstop_version")).unwrap();
2161
2162    let bepis = loader_args(
2163      root,
2164      &profile_with(LoaderKind::BepisLoader),
2165      &ctx(LaunchMode::Modded),
2166    )
2167    .unwrap();
2168    let bepis_idx = bepis
2169      .iter()
2170      .position(|a| a == "--doorstop-mono-dll-search-path-override")
2171      .unwrap();
2172
2173    assert!(bepis[bepis_idx + 1].ends_with("/unstripped_corlib"));
2174  }
2175
2176  #[test]
2177  fn windows_steam_plan_targets_steam_with_loader_args() {
2178    let dir = tempfile::tempdir().unwrap();
2179    let root = dir.path();
2180    let core = root.join("BepInEx/core");
2181
2182    std::fs::create_dir_all(&core).unwrap();
2183    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2184
2185    let eco = Ecosystem::bundled();
2186    let mut context = ctx(LaunchMode::Modded);
2187    context.extra_args = vec!["-nolog".to_string()];
2188
2189    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2190
2191    match &plan.program {
2192      LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
2193      other => panic!("expected Steam, got {other:?}"),
2194    }
2195
2196    assert_eq!(plan.args[0], "--doorstop-enable");
2197    // User args come last.
2198    assert_eq!(plan.args.last().unwrap(), "-nolog");
2199    assert!(plan.env.is_empty());
2200    // Windows injects through the proxy DLL, so Steam needs no wrapper file.
2201    assert_eq!(plan.steam_wrapper, None);
2202  }
2203
2204  #[test]
2205  fn proton_sets_wine_dll_overrides_and_prefixes_the_preloader() {
2206    let dir = tempfile::tempdir().unwrap();
2207    let root = dir.path();
2208    let core = root.join("BepInEx/core");
2209
2210    std::fs::create_dir_all(&core).unwrap();
2211    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2212
2213    let eco = Ecosystem::bundled();
2214    let mut context = ctx(LaunchMode::Modded);
2215    context.os = HostOs::Linux;
2216    context.runtime = Runtime::Proton;
2217
2218    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2219
2220    assert_eq!(
2221      plan.env,
2222      vec![("WINEDLLOVERRIDES".to_string(), "winhttp=n,b".to_string())]
2223    );
2224    assert!(plan.args.iter().any(|a| a.starts_with("Z:")));
2225    // Proton injects through the proxy DLL too: no script, so no wrapper.
2226    assert_eq!(plan.steam_wrapper, None);
2227  }
2228
2229  #[test]
2230  fn linux_native_bepinex_runs_the_profile_script() {
2231    let dir = tempfile::tempdir().unwrap();
2232    let root = dir.path();
2233    let core = root.join("BepInEx/core");
2234
2235    std::fs::create_dir_all(&core).unwrap();
2236    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2237    std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2238
2239    let eco = Ecosystem::bundled();
2240    let mut context = ctx(LaunchMode::Modded);
2241    context.os = HostOs::Linux;
2242    context.store = StorePlatform::SteamDirect;
2243    context.runtime = Runtime::Native;
2244
2245    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2246
2247    match &plan.program {
2248      // `exe_names` travels with the script: the caller execs the script *with*
2249      // the game binary, so it needs the same candidates `GameExe` hands over.
2250      LaunchProgram::ProfileScript { path, exe_names } => {
2251        assert!(path.ends_with("run_bepinex.sh"));
2252        assert_eq!(
2253          *exe_names,
2254          eco.game("valheim").unwrap().profile().unwrap().exe_names
2255        );
2256        assert!(!exe_names.is_empty());
2257      }
2258      other => panic!("expected ProfileScript, got {other:?}"),
2259    }
2260
2261    // A directly launched script is not the Steam wrapper case.
2262    assert_eq!(plan.steam_wrapper, None);
2263  }
2264
2265  #[test]
2266  fn macos_is_rejected() {
2267    let dir = tempfile::tempdir().unwrap();
2268    let root = dir.path();
2269    let core = root.join("BepInEx/core");
2270
2271    std::fs::create_dir_all(&core).unwrap();
2272    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2273
2274    let eco = Ecosystem::bundled();
2275    let mut context = ctx(LaunchMode::Modded);
2276    context.os = HostOs::MacOs;
2277
2278    let err = launch_plan_in(root, &eco, "valheim", &context).unwrap_err();
2279
2280    assert!(err.to_string().contains("macOS launch is not supported"));
2281
2282    // Control: the exact same directory and profile succeed once `os` is not
2283    // macOS, proving the error above comes from the macOS branch itself and
2284    // not, say, a missing BepInEx preloader fixture.
2285    context.os = HostOs::Windows;
2286
2287    assert!(launch_plan_in(root, &eco, "valheim", &context).is_ok());
2288  }
2289
2290  #[test]
2291  fn unknown_game_errors() {
2292    let dir = tempfile::tempdir().unwrap();
2293    let eco = Ecosystem::bundled();
2294
2295    let err = launch_plan_in(dir.path(), &eco, "not-a-game", &ctx(LaunchMode::Modded)).unwrap_err();
2296
2297    assert!(matches!(err, Error::UnknownGame { game } if game == "not-a-game"));
2298  }
2299
2300  #[test]
2301  fn proxy_dll_is_winmm_for_gdweave() {
2302    assert_eq!(proxy_dll(LoaderKind::GdWeave), "winmm");
2303    assert_eq!(proxy_dll(LoaderKind::BepInEx), "winhttp");
2304  }
2305
2306  #[test]
2307  fn wrapper_script_names_no_target_and_execs_the_loader() {
2308    let script = wrapper_script_contents();
2309
2310    assert!(script.starts_with("#!/bin/sh"));
2311
2312    // No target of any kind is baked in — that is what makes one script correct
2313    // for every profile, and what makes a bare launch unmodded rather than
2314    // whichever profile was current when it was written.
2315    assert!(script.contains(r#"TARGET="""#));
2316    assert!(script.contains(r#"[ -z "$TARGET" ]"#));
2317
2318    // The run-time flag is parsed, not `eval`-ed, and its value is only adopted
2319    // when it names a directory.
2320    assert!(script.contains(&format!(r#"[ "$argument" = "{WRAPPER_TARGET_FLAG}" ]"#)));
2321    assert!(script.contains(r#"[ -d "$candidate" ]"#));
2322    assert!(!script.contains("eval"));
2323
2324    // Verify all three branches are present in the correct order.
2325    let pos_server = script
2326      .find("start_server_bepinex.sh")
2327      .expect("server branch missing");
2328    let pos_run = script.find("run_bepinex.sh").expect("run branch missing");
2329    let pos_game = script
2330      .find("start_game_bepinex.sh")
2331      .expect("game branch missing");
2332
2333    assert!(pos_server < pos_run, "server branch must come before run");
2334    assert!(pos_run < pos_game, "run branch must come before game");
2335
2336    // The server branch must gate on TS_START_SERVER.
2337    assert!(script.contains("$TS_START_SERVER"));
2338
2339    // The script must have the else fallthrough and be well-formed.
2340    assert!(script.contains("else"));
2341    assert!(script.contains("fi"));
2342
2343    // The game command is forwarded, not swallowed.
2344    assert!(script.contains("\"$@\""));
2345  }
2346
2347  #[test]
2348  fn write_wrapper_script_creates_an_executable_file() {
2349    let dir = tempfile::tempdir().unwrap();
2350    let root = dir.path();
2351    let script_path = root.join("launch_wrapper.sh");
2352
2353    write_wrapper_script(&script_path).unwrap();
2354
2355    assert!(script_path.is_file());
2356
2357    #[cfg(unix)]
2358    {
2359      use std::os::unix::fs::PermissionsExt;
2360
2361      let mode = std::fs::metadata(&script_path)
2362        .unwrap()
2363        .permissions()
2364        .mode();
2365
2366      assert_eq!(mode & 0o111, 0o111);
2367    }
2368  }
2369
2370  /// The regression this exists for: a Thunderstore loader package ships its
2371  /// scripts non-executable, so a freshly installed profile cannot be launched at
2372  /// all until something sets the bit. Under Steam the failure is silent, so the
2373  /// only defense is that this runs before the wrapper `exec`s anything.
2374  #[test]
2375  #[cfg(unix)]
2376  fn ensure_loader_scripts_executable_adds_the_bit_and_reports_what_changed() {
2377    use std::os::unix::fs::PermissionsExt;
2378
2379    let dir = tempfile::tempdir().unwrap();
2380    let root = dir.path();
2381
2382    let game = root.join("start_game_bepinex.sh");
2383    let server = root.join("start_server_bepinex.sh");
2384
2385    std::fs::write(&game, b"#!/bin/sh\n").unwrap();
2386    std::fs::write(&server, b"#!/bin/sh\n").unwrap();
2387
2388    // Exactly what the package ships: readable, not executable.
2389    std::fs::set_permissions(&game, std::fs::Permissions::from_mode(0o644)).unwrap();
2390    std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o644)).unwrap();
2391
2392    let changed = ensure_loader_scripts_executable(root).unwrap();
2393
2394    assert_eq!(changed.len(), 2, "got: {changed:?}");
2395
2396    for name in ["start_game_bepinex.sh", "start_server_bepinex.sh"] {
2397      let mode = std::fs::metadata(root.join(name))
2398        .unwrap()
2399        .permissions()
2400        .mode();
2401
2402      assert_eq!(mode & 0o777, 0o755, "{name} got mode {mode:o}");
2403    }
2404
2405    // Idempotent: a second launch must not report a change, so repeated launches
2406    // do not keep rewriting modes.
2407    assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2408  }
2409
2410  /// Off Unix there is no execute bit, so a loader script is left alone and no
2411  /// change is reported for a launch to surface.
2412  #[test]
2413  #[cfg(not(unix))]
2414  fn ensure_loader_scripts_executable_changes_nothing_off_unix() {
2415    let dir = tempfile::tempdir().unwrap();
2416    let root = dir.path();
2417
2418    std::fs::write(root.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2419    std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2420
2421    assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2422  }
2423
2424  /// Read access is mirrored rather than forced to `0o755`, so a target whose
2425  /// scripts are deliberately owner-only does not become world-readable just to
2426  /// be launchable.
2427  #[test]
2428  #[cfg(unix)]
2429  fn ensure_loader_scripts_executable_mirrors_read_access() {
2430    use std::os::unix::fs::PermissionsExt;
2431
2432    let dir = tempfile::tempdir().unwrap();
2433    let root = dir.path();
2434    let script = root.join("run_bepinex.sh");
2435
2436    std::fs::write(&script, b"#!/bin/sh\n").unwrap();
2437    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o640)).unwrap();
2438
2439    ensure_loader_scripts_executable(root).unwrap();
2440
2441    let mode = std::fs::metadata(&script).unwrap().permissions().mode();
2442
2443    assert_eq!(mode & 0o777, 0o750, "got mode {mode:o}");
2444  }
2445
2446  /// A target with no loader scripts at all, such as a Proton profile or one
2447  /// whose loader injects through a proxy DLL, is not an error.
2448  #[test]
2449  fn ensure_loader_scripts_executable_ignores_a_target_with_no_scripts() {
2450    let dir = tempfile::tempdir().unwrap();
2451
2452    assert!(
2453      ensure_loader_scripts_executable(dir.path())
2454        .unwrap()
2455        .is_empty()
2456    );
2457  }
2458
2459  #[test]
2460  fn wrapper_target_args_name_the_flag_and_the_directory() {
2461    assert_eq!(
2462      wrapper_target_args(Path::new("/data/profiles/Main")),
2463      vec![
2464        WRAPPER_TARGET_FLAG.to_string(),
2465        "/data/profiles/Main".to_string()
2466      ]
2467    );
2468  }
2469
2470  // --- Executing the generated wrapper.
2471  //
2472  // The wrapper is a shell script, and the bugs that matter in one — a lost
2473  // quote, a flag leaking through to the game, an argument reordered by the
2474  // filtering loop — are invisible to assertions about its text. These tests run
2475  // `/bin/sh` against it for real and inspect the argv the chainloaded script
2476  // actually received. ---
2477
2478  /// Marks `path` executable, as [`write_wrapper_script`] does for the wrapper
2479  /// itself and as the loader scripts must be to be `exec`-ed.
2480  #[cfg(unix)]
2481  fn make_executable(path: &Path) {
2482    use std::os::unix::fs::PermissionsExt;
2483
2484    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2485  }
2486
2487  /// Writes a stand-in loader script at `path` that records the argv it was
2488  /// invoked with into `log`, one argument per line, prefixed by its own `$0`.
2489  ///
2490  /// One line per argument is what makes the assertions meaningful: a lost quote
2491  /// shows up as an argument split across two lines rather than as a string that
2492  /// merely looks similar.
2493  #[cfg(unix)]
2494  fn recording_loader(path: &Path, log: &Path) {
2495    let contents = format!(
2496      "#!/bin/sh\nprintf '%s\\n' \"$0\" > \"{log}\"\nfor argument in \"$@\"; do\n  printf '%s\\n' \"$argument\" >> \"{log}\"\ndone\n",
2497      log = log.display()
2498    );
2499
2500    std::fs::write(path, contents).unwrap();
2501    make_executable(path);
2502  }
2503
2504  /// The lines `recording_loader` wrote: the chainloaded script's own path, then
2505  /// each argument it received.
2506  #[cfg(unix)]
2507  fn recorded(log: &Path) -> Vec<String> {
2508    std::fs::read_to_string(log)
2509      .unwrap()
2510      .lines()
2511      .map(str::to_string)
2512      .collect()
2513  }
2514
2515  /// Runs `wrapper` with `args`, asserting it exited successfully.
2516  #[cfg(unix)]
2517  fn run_wrapper(wrapper: &Path, args: &[&str], server: bool) {
2518    let mut command = std::process::Command::new(wrapper);
2519
2520    command.args(args);
2521
2522    if server {
2523      command.env("TS_START_SERVER", "1");
2524    } else {
2525      command.env_remove("TS_START_SERVER");
2526    }
2527
2528    let output = command.output().unwrap();
2529
2530    assert!(
2531      output.status.success(),
2532      "wrapper failed: {}",
2533      String::from_utf8_lossy(&output.stderr)
2534    );
2535  }
2536
2537  #[cfg(unix)]
2538  #[test]
2539  fn wrapper_chainloads_the_target_given_at_run_time_and_consumes_only_the_flag() {
2540    let dir = tempfile::tempdir().unwrap();
2541    let fallback = dir.path().join("fallback");
2542    // A space in the target directory is the case that catches quoting bugs, and
2543    // it is a realistic profile name.
2544    let selected = dir.path().join("My Profile 2");
2545    let log = dir.path().join("argv.log");
2546    let wrapper = dir.path().join("steam-wrapper.sh");
2547
2548    std::fs::create_dir_all(&fallback).unwrap();
2549    std::fs::create_dir_all(&selected).unwrap();
2550    recording_loader(&selected.join("run_bepinex.sh"), &log);
2551    write_wrapper_script(&wrapper).unwrap();
2552
2553    let target = selected.to_string_lossy().to_string();
2554
2555    run_wrapper(
2556      &wrapper,
2557      &[
2558        "/games/valheim/valheim.x86_64",
2559        "--doorstop-enabled",
2560        "true",
2561        WRAPPER_TARGET_FLAG,
2562        &target,
2563        "-name",
2564        "a server with spaces",
2565      ],
2566      false,
2567    );
2568
2569    let lines = recorded(&log);
2570
2571    // The script inside the run-time target ran — not the fallback's.
2572    assert_eq!(lines[0], selected.join("run_bepinex.sh").to_string_lossy());
2573    // Every non-flag argument, in its original order, with spaces intact; the
2574    // flag and its value are gone.
2575    assert_eq!(
2576      &lines[1..],
2577      [
2578        "/games/valheim/valheim.x86_64",
2579        "--doorstop-enabled",
2580        "true",
2581        "-name",
2582        "a server with spaces",
2583      ]
2584    );
2585  }
2586
2587  #[cfg(unix)]
2588  #[test]
2589  fn wrapper_without_the_flag_launches_the_game_unmodded() {
2590    let dir = tempfile::tempdir().unwrap();
2591    let log = dir.path().join("argv.log");
2592    let wrapper = dir.path().join("steam-wrapper.sh");
2593    let game_exe = dir.path().join("valheim.x86_64");
2594    // A profile sitting right beside the wrapper, complete with a loader script.
2595    // Nothing may reach for it: no flag means no mods, not "whichever profile
2596    // happens to be there".
2597    let unrequested = dir.path().join("profile");
2598    let unrequested_log = dir.path().join("must-not-run.log");
2599
2600    std::fs::create_dir_all(&unrequested).unwrap();
2601    recording_loader(&unrequested.join("run_bepinex.sh"), &unrequested_log);
2602    recording_loader(&game_exe, &log);
2603    write_wrapper_script(&wrapper).unwrap();
2604
2605    // A launch straight from Steam, with no manager appending anything: exactly
2606    // what `%command%` expands to on its own.
2607    run_wrapper(&wrapper, &[&game_exe.to_string_lossy()], false);
2608
2609    assert!(
2610      !unrequested_log.exists(),
2611      "a bare launch must not load any profile's mods"
2612    );
2613
2614    let lines = recorded(&log);
2615
2616    assert_eq!(lines[0], game_exe.to_string_lossy());
2617    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2618  }
2619
2620  #[cfg(unix)]
2621  #[test]
2622  fn wrapper_launches_unmodded_when_the_flags_value_is_not_a_directory() {
2623    let dir = tempfile::tempdir().unwrap();
2624    let log = dir.path().join("argv.log");
2625    let wrapper = dir.path().join("steam-wrapper.sh");
2626    let game_exe = dir.path().join("valheim.x86_64");
2627
2628    recording_loader(&game_exe, &log);
2629    write_wrapper_script(&wrapper).unwrap();
2630
2631    // A profile deleted between the plan and the launch must not defeat the
2632    // launch, and must not be chainloaded as if it existed.
2633    let missing = dir.path().join("deleted-profile");
2634
2635    run_wrapper(
2636      &wrapper,
2637      &[
2638        &game_exe.to_string_lossy(),
2639        WRAPPER_TARGET_FLAG,
2640        &missing.to_string_lossy(),
2641      ],
2642      false,
2643    );
2644
2645    let lines = recorded(&log);
2646
2647    // The flag is consumed even when its value is rejected: the game must never
2648    // see it.
2649    assert_eq!(lines[0], game_exe.to_string_lossy());
2650    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2651  }
2652
2653  #[cfg(unix)]
2654  #[test]
2655  fn wrapper_consumes_a_trailing_flag_that_has_no_value() {
2656    let dir = tempfile::tempdir().unwrap();
2657    let log = dir.path().join("argv.log");
2658    let wrapper = dir.path().join("steam-wrapper.sh");
2659    let game_exe = dir.path().join("valheim.x86_64");
2660
2661    recording_loader(&game_exe, &log);
2662    write_wrapper_script(&wrapper).unwrap();
2663
2664    run_wrapper(
2665      &wrapper,
2666      &[&game_exe.to_string_lossy(), WRAPPER_TARGET_FLAG],
2667      false,
2668    );
2669
2670    let lines = recorded(&log);
2671
2672    // A valueless flag names no target, so this is a vanilla launch — and the
2673    // dangling flag is still swallowed rather than handed to the game.
2674    assert_eq!(lines[0], game_exe.to_string_lossy());
2675    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2676  }
2677
2678  #[cfg(unix)]
2679  #[test]
2680  fn wrapper_execs_the_game_directly_when_the_target_ships_no_loader_script() {
2681    let dir = tempfile::tempdir().unwrap();
2682    let selected = dir.path().join("profile");
2683    let log = dir.path().join("argv.log");
2684    let wrapper = dir.path().join("steam-wrapper.sh");
2685    // Stand in for the game binary Steam puts at the head of `%command%`.
2686    let game_exe = dir.path().join("valheim.x86_64");
2687
2688    std::fs::create_dir_all(&selected).unwrap();
2689    recording_loader(&game_exe, &log);
2690    write_wrapper_script(&wrapper).unwrap();
2691
2692    run_wrapper(
2693      &wrapper,
2694      &[
2695        &game_exe.to_string_lossy(),
2696        WRAPPER_TARGET_FLAG,
2697        &selected.to_string_lossy(),
2698        "-window-mode",
2699      ],
2700      false,
2701    );
2702
2703    let lines = recorded(&log);
2704
2705    // `exec "$@"` reached the game itself, and the flag still did not survive
2706    // into its argv.
2707    assert_eq!(lines[0], game_exe.to_string_lossy());
2708    assert_eq!(&lines[1..], ["-window-mode"]);
2709  }
2710
2711  #[cfg(unix)]
2712  #[test]
2713  fn wrapper_selects_the_server_script_only_when_ts_start_server_is_set() {
2714    let dir = tempfile::tempdir().unwrap();
2715    let target = dir.path().join("target");
2716    let server_log = dir.path().join("server.log");
2717    let game_log = dir.path().join("game.log");
2718    let wrapper = dir.path().join("steam-wrapper.sh");
2719
2720    std::fs::create_dir_all(&target).unwrap();
2721    // Both scripts present, which is the only way the gate is observable: the
2722    // server script has the higher precedence in `LOADER_SCRIPTS`, so without
2723    // the gate it would always win.
2724    recording_loader(&target.join(SERVER_SCRIPT), &server_log);
2725    recording_loader(&target.join("run_bepinex.sh"), &game_log);
2726    write_wrapper_script(&wrapper).unwrap();
2727
2728    let selected = target.to_string_lossy().to_string();
2729    let argv = [
2730      "/games/valheim/valheim.x86_64",
2731      WRAPPER_TARGET_FLAG,
2732      &selected,
2733    ];
2734
2735    run_wrapper(&wrapper, &argv, false);
2736
2737    assert!(
2738      !server_log.exists(),
2739      "the server script must not run for a game instance"
2740    );
2741    assert_eq!(
2742      recorded(&game_log)[0],
2743      target.join("run_bepinex.sh").to_string_lossy()
2744    );
2745
2746    run_wrapper(&wrapper, &argv, true);
2747
2748    assert_eq!(
2749      recorded(&server_log)[0],
2750      target.join(SERVER_SCRIPT).to_string_lossy()
2751    );
2752  }
2753
2754  #[test]
2755  fn steam_launch_options_are_only_the_wrapper_and_command_placeholder() {
2756    let options = steam_launch_options(Path::new("/data/launch_wrapper.sh"));
2757
2758    // Byte-for-byte what r2modman's `WrapperArguments.ts` emits: a quoted path
2759    // and `%command%`, and nothing else.
2760    assert_eq!(options, r#""/data/launch_wrapper.sh" %command%"#);
2761
2762    // No Wine setting rides along. This string is only ever produced for a Linux
2763    // native launch, where nothing in the path touches Wine, and it could not buy
2764    // Proton coverage anyway — see `steam_launch_options`'s doc comment.
2765    assert!(!options.contains("WINEDLLOVERRIDES"));
2766    assert!(!options.contains("winhttp"));
2767
2768    // A space in the script path stays inside the quotes.
2769    assert_eq!(
2770      steam_launch_options(Path::new("/data/My Games/wrapper.sh")),
2771      r#""/data/My Games/wrapper.sh" %command%"#
2772    );
2773
2774    // A Windows path is written with `/` separators.
2775    assert_eq!(
2776      steam_launch_options(Path::new(r"C:\Users\me\launch_wrapper.sh")),
2777      r#""C:/Users/me/launch_wrapper.sh" %command%"#
2778    );
2779  }
2780
2781  #[test]
2782  fn stage_destination_routes_per_loader() {
2783    let game = Path::new("/game");
2784
2785    assert_eq!(
2786      stage_destination(LoaderKind::BepInEx, "winhttp.dll", game, None),
2787      Some(PathBuf::from("/game/winhttp.dll"))
2788    );
2789    // mods.yml is manager state, never staged.
2790    assert_eq!(
2791      stage_destination(LoaderKind::BepInEx, "mods.yml", game, None),
2792      None
2793    );
2794
2795    // Shimloader: only its three files, into the UE binaries folder.
2796    assert_eq!(
2797      stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, Some("Palworld")),
2798      Some(PathBuf::from("/game/Palworld/Binaries/Win64/ue4ss.dll"))
2799    );
2800    assert_eq!(
2801      stage_destination(LoaderKind::Shimloader, "other.dll", game, Some("Palworld")),
2802      None
2803    );
2804    // No `dataFolderName` at all => nothing is staged.
2805    assert_eq!(
2806      stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, None),
2807      None
2808    );
2809
2810    // Rivet: only version.dll, into Release.
2811    assert_eq!(
2812      stage_destination(LoaderKind::Rivet, "version.dll", game, None),
2813      Some(PathBuf::from("/game/Release/version.dll"))
2814    );
2815    assert_eq!(
2816      stage_destination(LoaderKind::Rivet, "winhttp.dll", game, None),
2817      None
2818    );
2819  }
2820
2821  #[test]
2822  fn stage_for_launch_copies_root_files_only() {
2823    let dir = tempfile::tempdir().unwrap();
2824    let target = dir.path().join("target");
2825    let game_dir = dir.path().join("game");
2826
2827    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
2828    std::fs::create_dir_all(&game_dir).unwrap();
2829    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2830    std::fs::write(target.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
2831    std::fs::write(target.join("mods.yml"), b"[]").unwrap();
2832    std::fs::write(target.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
2833
2834    let eco = Ecosystem::bundled();
2835    let written = stage_for_launch_in(
2836      &target,
2837      &eco,
2838      "valheim",
2839      &game_dir,
2840      &ctx(LaunchMode::Modded),
2841    )
2842    .unwrap();
2843
2844    assert!(game_dir.join("winhttp.dll").exists());
2845    assert!(game_dir.join("doorstop_config.ini").exists());
2846    // Manager state and subdirectories are not staged.
2847    assert!(!game_dir.join("mods.yml").exists());
2848    assert!(!game_dir.join("BepInEx").exists());
2849    assert_eq!(written.len(), 2);
2850
2851    // The returned paths are exactly what was written, and sorted.
2852    assert!(written.contains(&game_dir.join("winhttp.dll")));
2853    assert!(written.contains(&game_dir.join("doorstop_config.ini")));
2854
2855    let mut sorted = written.clone();
2856    sorted.sort();
2857
2858    assert_eq!(written, sorted);
2859  }
2860
2861  #[test]
2862  fn stage_for_launch_stages_shimloader_files_into_nested_binaries_dir() {
2863    // Palworld is a bundled Shimloader game (`dataFolderName` = "Pal"), so this
2864    // exercises `stage_for_launch_in` end to end through a nested destination
2865    // that does not exist yet, forcing `stage_one_file`'s `create_dir_all`.
2866    let dir = tempfile::tempdir().unwrap();
2867    let target = dir.path().join("target");
2868    let game_dir = dir.path().join("game");
2869
2870    std::fs::create_dir_all(&target).unwrap();
2871    std::fs::create_dir_all(&game_dir).unwrap();
2872    std::fs::write(target.join("ue4ss.dll"), b"loader").unwrap();
2873    std::fs::write(target.join("dwmapi.dll"), b"proxy").unwrap();
2874    std::fs::write(target.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
2875    std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2876
2877    let eco = Ecosystem::bundled();
2878    let written = stage_for_launch_in(
2879      &target,
2880      &eco,
2881      "palworld",
2882      &game_dir,
2883      &ctx(LaunchMode::Modded),
2884    )
2885    .unwrap();
2886
2887    let nested = game_dir.join("Pal").join("Binaries").join("Win64");
2888
2889    assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
2890    assert!(nested.join("dwmapi.dll").exists());
2891    assert!(nested.join("ue4ss-settings.ini").exists());
2892    // Every other root file is skipped for Shimloader.
2893    assert!(!game_dir.join("other.dll").exists());
2894    assert!(!nested.join("other.dll").exists());
2895
2896    assert_eq!(written.len(), 3);
2897    assert!(written.contains(&nested.join("ue4ss.dll")));
2898    assert!(written.contains(&nested.join("dwmapi.dll")));
2899    assert!(written.contains(&nested.join("ue4ss-settings.ini")));
2900
2901    let mut sorted = written.clone();
2902    sorted.sort();
2903
2904    assert_eq!(written, sorted);
2905  }
2906
2907  #[test]
2908  fn stage_for_launch_stages_rivet_version_dll_into_release_dir() {
2909    // Scrap Mechanic is a bundled Rivet game, so this exercises
2910    // `stage_for_launch_in` end to end through the `<game>/Release` destination,
2911    // forcing `stage_one_file`'s `create_dir_all` for that nested directory too.
2912    let dir = tempfile::tempdir().unwrap();
2913    let target = dir.path().join("target");
2914    let game_dir = dir.path().join("game");
2915
2916    std::fs::create_dir_all(&target).unwrap();
2917    std::fs::create_dir_all(&game_dir).unwrap();
2918    std::fs::write(target.join("version.dll"), b"rivet-loader").unwrap();
2919    std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2920
2921    let eco = Ecosystem::bundled();
2922    let written = stage_for_launch_in(
2923      &target,
2924      &eco,
2925      "scrap-mechanic",
2926      &game_dir,
2927      &ctx(LaunchMode::Modded),
2928    )
2929    .unwrap();
2930
2931    let dest = game_dir.join("Release").join("version.dll");
2932
2933    assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
2934    // Every other root file is skipped for Rivet.
2935    assert!(!game_dir.join("other.dll").exists());
2936    assert!(!game_dir.join("Release").join("other.dll").exists());
2937
2938    assert_eq!(written, vec![dest]);
2939  }
2940
2941  #[test]
2942  fn stage_for_launch_skips_linux_native_bepinex() {
2943    let dir = tempfile::tempdir().unwrap();
2944    let target = dir.path().join("target");
2945    let game_dir = dir.path().join("game");
2946
2947    std::fs::create_dir_all(&target).unwrap();
2948    std::fs::create_dir_all(&game_dir).unwrap();
2949    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2950
2951    let eco = Ecosystem::bundled();
2952    let mut context = ctx(LaunchMode::Modded);
2953    context.os = HostOs::Linux;
2954    context.runtime = Runtime::Native;
2955
2956    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
2957
2958    assert!(written.is_empty());
2959    assert!(!game_dir.join("winhttp.dll").exists());
2960  }
2961
2962  #[cfg(unix)]
2963  #[test]
2964  fn stage_for_launch_refuses_to_write_through_a_symlink() {
2965    use std::os::unix::fs::symlink;
2966
2967    let dir = tempfile::tempdir().unwrap();
2968    let target = dir.path().join("target");
2969    let game_dir = dir.path().join("game");
2970    let outside = dir.path().join("secret.dll");
2971
2972    std::fs::create_dir_all(&target).unwrap();
2973    std::fs::create_dir_all(&game_dir).unwrap();
2974    std::fs::write(&outside, b"original").unwrap();
2975    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2976    symlink(&outside, game_dir.join("winhttp.dll")).unwrap();
2977
2978    let eco = Ecosystem::bundled();
2979
2980    assert!(
2981      stage_for_launch_in(
2982        &target,
2983        &eco,
2984        "valheim",
2985        &game_dir,
2986        &ctx(LaunchMode::Modded)
2987      )
2988      .is_err()
2989    );
2990    assert_eq!(std::fs::read(&outside).unwrap(), b"original");
2991  }
2992
2993  #[test]
2994  fn stage_for_launch_in_place_leaves_root_files_byte_for_byte_untouched() {
2995    // `target_dir == game_dir` is the layout a consumer with no r2modman
2996    // profile uses when it installs mods straight into the game directory
2997    // (see `stage_for_launch_in`'s doc comment). Before the fix, `stage_one_file`
2998    // called `std::fs::copy(path, path)` here, which truncates the destination
2999    // to zero bytes: `std::fs::copy` opens the destination with `O_TRUNC`
3000    // before it ever reads the source.
3001    let dir = tempfile::tempdir().unwrap();
3002    let root = dir.path().join("game");
3003
3004    std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
3005
3006    let winhttp_contents = b"MZ-fake-proxy-dll-18b";
3007    let ini_contents = b"[UnityDoorstop]\nenabled=true\n";
3008
3009    std::fs::write(root.join("winhttp.dll"), winhttp_contents).unwrap();
3010    std::fs::write(root.join("doorstop_config.ini"), ini_contents).unwrap();
3011    std::fs::write(root.join("mods.yml"), b"[]").unwrap();
3012    std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
3013
3014    let eco = Ecosystem::bundled();
3015    let written =
3016      stage_for_launch_in(&root, &eco, "valheim", &root, &ctx(LaunchMode::Modded)).unwrap();
3017
3018    // Contents, not mere existence — a zero-byte file still "exists", which is
3019    // precisely how the truncation bug hid behind every prior test.
3020    assert_eq!(
3021      std::fs::read(root.join("winhttp.dll")).unwrap(),
3022      winhttp_contents
3023    );
3024    assert_eq!(
3025      std::fs::read(root.join("doorstop_config.ini")).unwrap(),
3026      ini_contents
3027    );
3028
3029    // Neither file was actually written by this call — both were already
3030    // correctly in place — so neither is reported as written. See
3031    // `stage_for_launch_in`'s doc comment: over-reporting here would let a
3032    // caller that deletes everything in this list destroy a file it never
3033    // created.
3034    assert!(written.is_empty());
3035  }
3036
3037  #[test]
3038  fn stage_for_launch_in_place_survives_a_dot_dot_aliased_game_dir() {
3039    // `target/BepInEx/..` is not lexically equal to `target`, but resolves to
3040    // the exact same directory. The identity check must recognize this via
3041    // canonicalization rather than string comparison, or this differently
3042    // spelled `game_dir` would reintroduce the truncation bug.
3043    let dir = tempfile::tempdir().unwrap();
3044    let target = dir.path().join("target");
3045
3046    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3047
3048    let contents = b"proxy-bytes-not-truncated";
3049
3050    std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3051
3052    let aliased_game_dir = target.join("BepInEx").join("..");
3053    let eco = Ecosystem::bundled();
3054
3055    let written = stage_for_launch_in(
3056      &target,
3057      &eco,
3058      "valheim",
3059      &aliased_game_dir,
3060      &ctx(LaunchMode::Modded),
3061    )
3062    .unwrap();
3063
3064    assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3065    assert!(written.is_empty());
3066  }
3067
3068  #[cfg(unix)]
3069  #[test]
3070  fn stage_for_launch_in_place_survives_a_symlinked_game_dir() {
3071    use std::os::unix::fs::symlink;
3072
3073    // A `game_dir` reached through a symlinked directory must alias `target_dir`
3074    // exactly as the `..`-relative case above does, even though it is not
3075    // string-comparable to `target_dir` at all.
3076    let dir = tempfile::tempdir().unwrap();
3077    let target = dir.path().join("target");
3078    let link = dir.path().join("game-link");
3079
3080    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3081
3082    let contents = b"proxy-bytes-via-symlink";
3083
3084    std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3085    symlink(&target, &link).unwrap();
3086
3087    let eco = Ecosystem::bundled();
3088    let written =
3089      stage_for_launch_in(&target, &eco, "valheim", &link, &ctx(LaunchMode::Modded)).unwrap();
3090
3091    assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3092    assert!(written.is_empty());
3093  }
3094
3095  #[test]
3096  fn stage_for_launch_in_place_still_copies_shimloader_files_to_a_distinct_destination() {
3097    // Palworld is a bundled Shimloader game (`dataFolderName` = "Pal"). Even
3098    // with `target_dir == game_dir`, Shimloader's destination
3099    // (`<game_dir>/Pal/Binaries/Win64/<file>`) genuinely differs from its
3100    // source, so the identity check must not skip these — only a destination
3101    // identical to its source is exempted from copying.
3102    let dir = tempfile::tempdir().unwrap();
3103    let root = dir.path().join("game");
3104
3105    std::fs::create_dir_all(&root).unwrap();
3106    std::fs::write(root.join("ue4ss.dll"), b"loader").unwrap();
3107    std::fs::write(root.join("dwmapi.dll"), b"proxy").unwrap();
3108    std::fs::write(root.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
3109
3110    let eco = Ecosystem::bundled();
3111    let written =
3112      stage_for_launch_in(&root, &eco, "palworld", &root, &ctx(LaunchMode::Modded)).unwrap();
3113
3114    let nested = root.join("Pal").join("Binaries").join("Win64");
3115
3116    assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
3117    assert_eq!(std::fs::read(nested.join("dwmapi.dll")).unwrap(), b"proxy");
3118    // The source files are untouched by their own copy, and still present at
3119    // the target root (which is also `game_dir` here).
3120    assert_eq!(std::fs::read(root.join("ue4ss.dll")).unwrap(), b"loader");
3121
3122    assert_eq!(written.len(), 3);
3123    assert!(written.contains(&nested.join("ue4ss.dll")));
3124    assert!(written.contains(&nested.join("dwmapi.dll")));
3125    assert!(written.contains(&nested.join("ue4ss-settings.ini")));
3126  }
3127
3128  #[test]
3129  fn stage_for_launch_in_place_still_copies_rivet_version_dll_to_a_distinct_destination() {
3130    // Scrap Mechanic is a bundled Rivet game. Its destination
3131    // (`<game_dir>/Release/version.dll`) differs from its source even when
3132    // `target_dir == game_dir`, so it must still be copied rather than skipped.
3133    let dir = tempfile::tempdir().unwrap();
3134    let root = dir.path().join("game");
3135
3136    std::fs::create_dir_all(&root).unwrap();
3137    std::fs::write(root.join("version.dll"), b"rivet-loader").unwrap();
3138
3139    let eco = Ecosystem::bundled();
3140    let written = stage_for_launch_in(
3141      &root,
3142      &eco,
3143      "scrap-mechanic",
3144      &root,
3145      &ctx(LaunchMode::Modded),
3146    )
3147    .unwrap();
3148
3149    let dest = root.join("Release").join("version.dll");
3150
3151    assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3152    assert_eq!(
3153      std::fs::read(root.join("version.dll")).unwrap(),
3154      b"rivet-loader"
3155    );
3156    assert_eq!(written, vec![dest]);
3157  }
3158
3159  #[test]
3160  fn stage_for_launch_wraps_stage_for_launch_in_over_a_layout_profile() {
3161    let dir = tempfile::tempdir().unwrap();
3162    let base = dir.path().join("base");
3163    let game_dir = dir.path().join("game");
3164
3165    let profile_dir = crate::profile::layout::create(&base, "valheim", "Main").unwrap();
3166    let core = profile_dir.join("BepInEx/core");
3167
3168    std::fs::create_dir_all(&core).unwrap();
3169    std::fs::create_dir_all(&game_dir).unwrap();
3170    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3171    std::fs::write(profile_dir.join("winhttp.dll"), b"proxy").unwrap();
3172    std::fs::write(profile_dir.join("mods.yml"), b"[]").unwrap();
3173
3174    let eco = Ecosystem::bundled();
3175    let written = stage_for_launch(
3176      &base,
3177      "valheim",
3178      "Main",
3179      &eco,
3180      &game_dir,
3181      &ctx(LaunchMode::Modded),
3182    )
3183    .unwrap();
3184
3185    assert!(game_dir.join("winhttp.dll").exists());
3186    assert!(!game_dir.join("mods.yml").exists());
3187    assert_eq!(written, vec![game_dir.join("winhttp.dll")]);
3188  }
3189
3190  /// A Linux native `LaunchContext` for a directly executed (non-Steam) game.
3191  fn linux_native(mode: LaunchMode) -> LaunchContext {
3192    let mut context = ctx(mode);
3193
3194    context.os = HostOs::Linux;
3195    context.store = StorePlatform::SteamDirect;
3196    context.runtime = Runtime::Native;
3197
3198    context
3199  }
3200
3201  /// A target that looks like a real Linux BepInEx install, minus any loader
3202  /// script: preloader, proxy DLL, and Doorstop ini.
3203  fn linux_bepinex_target(root: &Path) {
3204    let core = root.join("BepInEx/core");
3205
3206    std::fs::create_dir_all(&core).unwrap();
3207    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3208    std::fs::write(root.join("winhttp.dll"), b"proxy").unwrap();
3209    std::fs::write(root.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
3210  }
3211
3212  #[test]
3213  fn linux_native_modded_selects_any_shipped_script_not_only_run_bepinex() {
3214    let dir = tempfile::tempdir().unwrap();
3215    let target = dir.path().join("target");
3216    let game_dir = dir.path().join("game");
3217
3218    linux_bepinex_target(&target);
3219    std::fs::create_dir_all(&game_dir).unwrap();
3220    // This package ships `start_game_bepinex.sh`; there is no `run_bepinex.sh`.
3221    std::fs::write(target.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3222
3223    let eco = Ecosystem::bundled();
3224    let context = linux_native(LaunchMode::Modded);
3225
3226    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3227
3228    match &plan.program {
3229      LaunchProgram::ProfileScript { path, .. } => {
3230        assert!(path.ends_with("start_game_bepinex.sh"))
3231      }
3232      // Falling through to `GameExe` here is the silent-vanilla bug: Doorstop
3233      // argv nothing reads, and no proxy staged into the game directory.
3234      other => panic!("expected ProfileScript, got {other:?}"),
3235    }
3236
3237    // Staging must agree with the plan rather than decide independently.
3238    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3239
3240    assert!(written.is_empty());
3241    assert!(!game_dir.join("winhttp.dll").exists());
3242  }
3243
3244  #[test]
3245  fn server_instance_prefers_the_server_script_and_a_game_instance_ignores_it() {
3246    let dir = tempfile::tempdir().unwrap();
3247    let all_three = dir.path().join("all-three");
3248    let server_only = dir.path().join("server-only");
3249
3250    linux_bepinex_target(&all_three);
3251    linux_bepinex_target(&server_only);
3252
3253    for name in LOADER_SCRIPTS {
3254      std::fs::write(all_three.join(name), b"#!/bin/sh\n").unwrap();
3255    }
3256
3257    std::fs::write(server_only.join(SERVER_SCRIPT), b"#!/bin/sh\n").unwrap();
3258
3259    let context = linux_native(LaunchMode::Modded);
3260    let game_profile = profile_with(LoaderKind::BepInEx);
3261    let mut server_profile = profile_with(LoaderKind::BepInEx);
3262
3263    server_profile.instance_type = InstanceType::Server;
3264
3265    let server = resolve_program(
3266      &script_injection(
3267        &all_three,
3268        &LaunchFacts::read(&all_three),
3269        &server_profile,
3270        &context,
3271      ),
3272      &all_three,
3273      &server_profile,
3274      &context,
3275    )
3276    .unwrap();
3277
3278    match &server {
3279      LaunchProgram::ProfileScript { path, .. } => {
3280        assert!(path.ends_with("start_server_bepinex.sh"))
3281      }
3282      other => panic!("expected ProfileScript, got {other:?}"),
3283    }
3284
3285    // A game instance skips the server script even when it is present and first
3286    // in precedence — exec'ing it would start a dedicated server.
3287    let game = resolve_program(
3288      &script_injection(
3289        &all_three,
3290        &LaunchFacts::read(&all_three),
3291        &game_profile,
3292        &context,
3293      ),
3294      &all_three,
3295      &game_profile,
3296      &context,
3297    )
3298    .unwrap();
3299
3300    match &game {
3301      LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3302      other => panic!("expected ProfileScript, got {other:?}"),
3303    }
3304
3305    // With only the server script on disk, a game instance has no script at all.
3306    let err = resolve_program(
3307      &script_injection(
3308        &server_only,
3309        &LaunchFacts::read(&server_only),
3310        &game_profile,
3311        &context,
3312      ),
3313      &server_only,
3314      &game_profile,
3315      &context,
3316    )
3317    .unwrap_err();
3318
3319    assert!(err.to_string().contains("run_bepinex.sh"));
3320  }
3321
3322  #[test]
3323  fn modded_script_injection_without_a_script_errors_but_vanilla_falls_through() {
3324    let dir = tempfile::tempdir().unwrap();
3325    let target = dir.path().join("target");
3326
3327    linux_bepinex_target(&target);
3328
3329    let eco = Ecosystem::bundled();
3330    let modded = linux_native(LaunchMode::Modded);
3331
3332    let err = launch_plan_in(&target, &eco, "valheim", &modded).unwrap_err();
3333    let message = err.to_string();
3334
3335    assert!(message.contains("run_bepinex.sh"), "{message}");
3336    assert!(message.contains("start_game_bepinex.sh"), "{message}");
3337    assert!(message.contains(&target.display().to_string()), "{message}");
3338
3339    // Vanilla asks for no injection at all, so a missing injector is not a
3340    // failure: the game binary runs with the loader's disable flag.
3341    let vanilla =
3342      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3343
3344    assert!(matches!(vanilla.program, LaunchProgram::GameExe { .. }));
3345    assert_eq!(
3346      vanilla.args,
3347      vec!["--doorstop-enable".to_string(), "false".to_string()]
3348    );
3349  }
3350
3351  #[test]
3352  fn linux_native_steam_launches_steam_and_reports_the_wrapper_requirement() {
3353    let dir = tempfile::tempdir().unwrap();
3354    let target = dir.path().join("target");
3355    let game_dir = dir.path().join("game");
3356    let script_path = dir.path().join("launch_wrapper.sh");
3357
3358    linux_bepinex_target(&target);
3359    std::fs::create_dir_all(&game_dir).unwrap();
3360    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3361
3362    let eco = Ecosystem::bundled();
3363    let mut context = linux_native(LaunchMode::Modded);
3364
3365    context.store = StorePlatform::Steam;
3366
3367    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3368
3369    // Steam cannot be handed a script as its program: it takes `-applaunch`.
3370    match &plan.program {
3371      LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
3372      other => panic!("expected Steam, got {other:?}"),
3373    }
3374
3375    // The wrapper requirement is discoverable from the plan itself, and carries
3376    // everything the two wrapper functions need — no reimplementing the rule and
3377    // no second ecosystem lookup.
3378    let wrapper = plan.steam_wrapper.clone().expect("wrapper requirement");
3379
3380    assert_eq!(wrapper.target_dir, target);
3381    assert_eq!(wrapper.loader, LoaderKind::BepInEx);
3382
3383    write_wrapper_script(&script_path).unwrap();
3384
3385    let options = steam_launch_options(&script_path);
3386
3387    assert_options_name_script(&options, &script_path);
3388    assert!(!options.contains("WINEDLLOVERRIDES"));
3389    assert!(
3390      std::fs::read_to_string(&script_path)
3391        .unwrap()
3392        .contains("run_bepinex.sh")
3393    );
3394
3395    // The plan already carries the target flag, so a caller that spawns it
3396    // verbatim reaches this target through a wrapper written for any other one.
3397    assert!(
3398      plan
3399        .args
3400        .windows(2)
3401        .any(|pair| pair == wrapper_target_args(&target).as_slice()),
3402      "plan args must carry the wrapper target flag: {:?}",
3403      plan.args
3404    );
3405
3406    // Injection is still script-based, so the game directory stays untouched.
3407    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3408
3409    assert!(written.is_empty());
3410    assert!(!game_dir.join("winhttp.dll").exists());
3411  }
3412
3413  #[test]
3414  fn stage_for_launch_rejects_macos() {
3415    let dir = tempfile::tempdir().unwrap();
3416    let target = dir.path().join("target");
3417    let game_dir = dir.path().join("game");
3418
3419    linux_bepinex_target(&target);
3420    std::fs::create_dir_all(&game_dir).unwrap();
3421
3422    let eco = Ecosystem::bundled();
3423    let mut context = ctx(LaunchMode::Modded);
3424
3425    context.os = HostOs::MacOs;
3426
3427    let err = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap_err();
3428
3429    assert!(err.to_string().contains("macOS launch is not supported"));
3430    // Nothing was written: `launch_plan_in` refuses macOS, so staging must not
3431    // dirty the game directory on its behalf.
3432    assert_eq!(std::fs::read_dir(&game_dir).unwrap().count(), 0);
3433
3434    // Control: the same target and game directory stage fine once `os` is not
3435    // macOS, proving the error comes from the macOS branch itself.
3436    context.os = HostOs::Windows;
3437
3438    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3439
3440    assert_eq!(written.len(), 2);
3441    assert!(game_dir.join("winhttp.dll").exists());
3442  }
3443
3444  #[test]
3445  fn only_a_wrapper_bound_plan_carries_the_target_flag() {
3446    let dir = tempfile::tempdir().unwrap();
3447    let target = dir.path().join("target");
3448
3449    linux_bepinex_target(&target);
3450    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3451
3452    let eco = Ecosystem::bundled();
3453
3454    // Linux native, but launched by executing the script directly: no wrapper
3455    // stands between the caller and the loader, so the flag would be a stray
3456    // argument the game has to tolerate.
3457    let direct =
3458      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3459
3460    assert_eq!(direct.steam_wrapper, None);
3461    assert!(!direct.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3462
3463    // Steam, but injecting through the proxy DLL rather than a script: still no
3464    // wrapper, still no flag.
3465    let mut proton = linux_native(LaunchMode::Modded);
3466
3467    proton.store = StorePlatform::Steam;
3468    proton.runtime = Runtime::Proton;
3469
3470    let proton_plan = launch_plan_in(&target, &eco, "valheim", &proton).unwrap();
3471
3472    assert_eq!(proton_plan.steam_wrapper, None);
3473    assert!(!proton_plan.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3474  }
3475
3476  #[test]
3477  fn wrapper_branches_are_generated_from_the_shared_script_list() {
3478    let script = wrapper_script_contents();
3479
3480    let mut previous = 0;
3481
3482    for name in LOADER_SCRIPTS {
3483      let position = script
3484        .find(&format!("[ -f \"$TARGET/{name}\" ]"))
3485        .unwrap_or_else(|| panic!("wrapper is missing a branch for {name}"));
3486
3487      assert!(position >= previous, "{name} is out of precedence order");
3488
3489      previous = position;
3490    }
3491  }
3492
3493  // --- Script-path Doorstop spelling (v3-detected target injected via a loader
3494  // script must still use v4 flags, because the script itself only understands
3495  // v4 spellings; see `doorstop_args`'s doc comment) ---
3496
3497  #[test]
3498  fn linux_native_script_present_vanilla_runs_the_script_with_v4_enabled_spelling() {
3499    let dir = tempfile::tempdir().unwrap();
3500    let target = dir.path().join("target");
3501
3502    linux_bepinex_target(&target);
3503    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3504    // No `.doorstop_version` file: `doorstop_version` defaults to 3, but the
3505    // script only recognizes the v4 spelling — see `doorstop_args`'s doc comment.
3506
3507    let eco = Ecosystem::bundled();
3508    let plan =
3509      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3510
3511    // Vanilla still runs the script: the script itself honours the disable
3512    // flag, so there is no reason to fall back to the bare game binary.
3513    match &plan.program {
3514      LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3515      other => panic!("expected ProfileScript, got {other:?}"),
3516    }
3517
3518    assert_eq!(
3519      plan.args,
3520      vec!["--doorstop-enabled".to_string(), "false".to_string()]
3521    );
3522  }
3523
3524  #[test]
3525  fn linux_native_script_present_modded_uses_v4_target_assembly_spelling() {
3526    let dir = tempfile::tempdir().unwrap();
3527    let target = dir.path().join("target");
3528
3529    linux_bepinex_target(&target);
3530    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3531    // No `.doorstop_version` file here either: same v3-defaults-but-script-wants-v4
3532    // situation as the vanilla case above.
3533
3534    let eco = Ecosystem::bundled();
3535    let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3536
3537    assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3538    assert_eq!(plan.args[0], "--doorstop-enabled");
3539    assert_eq!(plan.args[1], "true");
3540    assert_eq!(plan.args[2], "--doorstop-target-assembly");
3541    assert!(plan.args[3].ends_with("BepInEx/core/BepInEx.Preloader.dll"));
3542  }
3543
3544  #[test]
3545  fn linux_native_script_present_v3_detected_corlib_override_uses_v4_search_flag_spelling() {
3546    // The third of the three doorstop-flag pairs, and the one the fix's other
3547    // script-path tests don't touch: `linux_bepinex_target` never creates
3548    // `unstripped_corlib`, so without this test the corlib search-path flag on
3549    // the script-injected + v3-detected path is only correct by inference from
3550    // the shared `if v4` tuple in `doorstop_args`, not by a direct assertion.
3551    let dir = tempfile::tempdir().unwrap();
3552    let target = dir.path().join("target");
3553
3554    linux_bepinex_target(&target);
3555    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3556    std::fs::create_dir_all(target.join("unstripped_corlib")).unwrap();
3557    // No `.doorstop_version` file: detected version defaults to v3, but the
3558    // script on disk forces the v4 spellings — see `doorstop_args`'s doc comment.
3559
3560    let eco = Ecosystem::bundled();
3561    let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3562
3563    assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3564
3565    let idx = plan
3566      .args
3567      .iter()
3568      .position(|a| a == "--doorstop-mono-dll-search-path-override")
3569      .expect("v4 corlib search-path flag missing");
3570
3571    assert!(plan.args[idx + 1].ends_with("/unstripped_corlib"));
3572    assert!(
3573      !plan
3574        .args
3575        .iter()
3576        .any(|a| a == "--doorstop-dll-search-override"),
3577      "v3 corlib search-path spelling must not appear on the script-injected path: {:?}",
3578      plan.args
3579    );
3580  }
3581
3582  #[test]
3583  fn linux_native_script_present_v4_detected_target_is_unchanged() {
3584    let dir = tempfile::tempdir().unwrap();
3585    let target = dir.path().join("target");
3586
3587    linux_bepinex_target(&target);
3588    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3589    std::fs::write(target.join(".doorstop_version"), "4.0.0").unwrap();
3590
3591    let eco = Ecosystem::bundled();
3592
3593    let vanilla =
3594      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3595
3596    assert_eq!(
3597      vanilla.args,
3598      vec!["--doorstop-enabled".to_string(), "false".to_string()]
3599    );
3600
3601    let modded =
3602      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3603
3604    assert_eq!(modded.args[0], "--doorstop-enabled");
3605    assert_eq!(modded.args[2], "--doorstop-target-assembly");
3606  }
3607
3608  #[test]
3609  fn proton_v3_detected_target_still_uses_v3_spellings_even_with_a_script_on_disk() {
3610    // Regression guard: script-path spelling must key off actually running
3611    // through the script (Linux + native + a found script), not merely off
3612    // `HostOs::Linux` or the script file's mere presence on disk. A Proton
3613    // (Wine) launch never goes through the loader script — `script_injection`
3614    // requires `Runtime::Native` — so even with `run_bepinex.sh` sitting in the
3615    // target and no `.doorstop_version` file, the argv must still get the
3616    // version-matched (v3) spelling, because it is Doorstop's own parser, not
3617    // the script, that will read it under Proton.
3618    let dir = tempfile::tempdir().unwrap();
3619    let target = dir.path().join("target");
3620
3621    linux_bepinex_target(&target);
3622    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3623
3624    let eco = Ecosystem::bundled();
3625    let mut context = linux_native(LaunchMode::Modded);
3626
3627    context.runtime = Runtime::Proton;
3628
3629    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3630
3631    assert_eq!(plan.args[0], "--doorstop-enable");
3632    assert_eq!(plan.args[2], "--doorstop-target");
3633
3634    let mut vanilla_context = linux_native(LaunchMode::Vanilla);
3635
3636    vanilla_context.runtime = Runtime::Proton;
3637
3638    let vanilla = launch_plan_in(&target, &eco, "valheim", &vanilla_context).unwrap();
3639
3640    assert_eq!(
3641      vanilla.args,
3642      vec!["--doorstop-enable".to_string(), "false".to_string()]
3643    );
3644  }
3645
3646  #[test]
3647  fn windows_v3_detected_target_still_uses_v3_spellings_regression_guard() {
3648    // Regression guard for the non-script paths named in the fix: a
3649    // v3-detected target launched via argv (not a script) must keep the v3
3650    // spellings, on Windows exactly as before this fix.
3651    let dir = tempfile::tempdir().unwrap();
3652    let root = dir.path();
3653    let core = root.join("BepInEx/core");
3654
3655    std::fs::create_dir_all(&core).unwrap();
3656    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3657
3658    let eco = Ecosystem::bundled();
3659    let plan = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Modded)).unwrap();
3660
3661    assert_eq!(plan.args[0], "--doorstop-enable");
3662    assert_eq!(plan.args[2], "--doorstop-target");
3663
3664    let vanilla = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Vanilla)).unwrap();
3665
3666    assert_eq!(
3667      vanilla.args,
3668      vec!["--doorstop-enable".to_string(), "false".to_string()]
3669    );
3670  }
3671
3672  #[test]
3673  fn store_and_runtime_parse_from_their_config_spellings() {
3674    assert_eq!(
3675      "steam".parse::<StorePlatform>().unwrap(),
3676      StorePlatform::Steam
3677    );
3678    assert_eq!(
3679      "steam-direct".parse::<StorePlatform>().unwrap(),
3680      StorePlatform::SteamDirect
3681    );
3682    assert_eq!(
3683      "other".parse::<StorePlatform>().unwrap(),
3684      StorePlatform::Other
3685    );
3686    assert_eq!("native".parse::<Runtime>().unwrap(), Runtime::Native);
3687    assert_eq!("proton".parse::<Runtime>().unwrap(), Runtime::Proton);
3688
3689    // An unknown value names itself, so a caller can quote it back.
3690    let error = "wat".parse::<StorePlatform>().unwrap_err().to_string();
3691
3692    assert!(error.contains("wat"), "got: {error}");
3693  }
3694
3695  #[test]
3696  fn resolve_game_exe_returns_the_first_present_candidate() {
3697    let dir = tempfile::tempdir().unwrap();
3698    let game_dir = dir.path();
3699
3700    std::fs::write(game_dir.join("second.x86_64"), b"elf").unwrap();
3701
3702    let names = vec!["first.exe".to_string(), "second.x86_64".to_string()];
3703    let found = resolve_game_exe(game_dir, &names).unwrap();
3704
3705    assert_eq!(found, game_dir.join("second.x86_64"));
3706
3707    // Nothing present names every candidate it looked for.
3708    let error = resolve_game_exe(game_dir, &["absent.exe".to_string()])
3709      .unwrap_err()
3710      .to_string();
3711
3712    assert!(error.contains("absent.exe"), "got: {error}");
3713  }
3714
3715  #[test]
3716  fn a_plan_becomes_a_spawnable_command() {
3717    let dir = tempfile::tempdir().unwrap();
3718    let game_dir = dir.path();
3719
3720    std::fs::write(game_dir.join("valheim.x86_64"), b"elf").unwrap();
3721
3722    // `LaunchPlan` derives no `Default`, so every field is named. It is
3723    // `#[non_exhaustive]`, which only restricts other crates, so a struct literal
3724    // is fine inside this module.
3725    let plan = LaunchPlan {
3726      program: LaunchProgram::GameExe {
3727        exe_names: vec!["valheim.x86_64".to_string()],
3728      },
3729      args: vec!["-console".to_string()],
3730      env: vec![("KEY".to_string(), "VALUE".to_string())],
3731      working_dir: Some(game_dir.to_path_buf()),
3732      steam_wrapper: None,
3733    };
3734
3735    let command = plan.to_command(game_dir).unwrap();
3736
3737    assert_eq!(command.get_program(), game_dir.join("valheim.x86_64"));
3738    assert_eq!(
3739      command.get_args().collect::<Vec<_>>(),
3740      vec![std::ffi::OsStr::new("-console")]
3741    );
3742    assert_eq!(command.get_current_dir(), Some(game_dir));
3743    assert!(
3744      command
3745        .get_envs()
3746        .any(|(key, value)| key == std::ffi::OsStr::new("KEY")
3747          && value == Some(std::ffi::OsStr::new("VALUE")))
3748    );
3749  }
3750
3751  /// `-applaunch <id>` must lead, with the plan's own argv after it, whatever
3752  /// path the Steam executable resolved to. Asserted against an explicit program
3753  /// so the ordering is checked on any host, including one with no Steam at all.
3754  #[test]
3755  fn a_steam_command_leads_with_applaunch_and_keeps_the_plan_argv_after_it() {
3756    let program = Path::new(r"C:\Program Files (x86)\Steam\steam.exe");
3757    let mut command = steam_command(program, 892970);
3758
3759    command.args(["-console".to_string(), "--ts-target".to_string()]);
3760
3761    assert_eq!(command.get_program(), program.as_os_str());
3762    assert_eq!(
3763      command.get_args().collect::<Vec<_>>(),
3764      vec![
3765        std::ffi::OsStr::new("-applaunch"),
3766        std::ffi::OsStr::new("892970"),
3767        std::ffi::OsStr::new("-console"),
3768        std::ffi::OsStr::new("--ts-target"),
3769      ]
3770    );
3771  }
3772
3773  /// The Steam arm resolves its program through [`crate::steam::steam_exe`]
3774  /// rather than hardcoding `steam`, which never resolves on Windows.
3775  ///
3776  /// `LaunchPlan::env` is asserted *unchanged* here: it is documented as not
3777  /// reaching a game started through `-applaunch`, so this fix must keep setting
3778  /// exactly what the plan carried and add nothing that would silently do
3779  /// nothing.
3780  #[test]
3781  fn a_steam_plan_spawns_the_resolved_steam_executable() {
3782    let dir = tempfile::tempdir().unwrap();
3783    let game_dir = dir.path();
3784
3785    let plan = LaunchPlan {
3786      program: LaunchProgram::Steam {
3787        steam_app_id: 892970,
3788      },
3789      args: vec!["-console".to_string()],
3790      env: vec![("KEY".to_string(), "VALUE".to_string())],
3791      working_dir: None,
3792      steam_wrapper: None,
3793    };
3794
3795    let command = plan.to_command(game_dir).unwrap();
3796
3797    assert_eq!(
3798      command.get_program(),
3799      crate::steam::steam_exe().as_os_str(),
3800      "the Steam arm must use the resolved executable"
3801    );
3802    assert_eq!(
3803      command.get_args().collect::<Vec<_>>(),
3804      vec![
3805        std::ffi::OsStr::new("-applaunch"),
3806        std::ffi::OsStr::new("892970"),
3807        std::ffi::OsStr::new("-console"),
3808      ]
3809    );
3810
3811    let envs = command.get_envs().collect::<Vec<_>>();
3812
3813    assert_eq!(
3814      envs,
3815      vec![(
3816        std::ffi::OsStr::new("KEY"),
3817        Some(std::ffi::OsStr::new("VALUE"))
3818      )],
3819      "the plan's env must reach the command unchanged, with nothing added"
3820    );
3821  }
3822}
3823
3824#[cfg(test)]
3825mod planning_tests {
3826  use super::*;
3827
3828  const TARGET: &str = "/profiles/main";
3829
3830  fn ctx(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> LaunchContext {
3831    LaunchContext::new(os, store, runtime, mode)
3832  }
3833
3834  fn with_preloader() -> LaunchFacts {
3835    LaunchFacts {
3836      preloader: Some("BepInEx.Preloader.dll".to_string()),
3837      ..LaunchFacts::default()
3838    }
3839  }
3840
3841  fn plan(facts: &LaunchFacts, context: &LaunchContext) -> Result<LaunchPlan> {
3842    launch_plan_from(
3843      Path::new(TARGET),
3844      facts,
3845      &Ecosystem::bundled(),
3846      "valheim",
3847      context,
3848    )
3849  }
3850
3851  #[test]
3852  fn doorstop_flags_follow_the_recorded_version() {
3853    let windows = ctx(
3854      HostOs::Windows,
3855      StorePlatform::SteamDirect,
3856      Runtime::Native,
3857      LaunchMode::Modded,
3858    );
3859    let mut facts = with_preloader();
3860
3861    let v3 = plan(&facts, &windows).unwrap();
3862
3863    facts.doorstop_version = 4;
3864
3865    let v4 = plan(&facts, &windows).unwrap();
3866
3867    assert_eq!(v3.args[0], "--doorstop-enable");
3868    assert_eq!(v4.args[0], "--doorstop-enabled");
3869    assert!(
3870      v3.args
3871        .contains(&format!("{TARGET}/BepInEx/core/BepInEx.Preloader.dll"))
3872    );
3873  }
3874
3875  #[test]
3876  fn a_modded_bepinex_launch_needs_a_preloader() {
3877    let windows = ctx(
3878      HostOs::Windows,
3879      StorePlatform::SteamDirect,
3880      Runtime::Native,
3881      LaunchMode::Modded,
3882    );
3883
3884    let result = plan(&LaunchFacts::default(), &windows);
3885
3886    assert!(
3887      matches!(result, Err(Error::Profile(message)) if message.contains("no BepInEx preloader"))
3888    );
3889  }
3890
3891  #[test]
3892  fn corlibs_add_the_search_path_override() {
3893    let windows = ctx(
3894      HostOs::Windows,
3895      StorePlatform::SteamDirect,
3896      Runtime::Native,
3897      LaunchMode::Modded,
3898    );
3899    let mut facts = with_preloader();
3900
3901    facts.has_corlibs = true;
3902
3903    let plan = plan(&facts, &windows).unwrap();
3904
3905    assert!(
3906      plan
3907        .args
3908        .contains(&"--doorstop-dll-search-override".to_string())
3909    );
3910    assert!(plan.args.contains(&format!("{TARGET}/unstripped_corlib")));
3911  }
3912
3913  #[test]
3914  fn a_listed_loader_script_is_run_on_linux_native() {
3915    let linux = ctx(
3916      HostOs::Linux,
3917      StorePlatform::SteamDirect,
3918      Runtime::Native,
3919      LaunchMode::Modded,
3920    );
3921    let mut facts = with_preloader();
3922
3923    facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
3924
3925    let plan = plan(&facts, &linux).unwrap();
3926
3927    assert!(matches!(
3928      plan.program,
3929      LaunchProgram::ProfileScript { ref path, .. }
3930        if path == &Path::new(TARGET).join("start_game_bepinex.sh")
3931    ));
3932    assert_eq!(plan.args[0], "--doorstop-enabled");
3933  }
3934
3935  #[test]
3936  fn linux_native_modded_without_a_loader_script_is_refused() {
3937    let linux = ctx(
3938      HostOs::Linux,
3939      StorePlatform::SteamDirect,
3940      Runtime::Native,
3941      LaunchMode::Modded,
3942    );
3943
3944    let result = plan(&with_preloader(), &linux);
3945
3946    assert!(matches!(result, Err(Error::Profile(message)) if message.contains("loader script")));
3947  }
3948
3949  #[test]
3950  fn the_server_script_is_ignored_for_a_game_instance() {
3951    let linux = ctx(
3952      HostOs::Linux,
3953      StorePlatform::SteamDirect,
3954      Runtime::Native,
3955      LaunchMode::Modded,
3956    );
3957    let mut facts = with_preloader();
3958
3959    facts.loader_scripts = vec!["start_server_bepinex.sh".to_string()];
3960
3961    assert!(plan(&facts, &linux).is_err());
3962  }
3963
3964  #[test]
3965  fn melonloader_regenerates_only_without_its_assemblies() {
3966    let eco = Ecosystem::bundled();
3967    let profile = eco
3968      .games()
3969      .filter_map(|game| game.profile())
3970      .find(|profile| profile.package_loader == LoaderKind::MelonLoader)
3971      .unwrap();
3972    let windows = ctx(
3973      HostOs::Windows,
3974      StorePlatform::SteamDirect,
3975      Runtime::Native,
3976      LaunchMode::Modded,
3977    );
3978    let mut facts = LaunchFacts::default();
3979
3980    let bare = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
3981
3982    facts.melonloader_assemblies = true;
3983
3984    let built = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
3985
3986    assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
3987    assert!(!built.contains(&"--melonloader.agfregenerate".to_string()));
3988  }
3989
3990  #[test]
3991  fn macos_is_refused_whatever_the_facts() {
3992    let mac = ctx(
3993      HostOs::MacOs,
3994      StorePlatform::SteamDirect,
3995      Runtime::Native,
3996      LaunchMode::Modded,
3997    );
3998
3999    assert!(plan(&with_preloader(), &mac).is_err());
4000  }
4001
4002  #[test]
4003  #[cfg(feature = "io")]
4004  fn launch_facts_read_what_the_target_holds() {
4005    let dir = tempfile::tempdir().unwrap();
4006    let root = dir.path();
4007
4008    std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
4009    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
4010    std::fs::create_dir_all(root.join("MelonLoader/Il2CppAssemblies")).unwrap();
4011    std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"").unwrap();
4012    std::fs::write(root.join("run_bepinex.sh"), b"").unwrap();
4013    std::fs::write(root.join(".doorstop_version"), b"4.0.0").unwrap();
4014    std::fs::write(
4015      root.join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll"),
4016      b"",
4017    )
4018    .unwrap();
4019
4020    let facts = LaunchFacts::read(root);
4021
4022    assert_eq!(facts.doorstop_version, 4);
4023    assert_eq!(facts.preloader.as_deref(), Some("BepInEx.Preloader.dll"));
4024    assert!(facts.has_corlibs);
4025    assert_eq!(facts.loader_scripts, vec!["run_bepinex.sh".to_string()]);
4026    assert!(facts.melonloader_assemblies);
4027    assert_eq!(
4028      LaunchFacts::read(&root.join("missing")),
4029      LaunchFacts::default()
4030    );
4031  }
4032
4033  #[test]
4034  #[cfg(feature = "io")]
4035  fn launch_facts_read_the_loader_files_and_recorded_packages() {
4036    let dir = tempfile::tempdir().unwrap();
4037    let root = dir.path();
4038    let version: crate::models::Version = serde_json::from_str(
4039      r#"{"name":"GDWeave","full_name":"NotNet-GDWeave","description":"d","icon":"i",
4040      "version_number":"2.0.0","dependencies":[],"download_url":"u","downloads":1,
4041      "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
4042      "uuid4":"u","file_size":1}"#,
4043    )
4044    .unwrap();
4045
4046    std::fs::create_dir_all(root.join("GDWeave/core")).unwrap();
4047    std::fs::write(root.join("GDWeave/core/GDWeave.dll"), b"").unwrap();
4048    std::fs::create_dir_all(root.join("R2Northstar")).unwrap();
4049    std::fs::write(root.join("R2Northstar/Northstar.dll"), b"").unwrap();
4050    crate::profile::modlist::write(
4051      root,
4052      &[crate::profile::mod_entry_from_version(
4053        "NotNet-GDWeave",
4054        "NotNet",
4055        &version,
4056        1,
4057      )],
4058    )
4059    .unwrap();
4060
4061    let facts = LaunchFacts::read(root);
4062
4063    assert_eq!(
4064      facts.loaders,
4065      vec![LoaderKind::GdWeave, LoaderKind::Northstar]
4066    );
4067    assert_eq!(facts.recorded, vec!["NotNet-GDWeave".to_string()]);
4068  }
4069}