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      WINE_DLL_OVERRIDES.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, since Wine prefers its own builtin
1619/// `winhttp` over the loader's. [`LaunchPlan::steam_launch_options`] gives the
1620/// line for either case.
1621pub fn steam_launch_options(script_path: &Path) -> String {
1622  format!(
1623    r#""{script}" %command%"#,
1624    script = script_path.to_string_lossy().replace('\\', "/"),
1625  )
1626}
1627
1628impl LaunchPlan {
1629  /// What the user pastes into the game's Steam launch options for this plan,
1630  /// or `None` when the plan needs nothing there.
1631  ///
1632  /// Steam keeps one launch-options string for every launch of a game, so the
1633  /// answer is the same for a modded or a vanilla plan:
1634  ///
1635  /// - With a [`steam_wrapper`](Self::steam_wrapper) (Linux native), the line
1636  ///   running `wrapper_script`, as [`steam_launch_options`] builds it.
1637  /// - For a [`LaunchProgram::Steam`] launch under Proton, the
1638  ///   `WINEDLLOVERRIDES` line. Steam starts the game with its own environment,
1639  ///   so the override in [`env`](Self::env) reaches it only from here.
1640  ///
1641  /// ```
1642  /// use std::path::Path;
1643  /// use thunderstore_engine::ecosystem::Ecosystem;
1644  /// use thunderstore_engine::profile::launch::{
1645  ///   HostOs, LaunchContext, LaunchFacts, LaunchMode, Runtime, StorePlatform, launch_plan_from,
1646  /// };
1647  ///
1648  /// let mut facts = LaunchFacts::default();
1649  ///
1650  /// facts.preloader = Some("BepInEx.Preloader.dll".to_string());
1651  ///
1652  /// let proton = LaunchContext::new(HostOs::Linux, StorePlatform::Steam, Runtime::Proton, LaunchMode::Vanilla);
1653  /// let plan = launch_plan_from(Path::new("/profile"), &facts, &Ecosystem::bundled(), "valheim", &proton)?;
1654  ///
1655  /// assert_eq!(
1656  ///   plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")).as_deref(),
1657  ///   Some(r#"WINEDLLOVERRIDES="winhttp=n,b" %command%"#),
1658  /// );
1659  /// # Ok::<(), thunderstore_engine::Error>(())
1660  /// ```
1661  pub fn steam_launch_options(&self, wrapper_script: &Path) -> Option<String> {
1662    if self.steam_wrapper.is_some() {
1663      return Some(steam_launch_options(wrapper_script));
1664    }
1665
1666    if !matches!(self.program, LaunchProgram::Steam { .. }) {
1667      return None;
1668    }
1669
1670    self
1671      .env
1672      .iter()
1673      .find(|(key, _)| key == WINE_DLL_OVERRIDES)
1674      .map(|(key, value)| format!(r#"{key}="{value}" %command%"#))
1675  }
1676
1677  /// The proxy DLL this plan's Steam launch options override, when they carry
1678  /// the Proton override.
1679  #[cfg(feature = "io")]
1680  pub(crate) fn steam_dll_override(&self) -> Option<&str> {
1681    if self.steam_wrapper.is_some() || !matches!(self.program, LaunchProgram::Steam { .. }) {
1682      return None;
1683    }
1684
1685    self
1686      .env
1687      .iter()
1688      .find(|(key, _)| key == WINE_DLL_OVERRIDES)
1689      .and_then(|(_, value)| value.split('=').next())
1690  }
1691}
1692
1693/// The Wine variable that makes a loader's proxy DLL win over Wine's builtin.
1694const WINE_DLL_OVERRIDES: &str = "WINEDLLOVERRIDES";
1695
1696/// The first of `exe_names` present in `game_dir`.
1697#[cfg(feature = "io")]
1698pub fn resolve_game_exe(game_dir: &Path, exe_names: &[String]) -> Result<PathBuf> {
1699  exe_names
1700    .iter()
1701    .map(|name| game_dir.join(name))
1702    .find(|candidate| candidate.is_file())
1703    .ok_or_else(|| {
1704      Error::Profile(format!(
1705        "no game executable found in {}: none of {} exist",
1706        game_dir.display(),
1707        exe_names.join(", ")
1708      ))
1709    })
1710}
1711
1712/// Where a game's Steam wrapper script is written.
1713///
1714/// One shared file for every target rather than one per profile: the script
1715/// resolves which directory to chainload from its argv at run time, and Steam
1716/// stores exactly one launch-options string per game naming this path. A
1717/// per-profile path would go stale the moment a user switched profiles.
1718pub fn wrapper_path(base: &Path, game: &str) -> PathBuf {
1719  base.join(game).join("steam-wrapper.sh")
1720}
1721
1722/// Builds the invocation that asks a running Steam client to start
1723/// `steam_app_id`.
1724///
1725/// Takes the program as a parameter rather than resolving it, so the argv this
1726/// produces can be asserted on any host — including one with no Steam installed,
1727/// which is every CI runner this crate is tested on.
1728///
1729/// Sets no environment: `steam -applaunch <id>` only messages an already-running
1730/// client, which starts the game with its own environment, so anything set here
1731/// would silently reach nothing. See [`LaunchPlan::env`].
1732#[cfg(feature = "io")]
1733fn steam_command(program: &Path, steam_app_id: u32) -> std::process::Command {
1734  let mut command = std::process::Command::new(program);
1735
1736  command.arg("-applaunch").arg(steam_app_id.to_string());
1737
1738  command
1739}
1740
1741#[cfg(feature = "io")]
1742impl LaunchPlan {
1743  /// Translates this plan into the process to spawn.
1744  ///
1745  /// Always an argv array, never a shell, so a path containing spaces or quotes
1746  /// cannot become an injection. Separate from spawning so the program,
1747  /// arguments, and environment can be asserted without starting anything.
1748  ///
1749  /// Every [`LaunchProgram`] variant is handled, with no wildcard arm.
1750  /// `LaunchProgram` is `#[non_exhaustive]`, but that only constrains other
1751  /// crates, so a wildcard here would be an unreachable pattern and fail
1752  /// `-D warnings`. Adding a variant therefore breaks this build deliberately,
1753  /// which is the point: a new launch shape must be translated, not silently
1754  /// rejected at run time.
1755  ///
1756  /// This is where the host is read, which is why the two variants that need a
1757  /// real path both resolve one here rather than in [`launch_plan_in`]: the plan
1758  /// stays a pure computation, and translating it into a process is the step
1759  /// allowed to look at the machine. [`LaunchProgram::GameExe`] and
1760  /// [`LaunchProgram::ProfileScript`] resolve their binary out of `game_dir`, and
1761  /// [`LaunchProgram::Steam`] resolves the Steam client through
1762  /// [`crate::steam::steam_exe`] — a bare `steam` resolves on Linux but never on
1763  /// Windows, whose Steam installer adds nothing to `PATH`.
1764  pub fn to_command(&self, game_dir: &Path) -> Result<std::process::Command> {
1765    let mut command = match &self.program {
1766      LaunchProgram::GameExe { exe_names } => {
1767        std::process::Command::new(resolve_game_exe(game_dir, exe_names)?)
1768      }
1769      LaunchProgram::Steam { steam_app_id } => {
1770        steam_command(&crate::steam::steam_exe(), *steam_app_id)
1771      }
1772      LaunchProgram::ProfileScript { path, exe_names } => {
1773        let mut command = std::process::Command::new(path);
1774
1775        command.arg(resolve_game_exe(game_dir, exe_names)?);
1776
1777        command
1778      }
1779    };
1780
1781    command.args(&self.args);
1782
1783    for (key, value) in &self.env {
1784      command.env(key, value);
1785    }
1786
1787    if let Some(dir) = &self.working_dir {
1788      command.current_dir(dir);
1789    }
1790
1791    Ok(command)
1792  }
1793}
1794
1795#[cfg(all(test, feature = "io"))]
1796mod tests {
1797  use super::*;
1798
1799  /// Asserts `options` is `script` quoted, then `%command%`. On Unix that is
1800  /// `script` exactly; on Windows it holds no `\` and names the same file.
1801  pub(super) fn assert_options_name_script(options: &str, script: &Path) {
1802    let quoted = options
1803      .strip_suffix(" %command%")
1804      .and_then(|rest| rest.strip_prefix('"'))
1805      .and_then(|rest| rest.strip_suffix('"'))
1806      .unwrap_or_else(|| panic!("not a quoted path then %command%: {options}"));
1807
1808    #[cfg(unix)]
1809    assert_eq!(quoted, script.to_str().unwrap());
1810
1811    #[cfg(not(unix))]
1812    {
1813      assert!(!quoted.contains('\\'), "{quoted}");
1814      assert_eq!(
1815        std::fs::canonicalize(quoted).unwrap(),
1816        std::fs::canonicalize(script).unwrap()
1817      );
1818    }
1819  }
1820
1821  #[test]
1822  fn doorstop_version_reads_major_and_defaults_to_three() {
1823    let dir = tempfile::tempdir().unwrap();
1824    let root = dir.path();
1825
1826    // Missing file => v3.
1827    assert_eq!(doorstop_version(root), 3);
1828
1829    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1830    assert_eq!(doorstop_version(root), 4);
1831
1832    std::fs::write(root.join(".doorstop_version"), "3.7.1").unwrap();
1833    assert_eq!(doorstop_version(root), 3);
1834
1835    // r2modman falls back to v3 for major >= 5; we treat it as v4 (its own bug).
1836    std::fs::write(root.join(".doorstop_version"), "5.1.0").unwrap();
1837    assert_eq!(doorstop_version(root), 5);
1838
1839    // Unparseable => v3.
1840    std::fs::write(root.join(".doorstop_version"), "garbage").unwrap();
1841    assert_eq!(doorstop_version(root), 3);
1842  }
1843
1844  #[test]
1845  fn bepinex_preloader_finds_candidate_and_prefixes_under_proton() {
1846    let dir = tempfile::tempdir().unwrap();
1847    let root = dir.path();
1848    let core = root.join("BepInEx/core");
1849
1850    std::fs::create_dir_all(&core).unwrap();
1851    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1852    std::fs::write(core.join("Unrelated.dll"), b"x").unwrap();
1853
1854    let native = bepinex_preloader(root, Runtime::Native).unwrap();
1855
1856    assert!(native.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1857    assert!(!native.starts_with("Z:"));
1858
1859    let proton = bepinex_preloader(root, Runtime::Proton).unwrap();
1860
1861    assert!(proton.starts_with("Z:"));
1862    assert!(proton.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1863  }
1864
1865  #[test]
1866  fn bepinex_preloader_errors_when_absent() {
1867    let dir = tempfile::tempdir().unwrap();
1868
1869    assert!(bepinex_preloader(dir.path(), Runtime::Native).is_err());
1870  }
1871
1872  #[test]
1873  fn has_corlibs_detects_the_directory() {
1874    let dir = tempfile::tempdir().unwrap();
1875    let root = dir.path();
1876
1877    assert!(!has_corlibs(root));
1878
1879    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
1880
1881    assert!(has_corlibs(root));
1882  }
1883
1884  fn ctx(mode: LaunchMode) -> LaunchContext {
1885    LaunchContext {
1886      os: HostOs::Windows,
1887      store: StorePlatform::Steam,
1888      runtime: Runtime::Native,
1889      mode,
1890      extra_args: Vec::new(),
1891    }
1892  }
1893
1894  fn profile_with(loader: LoaderKind) -> GameProfile {
1895    let eco = Ecosystem::bundled();
1896    let mut profile = eco.game("valheim").unwrap().profile().unwrap().clone();
1897    profile.package_loader = loader;
1898
1899    profile
1900  }
1901
1902  #[test]
1903  fn bepinex_v3_and_v4_use_the_right_flag_spellings() {
1904    let dir = tempfile::tempdir().unwrap();
1905    let root = dir.path();
1906    let core = root.join("BepInEx/core");
1907
1908    std::fs::create_dir_all(&core).unwrap();
1909    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1910
1911    let profile = profile_with(LoaderKind::BepInEx);
1912
1913    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1914
1915    assert_eq!(v3[0], "--doorstop-enable");
1916    assert_eq!(v3[1], "true");
1917    assert_eq!(v3[2], "--doorstop-target");
1918
1919    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1920
1921    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1922
1923    assert_eq!(v4[0], "--doorstop-enabled");
1924    assert_eq!(v4[2], "--doorstop-target-assembly");
1925
1926    // Vanilla uses the matching spelling for the detected version — r2modman
1927    // emits the v3 spelling here even on v4, which we deliberately correct.
1928    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
1929
1930    assert_eq!(
1931      vanilla,
1932      vec!["--doorstop-enabled".to_string(), "false".to_string()]
1933    );
1934  }
1935
1936  #[test]
1937  fn melonloader_adds_regenerate_only_when_assemblies_are_absent() {
1938    let dir = tempfile::tempdir().unwrap();
1939    let root = dir.path();
1940    let profile = profile_with(LoaderKind::MelonLoader);
1941
1942    let bare = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1943
1944    assert_eq!(bare[0], "--melonloader.basedir");
1945    assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
1946
1947    let managed = root.join("MelonLoader/Managed");
1948    std::fs::create_dir_all(&managed).unwrap();
1949    std::fs::write(managed.join("Assembly-CSharp.dll"), b"x").unwrap();
1950
1951    let with_assembly = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1952
1953    assert!(!with_assembly.contains(&"--melonloader.agfregenerate".to_string()));
1954    assert_eq!(
1955      loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap(),
1956      vec!["--no-mods".to_string()]
1957    );
1958  }
1959
1960  #[test]
1961  fn single_element_flags_stay_single_elements() {
1962    let dir = tempfile::tempdir().unwrap();
1963    let root = dir.path();
1964
1965    let gdweave = loader_args(
1966      root,
1967      &profile_with(LoaderKind::GdWeave),
1968      &ctx(LaunchMode::Modded),
1969    )
1970    .unwrap();
1971
1972    assert_eq!(gdweave.len(), 1);
1973    assert!(gdweave[0].starts_with("--gdweave-folder-override="));
1974    assert!(gdweave[0].ends_with("/GDWeave"));
1975
1976    let northstar = loader_args(
1977      root,
1978      &profile_with(LoaderKind::Northstar),
1979      &ctx(LaunchMode::Modded),
1980    )
1981    .unwrap();
1982
1983    assert_eq!(northstar[0], "-northstar");
1984    assert!(northstar[1].starts_with("-profile="));
1985  }
1986
1987  #[test]
1988  fn shimloader_and_rivet_and_rom_shapes() {
1989    let dir = tempfile::tempdir().unwrap();
1990    let root = dir.path();
1991
1992    let shim = loader_args(
1993      root,
1994      &profile_with(LoaderKind::Shimloader),
1995      &ctx(LaunchMode::Modded),
1996    )
1997    .unwrap();
1998
1999    assert_eq!(shim.len(), 8);
2000    assert_eq!(shim[0], "--mod-dir");
2001    assert!(shim.contains(&"--overlay-dir".to_string()));
2002
2003    let rivet = loader_args(
2004      root,
2005      &profile_with(LoaderKind::Rivet),
2006      &ctx(LaunchMode::Modded),
2007    )
2008    .unwrap();
2009
2010    assert_eq!(rivet[0], "-rivetEnable");
2011    assert_eq!(rivet[1], "true");
2012    assert!(rivet.contains(&"-rivetDirectory".to_string()));
2013    assert_eq!(
2014      loader_args(
2015        root,
2016        &profile_with(LoaderKind::Rivet),
2017        &ctx(LaunchMode::Vanilla)
2018      )
2019      .unwrap(),
2020      vec!["-rivetEnable".to_string(), "false".to_string()]
2021    );
2022
2023    let rom = loader_args(
2024      root,
2025      &profile_with(LoaderKind::ReturnOfModding),
2026      &ctx(LaunchMode::Modded),
2027    )
2028    .unwrap();
2029
2030    assert_eq!(rom[0], "--rom_modding_root_folder");
2031  }
2032
2033  #[test]
2034  fn unknown_and_none_loaders_produce_no_args() {
2035    let dir = tempfile::tempdir().unwrap();
2036    let root = dir.path();
2037
2038    assert!(
2039      loader_args(
2040        root,
2041        &profile_with(LoaderKind::None),
2042        &ctx(LaunchMode::Modded)
2043      )
2044      .unwrap()
2045      .is_empty()
2046    );
2047    assert!(
2048      loader_args(
2049        root,
2050        &profile_with(LoaderKind::Other),
2051        &ctx(LaunchMode::Modded)
2052      )
2053      .unwrap()
2054      .is_empty()
2055    );
2056  }
2057
2058  #[test]
2059  fn server_instance_appends_server_flag_for_bepinex() {
2060    let dir = tempfile::tempdir().unwrap();
2061    let root = dir.path();
2062    let core = root.join("BepInEx/core");
2063
2064    std::fs::create_dir_all(&core).unwrap();
2065    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2066
2067    let mut profile = profile_with(LoaderKind::BepInEx);
2068    profile.instance_type = InstanceType::Server;
2069
2070    let args = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2071
2072    assert!(args.contains(&"--server".to_string()));
2073  }
2074
2075  #[test]
2076  fn umm_uses_doorstop_flags_and_never_gets_server_flag() {
2077    let dir = tempfile::tempdir().unwrap();
2078    let root = dir.path();
2079    let profile = profile_with(LoaderKind::Umm);
2080
2081    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2082
2083    assert_eq!(v3[0], "--doorstop-enable");
2084    assert_eq!(v3[1], "true");
2085    assert_eq!(v3[2], "--doorstop-target");
2086    assert!(v3[3].ends_with("UMM/Core/UnityModManager.dll"));
2087
2088    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2089
2090    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2091
2092    assert_eq!(v4[0], "--doorstop-enabled");
2093    assert_eq!(v4[2], "--doorstop-target-assembly");
2094    assert!(v4[3].ends_with("UMM/Core/UnityModManager.dll"));
2095
2096    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2097
2098    assert_eq!(
2099      vanilla,
2100      vec!["--doorstop-enabled".to_string(), "false".to_string()]
2101    );
2102
2103    // Unlike BepInEx, UMM's `DoorstopTarget` arm never appends `--server`, even
2104    // when the profile's instance type is `Server`.
2105    let mut server_profile = profile_with(LoaderKind::Umm);
2106    server_profile.instance_type = InstanceType::Server;
2107
2108    let server_args = loader_args(root, &server_profile, &ctx(LaunchMode::Modded)).unwrap();
2109
2110    assert!(!server_args.contains(&"--server".to_string()));
2111  }
2112
2113  #[test]
2114  fn bepis_loader_modded_and_vanilla_shapes() {
2115    let dir = tempfile::tempdir().unwrap();
2116    let root = dir.path();
2117    let core = root.join("BepInEx/core");
2118
2119    std::fs::create_dir_all(&core).unwrap();
2120    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2121
2122    let profile = profile_with(LoaderKind::BepisLoader);
2123
2124    let modded = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2125
2126    assert_eq!(modded[0], "--hookfxr-enable");
2127    assert_eq!(modded[1], "--bepinex-target");
2128    assert!(modded.contains(&"--doorstop-enabled".to_string()));
2129    assert!(modded.contains(&"--doorstop-target-assembly".to_string()));
2130
2131    let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2132
2133    assert_eq!(
2134      vanilla,
2135      vec![
2136        "--hookfxr-disable".to_string(),
2137        "--doorstop-enabled".to_string(),
2138        "false".to_string()
2139      ]
2140    );
2141  }
2142
2143  #[test]
2144  fn lovely_modded_and_vanilla_shapes() {
2145    let dir = tempfile::tempdir().unwrap();
2146    let root = dir.path();
2147
2148    let modded = loader_args(
2149      root,
2150      &profile_with(LoaderKind::Lovely),
2151      &ctx(LaunchMode::Modded),
2152    )
2153    .unwrap();
2154
2155    assert_eq!(modded[0], "--mod-dir");
2156    assert!(modded[1].ends_with("/mods"));
2157
2158    let vanilla = loader_args(
2159      root,
2160      &profile_with(LoaderKind::Lovely),
2161      &ctx(LaunchMode::Vanilla),
2162    )
2163    .unwrap();
2164
2165    assert_eq!(vanilla, vec!["--vanilla".to_string()]);
2166  }
2167
2168  #[test]
2169  fn godot_ml_modded_and_vanilla_shapes() {
2170    let dir = tempfile::tempdir().unwrap();
2171    let root = dir.path();
2172
2173    let modded = loader_args(
2174      root,
2175      &profile_with(LoaderKind::GodotMl),
2176      &ctx(LaunchMode::Modded),
2177    )
2178    .unwrap();
2179
2180    assert_eq!(modded[0], "--script");
2181    assert_eq!(modded[1], "res://addons/mod_loader/mod_loader_setup.gd");
2182    assert!(modded.contains(&"--mods-path".to_string()));
2183
2184    let vanilla = loader_args(
2185      root,
2186      &profile_with(LoaderKind::GodotMl),
2187      &ctx(LaunchMode::Vanilla),
2188    )
2189    .unwrap();
2190
2191    assert!(vanilla.is_empty());
2192  }
2193
2194  #[test]
2195  fn corlib_override_appends_search_flag_pair_matching_version() {
2196    let dir = tempfile::tempdir().unwrap();
2197    let root = dir.path();
2198    let core = root.join("BepInEx/core");
2199
2200    std::fs::create_dir_all(&core).unwrap();
2201    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2202    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
2203
2204    let profile = profile_with(LoaderKind::BepInEx);
2205
2206    let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2207    let v3_idx = v3
2208      .iter()
2209      .position(|a| a == "--doorstop-dll-search-override")
2210      .unwrap();
2211
2212    assert!(v3[v3_idx + 1].ends_with("/unstripped_corlib"));
2213
2214    std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2215
2216    let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2217    let v4_idx = v4
2218      .iter()
2219      .position(|a| a == "--doorstop-mono-dll-search-path-override")
2220      .unwrap();
2221
2222    assert!(v4[v4_idx + 1].ends_with("/unstripped_corlib"));
2223
2224    // BepisLoader hardcodes the v4 search-flag spelling regardless of the
2225    // detected `.doorstop_version`.
2226    std::fs::remove_file(root.join(".doorstop_version")).unwrap();
2227
2228    let bepis = loader_args(
2229      root,
2230      &profile_with(LoaderKind::BepisLoader),
2231      &ctx(LaunchMode::Modded),
2232    )
2233    .unwrap();
2234    let bepis_idx = bepis
2235      .iter()
2236      .position(|a| a == "--doorstop-mono-dll-search-path-override")
2237      .unwrap();
2238
2239    assert!(bepis[bepis_idx + 1].ends_with("/unstripped_corlib"));
2240  }
2241
2242  #[test]
2243  fn windows_steam_plan_targets_steam_with_loader_args() {
2244    let dir = tempfile::tempdir().unwrap();
2245    let root = dir.path();
2246    let core = root.join("BepInEx/core");
2247
2248    std::fs::create_dir_all(&core).unwrap();
2249    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2250
2251    let eco = Ecosystem::bundled();
2252    let mut context = ctx(LaunchMode::Modded);
2253    context.extra_args = vec!["-nolog".to_string()];
2254
2255    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2256
2257    match &plan.program {
2258      LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
2259      other => panic!("expected Steam, got {other:?}"),
2260    }
2261
2262    assert_eq!(plan.args[0], "--doorstop-enable");
2263    // User args come last.
2264    assert_eq!(plan.args.last().unwrap(), "-nolog");
2265    assert!(plan.env.is_empty());
2266    // Windows injects through the proxy DLL, so Steam needs no wrapper file.
2267    assert_eq!(plan.steam_wrapper, None);
2268  }
2269
2270  #[test]
2271  fn proton_sets_wine_dll_overrides_and_prefixes_the_preloader() {
2272    let dir = tempfile::tempdir().unwrap();
2273    let root = dir.path();
2274    let core = root.join("BepInEx/core");
2275
2276    std::fs::create_dir_all(&core).unwrap();
2277    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2278
2279    let eco = Ecosystem::bundled();
2280    let mut context = ctx(LaunchMode::Modded);
2281    context.os = HostOs::Linux;
2282    context.runtime = Runtime::Proton;
2283
2284    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2285
2286    assert_eq!(
2287      plan.env,
2288      vec![("WINEDLLOVERRIDES".to_string(), "winhttp=n,b".to_string())]
2289    );
2290    assert!(plan.args.iter().any(|a| a.starts_with("Z:")));
2291    // Proton injects through the proxy DLL too: no script, so no wrapper.
2292    assert_eq!(plan.steam_wrapper, None);
2293  }
2294
2295  #[test]
2296  fn linux_native_bepinex_runs_the_profile_script() {
2297    let dir = tempfile::tempdir().unwrap();
2298    let root = dir.path();
2299    let core = root.join("BepInEx/core");
2300
2301    std::fs::create_dir_all(&core).unwrap();
2302    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2303    std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2304
2305    let eco = Ecosystem::bundled();
2306    let mut context = ctx(LaunchMode::Modded);
2307    context.os = HostOs::Linux;
2308    context.store = StorePlatform::SteamDirect;
2309    context.runtime = Runtime::Native;
2310
2311    let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2312
2313    match &plan.program {
2314      // `exe_names` travels with the script: the caller execs the script *with*
2315      // the game binary, so it needs the same candidates `GameExe` hands over.
2316      LaunchProgram::ProfileScript { path, exe_names } => {
2317        assert!(path.ends_with("run_bepinex.sh"));
2318        assert_eq!(
2319          *exe_names,
2320          eco.game("valheim").unwrap().profile().unwrap().exe_names
2321        );
2322        assert!(!exe_names.is_empty());
2323      }
2324      other => panic!("expected ProfileScript, got {other:?}"),
2325    }
2326
2327    // A directly launched script is not the Steam wrapper case.
2328    assert_eq!(plan.steam_wrapper, None);
2329  }
2330
2331  #[test]
2332  fn macos_is_rejected() {
2333    let dir = tempfile::tempdir().unwrap();
2334    let root = dir.path();
2335    let core = root.join("BepInEx/core");
2336
2337    std::fs::create_dir_all(&core).unwrap();
2338    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2339
2340    let eco = Ecosystem::bundled();
2341    let mut context = ctx(LaunchMode::Modded);
2342    context.os = HostOs::MacOs;
2343
2344    let err = launch_plan_in(root, &eco, "valheim", &context).unwrap_err();
2345
2346    assert!(err.to_string().contains("macOS launch is not supported"));
2347
2348    // Control: the exact same directory and profile succeed once `os` is not
2349    // macOS, proving the error above comes from the macOS branch itself and
2350    // not, say, a missing BepInEx preloader fixture.
2351    context.os = HostOs::Windows;
2352
2353    assert!(launch_plan_in(root, &eco, "valheim", &context).is_ok());
2354  }
2355
2356  #[test]
2357  fn unknown_game_errors() {
2358    let dir = tempfile::tempdir().unwrap();
2359    let eco = Ecosystem::bundled();
2360
2361    let err = launch_plan_in(dir.path(), &eco, "not-a-game", &ctx(LaunchMode::Modded)).unwrap_err();
2362
2363    assert!(matches!(err, Error::UnknownGame { game } if game == "not-a-game"));
2364  }
2365
2366  #[test]
2367  fn proxy_dll_is_winmm_for_gdweave() {
2368    assert_eq!(proxy_dll(LoaderKind::GdWeave), "winmm");
2369    assert_eq!(proxy_dll(LoaderKind::BepInEx), "winhttp");
2370  }
2371
2372  #[test]
2373  fn wrapper_script_names_no_target_and_execs_the_loader() {
2374    let script = wrapper_script_contents();
2375
2376    assert!(script.starts_with("#!/bin/sh"));
2377
2378    // No target of any kind is baked in — that is what makes one script correct
2379    // for every profile, and what makes a bare launch unmodded rather than
2380    // whichever profile was current when it was written.
2381    assert!(script.contains(r#"TARGET="""#));
2382    assert!(script.contains(r#"[ -z "$TARGET" ]"#));
2383
2384    // The run-time flag is parsed, not `eval`-ed, and its value is only adopted
2385    // when it names a directory.
2386    assert!(script.contains(&format!(r#"[ "$argument" = "{WRAPPER_TARGET_FLAG}" ]"#)));
2387    assert!(script.contains(r#"[ -d "$candidate" ]"#));
2388    assert!(!script.contains("eval"));
2389
2390    // Verify all three branches are present in the correct order.
2391    let pos_server = script
2392      .find("start_server_bepinex.sh")
2393      .expect("server branch missing");
2394    let pos_run = script.find("run_bepinex.sh").expect("run branch missing");
2395    let pos_game = script
2396      .find("start_game_bepinex.sh")
2397      .expect("game branch missing");
2398
2399    assert!(pos_server < pos_run, "server branch must come before run");
2400    assert!(pos_run < pos_game, "run branch must come before game");
2401
2402    // The server branch must gate on TS_START_SERVER.
2403    assert!(script.contains("$TS_START_SERVER"));
2404
2405    // The script must have the else fallthrough and be well-formed.
2406    assert!(script.contains("else"));
2407    assert!(script.contains("fi"));
2408
2409    // The game command is forwarded, not swallowed.
2410    assert!(script.contains("\"$@\""));
2411  }
2412
2413  #[test]
2414  fn write_wrapper_script_creates_an_executable_file() {
2415    let dir = tempfile::tempdir().unwrap();
2416    let root = dir.path();
2417    let script_path = root.join("launch_wrapper.sh");
2418
2419    write_wrapper_script(&script_path).unwrap();
2420
2421    assert!(script_path.is_file());
2422
2423    #[cfg(unix)]
2424    {
2425      use std::os::unix::fs::PermissionsExt;
2426
2427      let mode = std::fs::metadata(&script_path)
2428        .unwrap()
2429        .permissions()
2430        .mode();
2431
2432      assert_eq!(mode & 0o111, 0o111);
2433    }
2434  }
2435
2436  /// The regression this exists for: a Thunderstore loader package ships its
2437  /// scripts non-executable, so a freshly installed profile cannot be launched at
2438  /// all until something sets the bit. Under Steam the failure is silent, so the
2439  /// only defense is that this runs before the wrapper `exec`s anything.
2440  #[test]
2441  #[cfg(unix)]
2442  fn ensure_loader_scripts_executable_adds_the_bit_and_reports_what_changed() {
2443    use std::os::unix::fs::PermissionsExt;
2444
2445    let dir = tempfile::tempdir().unwrap();
2446    let root = dir.path();
2447
2448    let game = root.join("start_game_bepinex.sh");
2449    let server = root.join("start_server_bepinex.sh");
2450
2451    std::fs::write(&game, b"#!/bin/sh\n").unwrap();
2452    std::fs::write(&server, b"#!/bin/sh\n").unwrap();
2453
2454    // Exactly what the package ships: readable, not executable.
2455    std::fs::set_permissions(&game, std::fs::Permissions::from_mode(0o644)).unwrap();
2456    std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o644)).unwrap();
2457
2458    let changed = ensure_loader_scripts_executable(root).unwrap();
2459
2460    assert_eq!(changed.len(), 2, "got: {changed:?}");
2461
2462    for name in ["start_game_bepinex.sh", "start_server_bepinex.sh"] {
2463      let mode = std::fs::metadata(root.join(name))
2464        .unwrap()
2465        .permissions()
2466        .mode();
2467
2468      assert_eq!(mode & 0o777, 0o755, "{name} got mode {mode:o}");
2469    }
2470
2471    // Idempotent: a second launch must not report a change, so repeated launches
2472    // do not keep rewriting modes.
2473    assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2474  }
2475
2476  /// Off Unix there is no execute bit, so a loader script is left alone and no
2477  /// change is reported for a launch to surface.
2478  #[test]
2479  #[cfg(not(unix))]
2480  fn ensure_loader_scripts_executable_changes_nothing_off_unix() {
2481    let dir = tempfile::tempdir().unwrap();
2482    let root = dir.path();
2483
2484    std::fs::write(root.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2485    std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2486
2487    assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2488  }
2489
2490  /// Read access is mirrored rather than forced to `0o755`, so a target whose
2491  /// scripts are deliberately owner-only does not become world-readable just to
2492  /// be launchable.
2493  #[test]
2494  #[cfg(unix)]
2495  fn ensure_loader_scripts_executable_mirrors_read_access() {
2496    use std::os::unix::fs::PermissionsExt;
2497
2498    let dir = tempfile::tempdir().unwrap();
2499    let root = dir.path();
2500    let script = root.join("run_bepinex.sh");
2501
2502    std::fs::write(&script, b"#!/bin/sh\n").unwrap();
2503    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o640)).unwrap();
2504
2505    ensure_loader_scripts_executable(root).unwrap();
2506
2507    let mode = std::fs::metadata(&script).unwrap().permissions().mode();
2508
2509    assert_eq!(mode & 0o777, 0o750, "got mode {mode:o}");
2510  }
2511
2512  /// A target with no loader scripts at all, such as a Proton profile or one
2513  /// whose loader injects through a proxy DLL, is not an error.
2514  #[test]
2515  fn ensure_loader_scripts_executable_ignores_a_target_with_no_scripts() {
2516    let dir = tempfile::tempdir().unwrap();
2517
2518    assert!(
2519      ensure_loader_scripts_executable(dir.path())
2520        .unwrap()
2521        .is_empty()
2522    );
2523  }
2524
2525  #[test]
2526  fn wrapper_target_args_name_the_flag_and_the_directory() {
2527    assert_eq!(
2528      wrapper_target_args(Path::new("/data/profiles/Main")),
2529      vec![
2530        WRAPPER_TARGET_FLAG.to_string(),
2531        "/data/profiles/Main".to_string()
2532      ]
2533    );
2534  }
2535
2536  // --- Executing the generated wrapper.
2537  //
2538  // The wrapper is a shell script, and the bugs that matter in one — a lost
2539  // quote, a flag leaking through to the game, an argument reordered by the
2540  // filtering loop — are invisible to assertions about its text. These tests run
2541  // `/bin/sh` against it for real and inspect the argv the chainloaded script
2542  // actually received. ---
2543
2544  /// Marks `path` executable, as [`write_wrapper_script`] does for the wrapper
2545  /// itself and as the loader scripts must be to be `exec`-ed.
2546  #[cfg(unix)]
2547  fn make_executable(path: &Path) {
2548    use std::os::unix::fs::PermissionsExt;
2549
2550    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2551  }
2552
2553  /// Writes a stand-in loader script at `path` that records the argv it was
2554  /// invoked with into `log`, one argument per line, prefixed by its own `$0`.
2555  ///
2556  /// One line per argument is what makes the assertions meaningful: a lost quote
2557  /// shows up as an argument split across two lines rather than as a string that
2558  /// merely looks similar.
2559  #[cfg(unix)]
2560  fn recording_loader(path: &Path, log: &Path) {
2561    let contents = format!(
2562      "#!/bin/sh\nprintf '%s\\n' \"$0\" > \"{log}\"\nfor argument in \"$@\"; do\n  printf '%s\\n' \"$argument\" >> \"{log}\"\ndone\n",
2563      log = log.display()
2564    );
2565
2566    std::fs::write(path, contents).unwrap();
2567    make_executable(path);
2568  }
2569
2570  /// The lines `recording_loader` wrote: the chainloaded script's own path, then
2571  /// each argument it received.
2572  #[cfg(unix)]
2573  fn recorded(log: &Path) -> Vec<String> {
2574    std::fs::read_to_string(log)
2575      .unwrap()
2576      .lines()
2577      .map(str::to_string)
2578      .collect()
2579  }
2580
2581  /// Runs `wrapper` with `args`, asserting it exited successfully.
2582  #[cfg(unix)]
2583  fn run_wrapper(wrapper: &Path, args: &[&str], server: bool) {
2584    let mut command = std::process::Command::new(wrapper);
2585
2586    command.args(args);
2587
2588    if server {
2589      command.env("TS_START_SERVER", "1");
2590    } else {
2591      command.env_remove("TS_START_SERVER");
2592    }
2593
2594    let output = command.output().unwrap();
2595
2596    assert!(
2597      output.status.success(),
2598      "wrapper failed: {}",
2599      String::from_utf8_lossy(&output.stderr)
2600    );
2601  }
2602
2603  #[cfg(unix)]
2604  #[test]
2605  fn wrapper_chainloads_the_target_given_at_run_time_and_consumes_only_the_flag() {
2606    let dir = tempfile::tempdir().unwrap();
2607    let fallback = dir.path().join("fallback");
2608    // A space in the target directory is the case that catches quoting bugs, and
2609    // it is a realistic profile name.
2610    let selected = dir.path().join("My Profile 2");
2611    let log = dir.path().join("argv.log");
2612    let wrapper = dir.path().join("steam-wrapper.sh");
2613
2614    std::fs::create_dir_all(&fallback).unwrap();
2615    std::fs::create_dir_all(&selected).unwrap();
2616    recording_loader(&selected.join("run_bepinex.sh"), &log);
2617    write_wrapper_script(&wrapper).unwrap();
2618
2619    let target = selected.to_string_lossy().to_string();
2620
2621    run_wrapper(
2622      &wrapper,
2623      &[
2624        "/games/valheim/valheim.x86_64",
2625        "--doorstop-enabled",
2626        "true",
2627        WRAPPER_TARGET_FLAG,
2628        &target,
2629        "-name",
2630        "a server with spaces",
2631      ],
2632      false,
2633    );
2634
2635    let lines = recorded(&log);
2636
2637    // The script inside the run-time target ran — not the fallback's.
2638    assert_eq!(lines[0], selected.join("run_bepinex.sh").to_string_lossy());
2639    // Every non-flag argument, in its original order, with spaces intact; the
2640    // flag and its value are gone.
2641    assert_eq!(
2642      &lines[1..],
2643      [
2644        "/games/valheim/valheim.x86_64",
2645        "--doorstop-enabled",
2646        "true",
2647        "-name",
2648        "a server with spaces",
2649      ]
2650    );
2651  }
2652
2653  #[cfg(unix)]
2654  #[test]
2655  fn wrapper_without_the_flag_launches_the_game_unmodded() {
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    // A profile sitting right beside the wrapper, complete with a loader script.
2661    // Nothing may reach for it: no flag means no mods, not "whichever profile
2662    // happens to be there".
2663    let unrequested = dir.path().join("profile");
2664    let unrequested_log = dir.path().join("must-not-run.log");
2665
2666    std::fs::create_dir_all(&unrequested).unwrap();
2667    recording_loader(&unrequested.join("run_bepinex.sh"), &unrequested_log);
2668    recording_loader(&game_exe, &log);
2669    write_wrapper_script(&wrapper).unwrap();
2670
2671    // A launch straight from Steam, with no manager appending anything: exactly
2672    // what `%command%` expands to on its own.
2673    run_wrapper(&wrapper, &[&game_exe.to_string_lossy()], false);
2674
2675    assert!(
2676      !unrequested_log.exists(),
2677      "a bare launch must not load any profile's mods"
2678    );
2679
2680    let lines = recorded(&log);
2681
2682    assert_eq!(lines[0], game_exe.to_string_lossy());
2683    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2684  }
2685
2686  #[cfg(unix)]
2687  #[test]
2688  fn wrapper_launches_unmodded_when_the_flags_value_is_not_a_directory() {
2689    let dir = tempfile::tempdir().unwrap();
2690    let log = dir.path().join("argv.log");
2691    let wrapper = dir.path().join("steam-wrapper.sh");
2692    let game_exe = dir.path().join("valheim.x86_64");
2693
2694    recording_loader(&game_exe, &log);
2695    write_wrapper_script(&wrapper).unwrap();
2696
2697    // A profile deleted between the plan and the launch must not defeat the
2698    // launch, and must not be chainloaded as if it existed.
2699    let missing = dir.path().join("deleted-profile");
2700
2701    run_wrapper(
2702      &wrapper,
2703      &[
2704        &game_exe.to_string_lossy(),
2705        WRAPPER_TARGET_FLAG,
2706        &missing.to_string_lossy(),
2707      ],
2708      false,
2709    );
2710
2711    let lines = recorded(&log);
2712
2713    // The flag is consumed even when its value is rejected: the game must never
2714    // see it.
2715    assert_eq!(lines[0], game_exe.to_string_lossy());
2716    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2717  }
2718
2719  #[cfg(unix)]
2720  #[test]
2721  fn wrapper_consumes_a_trailing_flag_that_has_no_value() {
2722    let dir = tempfile::tempdir().unwrap();
2723    let log = dir.path().join("argv.log");
2724    let wrapper = dir.path().join("steam-wrapper.sh");
2725    let game_exe = dir.path().join("valheim.x86_64");
2726
2727    recording_loader(&game_exe, &log);
2728    write_wrapper_script(&wrapper).unwrap();
2729
2730    run_wrapper(
2731      &wrapper,
2732      &[&game_exe.to_string_lossy(), WRAPPER_TARGET_FLAG],
2733      false,
2734    );
2735
2736    let lines = recorded(&log);
2737
2738    // A valueless flag names no target, so this is a vanilla launch — and the
2739    // dangling flag is still swallowed rather than handed to the game.
2740    assert_eq!(lines[0], game_exe.to_string_lossy());
2741    assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2742  }
2743
2744  #[cfg(unix)]
2745  #[test]
2746  fn wrapper_execs_the_game_directly_when_the_target_ships_no_loader_script() {
2747    let dir = tempfile::tempdir().unwrap();
2748    let selected = dir.path().join("profile");
2749    let log = dir.path().join("argv.log");
2750    let wrapper = dir.path().join("steam-wrapper.sh");
2751    // Stand in for the game binary Steam puts at the head of `%command%`.
2752    let game_exe = dir.path().join("valheim.x86_64");
2753
2754    std::fs::create_dir_all(&selected).unwrap();
2755    recording_loader(&game_exe, &log);
2756    write_wrapper_script(&wrapper).unwrap();
2757
2758    run_wrapper(
2759      &wrapper,
2760      &[
2761        &game_exe.to_string_lossy(),
2762        WRAPPER_TARGET_FLAG,
2763        &selected.to_string_lossy(),
2764        "-window-mode",
2765      ],
2766      false,
2767    );
2768
2769    let lines = recorded(&log);
2770
2771    // `exec "$@"` reached the game itself, and the flag still did not survive
2772    // into its argv.
2773    assert_eq!(lines[0], game_exe.to_string_lossy());
2774    assert_eq!(&lines[1..], ["-window-mode"]);
2775  }
2776
2777  #[cfg(unix)]
2778  #[test]
2779  fn wrapper_selects_the_server_script_only_when_ts_start_server_is_set() {
2780    let dir = tempfile::tempdir().unwrap();
2781    let target = dir.path().join("target");
2782    let server_log = dir.path().join("server.log");
2783    let game_log = dir.path().join("game.log");
2784    let wrapper = dir.path().join("steam-wrapper.sh");
2785
2786    std::fs::create_dir_all(&target).unwrap();
2787    // Both scripts present, which is the only way the gate is observable: the
2788    // server script has the higher precedence in `LOADER_SCRIPTS`, so without
2789    // the gate it would always win.
2790    recording_loader(&target.join(SERVER_SCRIPT), &server_log);
2791    recording_loader(&target.join("run_bepinex.sh"), &game_log);
2792    write_wrapper_script(&wrapper).unwrap();
2793
2794    let selected = target.to_string_lossy().to_string();
2795    let argv = [
2796      "/games/valheim/valheim.x86_64",
2797      WRAPPER_TARGET_FLAG,
2798      &selected,
2799    ];
2800
2801    run_wrapper(&wrapper, &argv, false);
2802
2803    assert!(
2804      !server_log.exists(),
2805      "the server script must not run for a game instance"
2806    );
2807    assert_eq!(
2808      recorded(&game_log)[0],
2809      target.join("run_bepinex.sh").to_string_lossy()
2810    );
2811
2812    run_wrapper(&wrapper, &argv, true);
2813
2814    assert_eq!(
2815      recorded(&server_log)[0],
2816      target.join(SERVER_SCRIPT).to_string_lossy()
2817    );
2818  }
2819
2820  #[test]
2821  fn steam_launch_options_are_only_the_wrapper_and_command_placeholder() {
2822    let options = steam_launch_options(Path::new("/data/launch_wrapper.sh"));
2823
2824    // Byte-for-byte what r2modman's `WrapperArguments.ts` emits: a quoted path
2825    // and `%command%`, and nothing else.
2826    assert_eq!(options, r#""/data/launch_wrapper.sh" %command%"#);
2827
2828    // No Wine setting rides along. This string is only ever produced for a Linux
2829    // native launch, where nothing in the path touches Wine, and it could not buy
2830    // Proton coverage anyway — see `steam_launch_options`'s doc comment.
2831    assert!(!options.contains("WINEDLLOVERRIDES"));
2832    assert!(!options.contains("winhttp"));
2833
2834    // A space in the script path stays inside the quotes.
2835    assert_eq!(
2836      steam_launch_options(Path::new("/data/My Games/wrapper.sh")),
2837      r#""/data/My Games/wrapper.sh" %command%"#
2838    );
2839
2840    // A Windows path is written with `/` separators.
2841    assert_eq!(
2842      steam_launch_options(Path::new(r"C:\Users\me\launch_wrapper.sh")),
2843      r#""C:/Users/me/launch_wrapper.sh" %command%"#
2844    );
2845  }
2846
2847  #[test]
2848  fn stage_destination_routes_per_loader() {
2849    let game = Path::new("/game");
2850
2851    assert_eq!(
2852      stage_destination(LoaderKind::BepInEx, "winhttp.dll", game, None),
2853      Some(PathBuf::from("/game/winhttp.dll"))
2854    );
2855    // mods.yml is manager state, never staged.
2856    assert_eq!(
2857      stage_destination(LoaderKind::BepInEx, "mods.yml", game, None),
2858      None
2859    );
2860
2861    // Shimloader: only its three files, into the UE binaries folder.
2862    assert_eq!(
2863      stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, Some("Palworld")),
2864      Some(PathBuf::from("/game/Palworld/Binaries/Win64/ue4ss.dll"))
2865    );
2866    assert_eq!(
2867      stage_destination(LoaderKind::Shimloader, "other.dll", game, Some("Palworld")),
2868      None
2869    );
2870    // No `dataFolderName` at all => nothing is staged.
2871    assert_eq!(
2872      stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, None),
2873      None
2874    );
2875
2876    // Rivet: only version.dll, into Release.
2877    assert_eq!(
2878      stage_destination(LoaderKind::Rivet, "version.dll", game, None),
2879      Some(PathBuf::from("/game/Release/version.dll"))
2880    );
2881    assert_eq!(
2882      stage_destination(LoaderKind::Rivet, "winhttp.dll", game, None),
2883      None
2884    );
2885  }
2886
2887  #[test]
2888  fn stage_for_launch_copies_root_files_only() {
2889    let dir = tempfile::tempdir().unwrap();
2890    let target = dir.path().join("target");
2891    let game_dir = dir.path().join("game");
2892
2893    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
2894    std::fs::create_dir_all(&game_dir).unwrap();
2895    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2896    std::fs::write(target.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
2897    std::fs::write(target.join("mods.yml"), b"[]").unwrap();
2898    std::fs::write(target.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
2899
2900    let eco = Ecosystem::bundled();
2901    let written = stage_for_launch_in(
2902      &target,
2903      &eco,
2904      "valheim",
2905      &game_dir,
2906      &ctx(LaunchMode::Modded),
2907    )
2908    .unwrap();
2909
2910    assert!(game_dir.join("winhttp.dll").exists());
2911    assert!(game_dir.join("doorstop_config.ini").exists());
2912    // Manager state and subdirectories are not staged.
2913    assert!(!game_dir.join("mods.yml").exists());
2914    assert!(!game_dir.join("BepInEx").exists());
2915    assert_eq!(written.len(), 2);
2916
2917    // The returned paths are exactly what was written, and sorted.
2918    assert!(written.contains(&game_dir.join("winhttp.dll")));
2919    assert!(written.contains(&game_dir.join("doorstop_config.ini")));
2920
2921    let mut sorted = written.clone();
2922    sorted.sort();
2923
2924    assert_eq!(written, sorted);
2925  }
2926
2927  #[test]
2928  fn stage_for_launch_stages_shimloader_files_into_nested_binaries_dir() {
2929    // Palworld is a bundled Shimloader game (`dataFolderName` = "Pal"), so this
2930    // exercises `stage_for_launch_in` end to end through a nested destination
2931    // that does not exist yet, forcing `stage_one_file`'s `create_dir_all`.
2932    let dir = tempfile::tempdir().unwrap();
2933    let target = dir.path().join("target");
2934    let game_dir = dir.path().join("game");
2935
2936    std::fs::create_dir_all(&target).unwrap();
2937    std::fs::create_dir_all(&game_dir).unwrap();
2938    std::fs::write(target.join("ue4ss.dll"), b"loader").unwrap();
2939    std::fs::write(target.join("dwmapi.dll"), b"proxy").unwrap();
2940    std::fs::write(target.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
2941    std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2942
2943    let eco = Ecosystem::bundled();
2944    let written = stage_for_launch_in(
2945      &target,
2946      &eco,
2947      "palworld",
2948      &game_dir,
2949      &ctx(LaunchMode::Modded),
2950    )
2951    .unwrap();
2952
2953    let nested = game_dir.join("Pal").join("Binaries").join("Win64");
2954
2955    assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
2956    assert!(nested.join("dwmapi.dll").exists());
2957    assert!(nested.join("ue4ss-settings.ini").exists());
2958    // Every other root file is skipped for Shimloader.
2959    assert!(!game_dir.join("other.dll").exists());
2960    assert!(!nested.join("other.dll").exists());
2961
2962    assert_eq!(written.len(), 3);
2963    assert!(written.contains(&nested.join("ue4ss.dll")));
2964    assert!(written.contains(&nested.join("dwmapi.dll")));
2965    assert!(written.contains(&nested.join("ue4ss-settings.ini")));
2966
2967    let mut sorted = written.clone();
2968    sorted.sort();
2969
2970    assert_eq!(written, sorted);
2971  }
2972
2973  #[test]
2974  fn stage_for_launch_stages_rivet_version_dll_into_release_dir() {
2975    // Scrap Mechanic is a bundled Rivet game, so this exercises
2976    // `stage_for_launch_in` end to end through the `<game>/Release` destination,
2977    // forcing `stage_one_file`'s `create_dir_all` for that nested directory too.
2978    let dir = tempfile::tempdir().unwrap();
2979    let target = dir.path().join("target");
2980    let game_dir = dir.path().join("game");
2981
2982    std::fs::create_dir_all(&target).unwrap();
2983    std::fs::create_dir_all(&game_dir).unwrap();
2984    std::fs::write(target.join("version.dll"), b"rivet-loader").unwrap();
2985    std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2986
2987    let eco = Ecosystem::bundled();
2988    let written = stage_for_launch_in(
2989      &target,
2990      &eco,
2991      "scrap-mechanic",
2992      &game_dir,
2993      &ctx(LaunchMode::Modded),
2994    )
2995    .unwrap();
2996
2997    let dest = game_dir.join("Release").join("version.dll");
2998
2999    assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3000    // Every other root file is skipped for Rivet.
3001    assert!(!game_dir.join("other.dll").exists());
3002    assert!(!game_dir.join("Release").join("other.dll").exists());
3003
3004    assert_eq!(written, vec![dest]);
3005  }
3006
3007  #[test]
3008  fn stage_for_launch_skips_linux_native_bepinex() {
3009    let dir = tempfile::tempdir().unwrap();
3010    let target = dir.path().join("target");
3011    let game_dir = dir.path().join("game");
3012
3013    std::fs::create_dir_all(&target).unwrap();
3014    std::fs::create_dir_all(&game_dir).unwrap();
3015    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
3016
3017    let eco = Ecosystem::bundled();
3018    let mut context = ctx(LaunchMode::Modded);
3019    context.os = HostOs::Linux;
3020    context.runtime = Runtime::Native;
3021
3022    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3023
3024    assert!(written.is_empty());
3025    assert!(!game_dir.join("winhttp.dll").exists());
3026  }
3027
3028  #[cfg(unix)]
3029  #[test]
3030  fn stage_for_launch_refuses_to_write_through_a_symlink() {
3031    use std::os::unix::fs::symlink;
3032
3033    let dir = tempfile::tempdir().unwrap();
3034    let target = dir.path().join("target");
3035    let game_dir = dir.path().join("game");
3036    let outside = dir.path().join("secret.dll");
3037
3038    std::fs::create_dir_all(&target).unwrap();
3039    std::fs::create_dir_all(&game_dir).unwrap();
3040    std::fs::write(&outside, b"original").unwrap();
3041    std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
3042    symlink(&outside, game_dir.join("winhttp.dll")).unwrap();
3043
3044    let eco = Ecosystem::bundled();
3045
3046    assert!(
3047      stage_for_launch_in(
3048        &target,
3049        &eco,
3050        "valheim",
3051        &game_dir,
3052        &ctx(LaunchMode::Modded)
3053      )
3054      .is_err()
3055    );
3056    assert_eq!(std::fs::read(&outside).unwrap(), b"original");
3057  }
3058
3059  #[test]
3060  fn stage_for_launch_in_place_leaves_root_files_byte_for_byte_untouched() {
3061    // `target_dir == game_dir` is the layout a consumer with no r2modman
3062    // profile uses when it installs mods straight into the game directory
3063    // (see `stage_for_launch_in`'s doc comment). Before the fix, `stage_one_file`
3064    // called `std::fs::copy(path, path)` here, which truncates the destination
3065    // to zero bytes: `std::fs::copy` opens the destination with `O_TRUNC`
3066    // before it ever reads the source.
3067    let dir = tempfile::tempdir().unwrap();
3068    let root = dir.path().join("game");
3069
3070    std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
3071
3072    let winhttp_contents = b"MZ-fake-proxy-dll-18b";
3073    let ini_contents = b"[UnityDoorstop]\nenabled=true\n";
3074
3075    std::fs::write(root.join("winhttp.dll"), winhttp_contents).unwrap();
3076    std::fs::write(root.join("doorstop_config.ini"), ini_contents).unwrap();
3077    std::fs::write(root.join("mods.yml"), b"[]").unwrap();
3078    std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
3079
3080    let eco = Ecosystem::bundled();
3081    let written =
3082      stage_for_launch_in(&root, &eco, "valheim", &root, &ctx(LaunchMode::Modded)).unwrap();
3083
3084    // Contents, not mere existence — a zero-byte file still "exists", which is
3085    // precisely how the truncation bug hid behind every prior test.
3086    assert_eq!(
3087      std::fs::read(root.join("winhttp.dll")).unwrap(),
3088      winhttp_contents
3089    );
3090    assert_eq!(
3091      std::fs::read(root.join("doorstop_config.ini")).unwrap(),
3092      ini_contents
3093    );
3094
3095    // Neither file was actually written by this call — both were already
3096    // correctly in place — so neither is reported as written. See
3097    // `stage_for_launch_in`'s doc comment: over-reporting here would let a
3098    // caller that deletes everything in this list destroy a file it never
3099    // created.
3100    assert!(written.is_empty());
3101  }
3102
3103  #[test]
3104  fn stage_for_launch_in_place_survives_a_dot_dot_aliased_game_dir() {
3105    // `target/BepInEx/..` is not lexically equal to `target`, but resolves to
3106    // the exact same directory. The identity check must recognize this via
3107    // canonicalization rather than string comparison, or this differently
3108    // spelled `game_dir` would reintroduce the truncation bug.
3109    let dir = tempfile::tempdir().unwrap();
3110    let target = dir.path().join("target");
3111
3112    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3113
3114    let contents = b"proxy-bytes-not-truncated";
3115
3116    std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3117
3118    let aliased_game_dir = target.join("BepInEx").join("..");
3119    let eco = Ecosystem::bundled();
3120
3121    let written = stage_for_launch_in(
3122      &target,
3123      &eco,
3124      "valheim",
3125      &aliased_game_dir,
3126      &ctx(LaunchMode::Modded),
3127    )
3128    .unwrap();
3129
3130    assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3131    assert!(written.is_empty());
3132  }
3133
3134  #[cfg(unix)]
3135  #[test]
3136  fn stage_for_launch_in_place_survives_a_symlinked_game_dir() {
3137    use std::os::unix::fs::symlink;
3138
3139    // A `game_dir` reached through a symlinked directory must alias `target_dir`
3140    // exactly as the `..`-relative case above does, even though it is not
3141    // string-comparable to `target_dir` at all.
3142    let dir = tempfile::tempdir().unwrap();
3143    let target = dir.path().join("target");
3144    let link = dir.path().join("game-link");
3145
3146    std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3147
3148    let contents = b"proxy-bytes-via-symlink";
3149
3150    std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3151    symlink(&target, &link).unwrap();
3152
3153    let eco = Ecosystem::bundled();
3154    let written =
3155      stage_for_launch_in(&target, &eco, "valheim", &link, &ctx(LaunchMode::Modded)).unwrap();
3156
3157    assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3158    assert!(written.is_empty());
3159  }
3160
3161  #[test]
3162  fn stage_for_launch_in_place_still_copies_shimloader_files_to_a_distinct_destination() {
3163    // Palworld is a bundled Shimloader game (`dataFolderName` = "Pal"). Even
3164    // with `target_dir == game_dir`, Shimloader's destination
3165    // (`<game_dir>/Pal/Binaries/Win64/<file>`) genuinely differs from its
3166    // source, so the identity check must not skip these — only a destination
3167    // identical to its source is exempted from copying.
3168    let dir = tempfile::tempdir().unwrap();
3169    let root = dir.path().join("game");
3170
3171    std::fs::create_dir_all(&root).unwrap();
3172    std::fs::write(root.join("ue4ss.dll"), b"loader").unwrap();
3173    std::fs::write(root.join("dwmapi.dll"), b"proxy").unwrap();
3174    std::fs::write(root.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
3175
3176    let eco = Ecosystem::bundled();
3177    let written =
3178      stage_for_launch_in(&root, &eco, "palworld", &root, &ctx(LaunchMode::Modded)).unwrap();
3179
3180    let nested = root.join("Pal").join("Binaries").join("Win64");
3181
3182    assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
3183    assert_eq!(std::fs::read(nested.join("dwmapi.dll")).unwrap(), b"proxy");
3184    // The source files are untouched by their own copy, and still present at
3185    // the target root (which is also `game_dir` here).
3186    assert_eq!(std::fs::read(root.join("ue4ss.dll")).unwrap(), b"loader");
3187
3188    assert_eq!(written.len(), 3);
3189    assert!(written.contains(&nested.join("ue4ss.dll")));
3190    assert!(written.contains(&nested.join("dwmapi.dll")));
3191    assert!(written.contains(&nested.join("ue4ss-settings.ini")));
3192  }
3193
3194  #[test]
3195  fn stage_for_launch_in_place_still_copies_rivet_version_dll_to_a_distinct_destination() {
3196    // Scrap Mechanic is a bundled Rivet game. Its destination
3197    // (`<game_dir>/Release/version.dll`) differs from its source even when
3198    // `target_dir == game_dir`, so it must still be copied rather than skipped.
3199    let dir = tempfile::tempdir().unwrap();
3200    let root = dir.path().join("game");
3201
3202    std::fs::create_dir_all(&root).unwrap();
3203    std::fs::write(root.join("version.dll"), b"rivet-loader").unwrap();
3204
3205    let eco = Ecosystem::bundled();
3206    let written = stage_for_launch_in(
3207      &root,
3208      &eco,
3209      "scrap-mechanic",
3210      &root,
3211      &ctx(LaunchMode::Modded),
3212    )
3213    .unwrap();
3214
3215    let dest = root.join("Release").join("version.dll");
3216
3217    assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3218    assert_eq!(
3219      std::fs::read(root.join("version.dll")).unwrap(),
3220      b"rivet-loader"
3221    );
3222    assert_eq!(written, vec![dest]);
3223  }
3224
3225  #[test]
3226  fn stage_for_launch_wraps_stage_for_launch_in_over_a_layout_profile() {
3227    let dir = tempfile::tempdir().unwrap();
3228    let base = dir.path().join("base");
3229    let game_dir = dir.path().join("game");
3230
3231    let profile_dir = crate::profile::layout::create(&base, "valheim", "Main").unwrap();
3232    let core = profile_dir.join("BepInEx/core");
3233
3234    std::fs::create_dir_all(&core).unwrap();
3235    std::fs::create_dir_all(&game_dir).unwrap();
3236    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3237    std::fs::write(profile_dir.join("winhttp.dll"), b"proxy").unwrap();
3238    std::fs::write(profile_dir.join("mods.yml"), b"[]").unwrap();
3239
3240    let eco = Ecosystem::bundled();
3241    let written = stage_for_launch(
3242      &base,
3243      "valheim",
3244      "Main",
3245      &eco,
3246      &game_dir,
3247      &ctx(LaunchMode::Modded),
3248    )
3249    .unwrap();
3250
3251    assert!(game_dir.join("winhttp.dll").exists());
3252    assert!(!game_dir.join("mods.yml").exists());
3253    assert_eq!(written, vec![game_dir.join("winhttp.dll")]);
3254  }
3255
3256  /// A Linux native `LaunchContext` for a directly executed (non-Steam) game.
3257  fn linux_native(mode: LaunchMode) -> LaunchContext {
3258    let mut context = ctx(mode);
3259
3260    context.os = HostOs::Linux;
3261    context.store = StorePlatform::SteamDirect;
3262    context.runtime = Runtime::Native;
3263
3264    context
3265  }
3266
3267  /// A target that looks like a real Linux BepInEx install, minus any loader
3268  /// script: preloader, proxy DLL, and Doorstop ini.
3269  fn linux_bepinex_target(root: &Path) {
3270    let core = root.join("BepInEx/core");
3271
3272    std::fs::create_dir_all(&core).unwrap();
3273    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3274    std::fs::write(root.join("winhttp.dll"), b"proxy").unwrap();
3275    std::fs::write(root.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
3276  }
3277
3278  #[test]
3279  fn linux_native_modded_selects_any_shipped_script_not_only_run_bepinex() {
3280    let dir = tempfile::tempdir().unwrap();
3281    let target = dir.path().join("target");
3282    let game_dir = dir.path().join("game");
3283
3284    linux_bepinex_target(&target);
3285    std::fs::create_dir_all(&game_dir).unwrap();
3286    // This package ships `start_game_bepinex.sh`; there is no `run_bepinex.sh`.
3287    std::fs::write(target.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3288
3289    let eco = Ecosystem::bundled();
3290    let context = linux_native(LaunchMode::Modded);
3291
3292    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3293
3294    match &plan.program {
3295      LaunchProgram::ProfileScript { path, .. } => {
3296        assert!(path.ends_with("start_game_bepinex.sh"))
3297      }
3298      // Falling through to `GameExe` here is the silent-vanilla bug: Doorstop
3299      // argv nothing reads, and no proxy staged into the game directory.
3300      other => panic!("expected ProfileScript, got {other:?}"),
3301    }
3302
3303    // Staging must agree with the plan rather than decide independently.
3304    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3305
3306    assert!(written.is_empty());
3307    assert!(!game_dir.join("winhttp.dll").exists());
3308  }
3309
3310  #[test]
3311  fn server_instance_prefers_the_server_script_and_a_game_instance_ignores_it() {
3312    let dir = tempfile::tempdir().unwrap();
3313    let all_three = dir.path().join("all-three");
3314    let server_only = dir.path().join("server-only");
3315
3316    linux_bepinex_target(&all_three);
3317    linux_bepinex_target(&server_only);
3318
3319    for name in LOADER_SCRIPTS {
3320      std::fs::write(all_three.join(name), b"#!/bin/sh\n").unwrap();
3321    }
3322
3323    std::fs::write(server_only.join(SERVER_SCRIPT), b"#!/bin/sh\n").unwrap();
3324
3325    let context = linux_native(LaunchMode::Modded);
3326    let game_profile = profile_with(LoaderKind::BepInEx);
3327    let mut server_profile = profile_with(LoaderKind::BepInEx);
3328
3329    server_profile.instance_type = InstanceType::Server;
3330
3331    let server = resolve_program(
3332      &script_injection(
3333        &all_three,
3334        &LaunchFacts::read(&all_three),
3335        &server_profile,
3336        &context,
3337      ),
3338      &all_three,
3339      &server_profile,
3340      &context,
3341    )
3342    .unwrap();
3343
3344    match &server {
3345      LaunchProgram::ProfileScript { path, .. } => {
3346        assert!(path.ends_with("start_server_bepinex.sh"))
3347      }
3348      other => panic!("expected ProfileScript, got {other:?}"),
3349    }
3350
3351    // A game instance skips the server script even when it is present and first
3352    // in precedence — exec'ing it would start a dedicated server.
3353    let game = resolve_program(
3354      &script_injection(
3355        &all_three,
3356        &LaunchFacts::read(&all_three),
3357        &game_profile,
3358        &context,
3359      ),
3360      &all_three,
3361      &game_profile,
3362      &context,
3363    )
3364    .unwrap();
3365
3366    match &game {
3367      LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3368      other => panic!("expected ProfileScript, got {other:?}"),
3369    }
3370
3371    // With only the server script on disk, a game instance has no script at all.
3372    let err = resolve_program(
3373      &script_injection(
3374        &server_only,
3375        &LaunchFacts::read(&server_only),
3376        &game_profile,
3377        &context,
3378      ),
3379      &server_only,
3380      &game_profile,
3381      &context,
3382    )
3383    .unwrap_err();
3384
3385    assert!(err.to_string().contains("run_bepinex.sh"));
3386  }
3387
3388  #[test]
3389  fn modded_script_injection_without_a_script_errors_but_vanilla_falls_through() {
3390    let dir = tempfile::tempdir().unwrap();
3391    let target = dir.path().join("target");
3392
3393    linux_bepinex_target(&target);
3394
3395    let eco = Ecosystem::bundled();
3396    let modded = linux_native(LaunchMode::Modded);
3397
3398    let err = launch_plan_in(&target, &eco, "valheim", &modded).unwrap_err();
3399    let message = err.to_string();
3400
3401    assert!(message.contains("run_bepinex.sh"), "{message}");
3402    assert!(message.contains("start_game_bepinex.sh"), "{message}");
3403    assert!(message.contains(&target.display().to_string()), "{message}");
3404
3405    // Vanilla asks for no injection at all, so a missing injector is not a
3406    // failure: the game binary runs with the loader's disable flag.
3407    let vanilla =
3408      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3409
3410    assert!(matches!(vanilla.program, LaunchProgram::GameExe { .. }));
3411    assert_eq!(
3412      vanilla.args,
3413      vec!["--doorstop-enable".to_string(), "false".to_string()]
3414    );
3415  }
3416
3417  #[test]
3418  fn linux_native_steam_launches_steam_and_reports_the_wrapper_requirement() {
3419    let dir = tempfile::tempdir().unwrap();
3420    let target = dir.path().join("target");
3421    let game_dir = dir.path().join("game");
3422    let script_path = dir.path().join("launch_wrapper.sh");
3423
3424    linux_bepinex_target(&target);
3425    std::fs::create_dir_all(&game_dir).unwrap();
3426    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3427
3428    let eco = Ecosystem::bundled();
3429    let mut context = linux_native(LaunchMode::Modded);
3430
3431    context.store = StorePlatform::Steam;
3432
3433    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3434
3435    // Steam cannot be handed a script as its program: it takes `-applaunch`.
3436    match &plan.program {
3437      LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
3438      other => panic!("expected Steam, got {other:?}"),
3439    }
3440
3441    // The wrapper requirement is discoverable from the plan itself, and carries
3442    // everything the two wrapper functions need — no reimplementing the rule and
3443    // no second ecosystem lookup.
3444    let wrapper = plan.steam_wrapper.clone().expect("wrapper requirement");
3445
3446    assert_eq!(wrapper.target_dir, target);
3447    assert_eq!(wrapper.loader, LoaderKind::BepInEx);
3448
3449    write_wrapper_script(&script_path).unwrap();
3450
3451    let options = steam_launch_options(&script_path);
3452
3453    assert_options_name_script(&options, &script_path);
3454    assert!(!options.contains("WINEDLLOVERRIDES"));
3455    assert!(
3456      std::fs::read_to_string(&script_path)
3457        .unwrap()
3458        .contains("run_bepinex.sh")
3459    );
3460
3461    // The plan already carries the target flag, so a caller that spawns it
3462    // verbatim reaches this target through a wrapper written for any other one.
3463    assert!(
3464      plan
3465        .args
3466        .windows(2)
3467        .any(|pair| pair == wrapper_target_args(&target).as_slice()),
3468      "plan args must carry the wrapper target flag: {:?}",
3469      plan.args
3470    );
3471
3472    // Injection is still script-based, so the game directory stays untouched.
3473    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3474
3475    assert!(written.is_empty());
3476    assert!(!game_dir.join("winhttp.dll").exists());
3477  }
3478
3479  #[test]
3480  fn stage_for_launch_rejects_macos() {
3481    let dir = tempfile::tempdir().unwrap();
3482    let target = dir.path().join("target");
3483    let game_dir = dir.path().join("game");
3484
3485    linux_bepinex_target(&target);
3486    std::fs::create_dir_all(&game_dir).unwrap();
3487
3488    let eco = Ecosystem::bundled();
3489    let mut context = ctx(LaunchMode::Modded);
3490
3491    context.os = HostOs::MacOs;
3492
3493    let err = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap_err();
3494
3495    assert!(err.to_string().contains("macOS launch is not supported"));
3496    // Nothing was written: `launch_plan_in` refuses macOS, so staging must not
3497    // dirty the game directory on its behalf.
3498    assert_eq!(std::fs::read_dir(&game_dir).unwrap().count(), 0);
3499
3500    // Control: the same target and game directory stage fine once `os` is not
3501    // macOS, proving the error comes from the macOS branch itself.
3502    context.os = HostOs::Windows;
3503
3504    let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3505
3506    assert_eq!(written.len(), 2);
3507    assert!(game_dir.join("winhttp.dll").exists());
3508  }
3509
3510  #[test]
3511  fn only_a_wrapper_bound_plan_carries_the_target_flag() {
3512    let dir = tempfile::tempdir().unwrap();
3513    let target = dir.path().join("target");
3514
3515    linux_bepinex_target(&target);
3516    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3517
3518    let eco = Ecosystem::bundled();
3519
3520    // Linux native, but launched by executing the script directly: no wrapper
3521    // stands between the caller and the loader, so the flag would be a stray
3522    // argument the game has to tolerate.
3523    let direct =
3524      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3525
3526    assert_eq!(direct.steam_wrapper, None);
3527    assert!(!direct.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3528
3529    // Steam, but injecting through the proxy DLL rather than a script: still no
3530    // wrapper, still no flag.
3531    let mut proton = linux_native(LaunchMode::Modded);
3532
3533    proton.store = StorePlatform::Steam;
3534    proton.runtime = Runtime::Proton;
3535
3536    let proton_plan = launch_plan_in(&target, &eco, "valheim", &proton).unwrap();
3537
3538    assert_eq!(proton_plan.steam_wrapper, None);
3539    assert!(!proton_plan.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3540  }
3541
3542  #[test]
3543  fn wrapper_branches_are_generated_from_the_shared_script_list() {
3544    let script = wrapper_script_contents();
3545
3546    let mut previous = 0;
3547
3548    for name in LOADER_SCRIPTS {
3549      let position = script
3550        .find(&format!("[ -f \"$TARGET/{name}\" ]"))
3551        .unwrap_or_else(|| panic!("wrapper is missing a branch for {name}"));
3552
3553      assert!(position >= previous, "{name} is out of precedence order");
3554
3555      previous = position;
3556    }
3557  }
3558
3559  // --- Script-path Doorstop spelling (v3-detected target injected via a loader
3560  // script must still use v4 flags, because the script itself only understands
3561  // v4 spellings; see `doorstop_args`'s doc comment) ---
3562
3563  #[test]
3564  fn linux_native_script_present_vanilla_runs_the_script_with_v4_enabled_spelling() {
3565    let dir = tempfile::tempdir().unwrap();
3566    let target = dir.path().join("target");
3567
3568    linux_bepinex_target(&target);
3569    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3570    // No `.doorstop_version` file: `doorstop_version` defaults to 3, but the
3571    // script only recognizes the v4 spelling — see `doorstop_args`'s doc comment.
3572
3573    let eco = Ecosystem::bundled();
3574    let plan =
3575      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3576
3577    // Vanilla still runs the script: the script itself honours the disable
3578    // flag, so there is no reason to fall back to the bare game binary.
3579    match &plan.program {
3580      LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3581      other => panic!("expected ProfileScript, got {other:?}"),
3582    }
3583
3584    assert_eq!(
3585      plan.args,
3586      vec!["--doorstop-enabled".to_string(), "false".to_string()]
3587    );
3588  }
3589
3590  #[test]
3591  fn linux_native_script_present_modded_uses_v4_target_assembly_spelling() {
3592    let dir = tempfile::tempdir().unwrap();
3593    let target = dir.path().join("target");
3594
3595    linux_bepinex_target(&target);
3596    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3597    // No `.doorstop_version` file here either: same v3-defaults-but-script-wants-v4
3598    // situation as the vanilla case above.
3599
3600    let eco = Ecosystem::bundled();
3601    let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3602
3603    assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3604    assert_eq!(plan.args[0], "--doorstop-enabled");
3605    assert_eq!(plan.args[1], "true");
3606    assert_eq!(plan.args[2], "--doorstop-target-assembly");
3607    assert!(plan.args[3].ends_with("BepInEx/core/BepInEx.Preloader.dll"));
3608  }
3609
3610  #[test]
3611  fn linux_native_script_present_v3_detected_corlib_override_uses_v4_search_flag_spelling() {
3612    // The third of the three doorstop-flag pairs, and the one the fix's other
3613    // script-path tests don't touch: `linux_bepinex_target` never creates
3614    // `unstripped_corlib`, so without this test the corlib search-path flag on
3615    // the script-injected + v3-detected path is only correct by inference from
3616    // the shared `if v4` tuple in `doorstop_args`, not by a direct assertion.
3617    let dir = tempfile::tempdir().unwrap();
3618    let target = dir.path().join("target");
3619
3620    linux_bepinex_target(&target);
3621    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3622    std::fs::create_dir_all(target.join("unstripped_corlib")).unwrap();
3623    // No `.doorstop_version` file: detected version defaults to v3, but the
3624    // script on disk forces the v4 spellings — see `doorstop_args`'s doc comment.
3625
3626    let eco = Ecosystem::bundled();
3627    let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3628
3629    assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3630
3631    let idx = plan
3632      .args
3633      .iter()
3634      .position(|a| a == "--doorstop-mono-dll-search-path-override")
3635      .expect("v4 corlib search-path flag missing");
3636
3637    assert!(plan.args[idx + 1].ends_with("/unstripped_corlib"));
3638    assert!(
3639      !plan
3640        .args
3641        .iter()
3642        .any(|a| a == "--doorstop-dll-search-override"),
3643      "v3 corlib search-path spelling must not appear on the script-injected path: {:?}",
3644      plan.args
3645    );
3646  }
3647
3648  #[test]
3649  fn linux_native_script_present_v4_detected_target_is_unchanged() {
3650    let dir = tempfile::tempdir().unwrap();
3651    let target = dir.path().join("target");
3652
3653    linux_bepinex_target(&target);
3654    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3655    std::fs::write(target.join(".doorstop_version"), "4.0.0").unwrap();
3656
3657    let eco = Ecosystem::bundled();
3658
3659    let vanilla =
3660      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3661
3662    assert_eq!(
3663      vanilla.args,
3664      vec!["--doorstop-enabled".to_string(), "false".to_string()]
3665    );
3666
3667    let modded =
3668      launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3669
3670    assert_eq!(modded.args[0], "--doorstop-enabled");
3671    assert_eq!(modded.args[2], "--doorstop-target-assembly");
3672  }
3673
3674  #[test]
3675  fn proton_v3_detected_target_still_uses_v3_spellings_even_with_a_script_on_disk() {
3676    // Regression guard: script-path spelling must key off actually running
3677    // through the script (Linux + native + a found script), not merely off
3678    // `HostOs::Linux` or the script file's mere presence on disk. A Proton
3679    // (Wine) launch never goes through the loader script — `script_injection`
3680    // requires `Runtime::Native` — so even with `run_bepinex.sh` sitting in the
3681    // target and no `.doorstop_version` file, the argv must still get the
3682    // version-matched (v3) spelling, because it is Doorstop's own parser, not
3683    // the script, that will read it under Proton.
3684    let dir = tempfile::tempdir().unwrap();
3685    let target = dir.path().join("target");
3686
3687    linux_bepinex_target(&target);
3688    std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3689
3690    let eco = Ecosystem::bundled();
3691    let mut context = linux_native(LaunchMode::Modded);
3692
3693    context.runtime = Runtime::Proton;
3694
3695    let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3696
3697    assert_eq!(plan.args[0], "--doorstop-enable");
3698    assert_eq!(plan.args[2], "--doorstop-target");
3699
3700    let mut vanilla_context = linux_native(LaunchMode::Vanilla);
3701
3702    vanilla_context.runtime = Runtime::Proton;
3703
3704    let vanilla = launch_plan_in(&target, &eco, "valheim", &vanilla_context).unwrap();
3705
3706    assert_eq!(
3707      vanilla.args,
3708      vec!["--doorstop-enable".to_string(), "false".to_string()]
3709    );
3710  }
3711
3712  #[test]
3713  fn windows_v3_detected_target_still_uses_v3_spellings_regression_guard() {
3714    // Regression guard for the non-script paths named in the fix: a
3715    // v3-detected target launched via argv (not a script) must keep the v3
3716    // spellings, on Windows exactly as before this fix.
3717    let dir = tempfile::tempdir().unwrap();
3718    let root = dir.path();
3719    let core = root.join("BepInEx/core");
3720
3721    std::fs::create_dir_all(&core).unwrap();
3722    std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3723
3724    let eco = Ecosystem::bundled();
3725    let plan = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Modded)).unwrap();
3726
3727    assert_eq!(plan.args[0], "--doorstop-enable");
3728    assert_eq!(plan.args[2], "--doorstop-target");
3729
3730    let vanilla = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Vanilla)).unwrap();
3731
3732    assert_eq!(
3733      vanilla.args,
3734      vec!["--doorstop-enable".to_string(), "false".to_string()]
3735    );
3736  }
3737
3738  #[test]
3739  fn store_and_runtime_parse_from_their_config_spellings() {
3740    assert_eq!(
3741      "steam".parse::<StorePlatform>().unwrap(),
3742      StorePlatform::Steam
3743    );
3744    assert_eq!(
3745      "steam-direct".parse::<StorePlatform>().unwrap(),
3746      StorePlatform::SteamDirect
3747    );
3748    assert_eq!(
3749      "other".parse::<StorePlatform>().unwrap(),
3750      StorePlatform::Other
3751    );
3752    assert_eq!("native".parse::<Runtime>().unwrap(), Runtime::Native);
3753    assert_eq!("proton".parse::<Runtime>().unwrap(), Runtime::Proton);
3754
3755    // An unknown value names itself, so a caller can quote it back.
3756    let error = "wat".parse::<StorePlatform>().unwrap_err().to_string();
3757
3758    assert!(error.contains("wat"), "got: {error}");
3759  }
3760
3761  #[test]
3762  fn resolve_game_exe_returns_the_first_present_candidate() {
3763    let dir = tempfile::tempdir().unwrap();
3764    let game_dir = dir.path();
3765
3766    std::fs::write(game_dir.join("second.x86_64"), b"elf").unwrap();
3767
3768    let names = vec!["first.exe".to_string(), "second.x86_64".to_string()];
3769    let found = resolve_game_exe(game_dir, &names).unwrap();
3770
3771    assert_eq!(found, game_dir.join("second.x86_64"));
3772
3773    // Nothing present names every candidate it looked for.
3774    let error = resolve_game_exe(game_dir, &["absent.exe".to_string()])
3775      .unwrap_err()
3776      .to_string();
3777
3778    assert!(error.contains("absent.exe"), "got: {error}");
3779  }
3780
3781  #[test]
3782  fn a_plan_becomes_a_spawnable_command() {
3783    let dir = tempfile::tempdir().unwrap();
3784    let game_dir = dir.path();
3785
3786    std::fs::write(game_dir.join("valheim.x86_64"), b"elf").unwrap();
3787
3788    // `LaunchPlan` derives no `Default`, so every field is named. It is
3789    // `#[non_exhaustive]`, which only restricts other crates, so a struct literal
3790    // is fine inside this module.
3791    let plan = LaunchPlan {
3792      program: LaunchProgram::GameExe {
3793        exe_names: vec!["valheim.x86_64".to_string()],
3794      },
3795      args: vec!["-console".to_string()],
3796      env: vec![("KEY".to_string(), "VALUE".to_string())],
3797      working_dir: Some(game_dir.to_path_buf()),
3798      steam_wrapper: None,
3799    };
3800
3801    let command = plan.to_command(game_dir).unwrap();
3802
3803    assert_eq!(command.get_program(), game_dir.join("valheim.x86_64"));
3804    assert_eq!(
3805      command.get_args().collect::<Vec<_>>(),
3806      vec![std::ffi::OsStr::new("-console")]
3807    );
3808    assert_eq!(command.get_current_dir(), Some(game_dir));
3809    assert!(
3810      command
3811        .get_envs()
3812        .any(|(key, value)| key == std::ffi::OsStr::new("KEY")
3813          && value == Some(std::ffi::OsStr::new("VALUE")))
3814    );
3815  }
3816
3817  /// `-applaunch <id>` must lead, with the plan's own argv after it, whatever
3818  /// path the Steam executable resolved to. Asserted against an explicit program
3819  /// so the ordering is checked on any host, including one with no Steam at all.
3820  #[test]
3821  fn a_steam_command_leads_with_applaunch_and_keeps_the_plan_argv_after_it() {
3822    let program = Path::new(r"C:\Program Files (x86)\Steam\steam.exe");
3823    let mut command = steam_command(program, 892970);
3824
3825    command.args(["-console".to_string(), "--ts-target".to_string()]);
3826
3827    assert_eq!(command.get_program(), program.as_os_str());
3828    assert_eq!(
3829      command.get_args().collect::<Vec<_>>(),
3830      vec![
3831        std::ffi::OsStr::new("-applaunch"),
3832        std::ffi::OsStr::new("892970"),
3833        std::ffi::OsStr::new("-console"),
3834        std::ffi::OsStr::new("--ts-target"),
3835      ]
3836    );
3837  }
3838
3839  /// The Steam arm resolves its program through [`crate::steam::steam_exe`]
3840  /// rather than hardcoding `steam`, which never resolves on Windows.
3841  ///
3842  /// `LaunchPlan::env` is asserted *unchanged* here: it is documented as not
3843  /// reaching a game started through `-applaunch`, so this fix must keep setting
3844  /// exactly what the plan carried and add nothing that would silently do
3845  /// nothing.
3846  #[test]
3847  fn a_steam_plan_spawns_the_resolved_steam_executable() {
3848    let dir = tempfile::tempdir().unwrap();
3849    let game_dir = dir.path();
3850
3851    let plan = LaunchPlan {
3852      program: LaunchProgram::Steam {
3853        steam_app_id: 892970,
3854      },
3855      args: vec!["-console".to_string()],
3856      env: vec![("KEY".to_string(), "VALUE".to_string())],
3857      working_dir: None,
3858      steam_wrapper: None,
3859    };
3860
3861    let command = plan.to_command(game_dir).unwrap();
3862
3863    assert_eq!(
3864      command.get_program(),
3865      crate::steam::steam_exe().as_os_str(),
3866      "the Steam arm must use the resolved executable"
3867    );
3868    assert_eq!(
3869      command.get_args().collect::<Vec<_>>(),
3870      vec![
3871        std::ffi::OsStr::new("-applaunch"),
3872        std::ffi::OsStr::new("892970"),
3873        std::ffi::OsStr::new("-console"),
3874      ]
3875    );
3876
3877    let envs = command.get_envs().collect::<Vec<_>>();
3878
3879    assert_eq!(
3880      envs,
3881      vec![(
3882        std::ffi::OsStr::new("KEY"),
3883        Some(std::ffi::OsStr::new("VALUE"))
3884      )],
3885      "the plan's env must reach the command unchanged, with nothing added"
3886    );
3887  }
3888}
3889
3890#[cfg(test)]
3891mod planning_tests {
3892  use super::*;
3893
3894  const TARGET: &str = "/profiles/main";
3895
3896  fn ctx(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> LaunchContext {
3897    LaunchContext::new(os, store, runtime, mode)
3898  }
3899
3900  fn with_preloader() -> LaunchFacts {
3901    LaunchFacts {
3902      preloader: Some("BepInEx.Preloader.dll".to_string()),
3903      ..LaunchFacts::default()
3904    }
3905  }
3906
3907  fn plan(facts: &LaunchFacts, context: &LaunchContext) -> Result<LaunchPlan> {
3908    launch_plan_from(
3909      Path::new(TARGET),
3910      facts,
3911      &Ecosystem::bundled(),
3912      "valheim",
3913      context,
3914    )
3915  }
3916
3917  #[test]
3918  fn doorstop_flags_follow_the_recorded_version() {
3919    let windows = ctx(
3920      HostOs::Windows,
3921      StorePlatform::SteamDirect,
3922      Runtime::Native,
3923      LaunchMode::Modded,
3924    );
3925    let mut facts = with_preloader();
3926
3927    let v3 = plan(&facts, &windows).unwrap();
3928
3929    facts.doorstop_version = 4;
3930
3931    let v4 = plan(&facts, &windows).unwrap();
3932
3933    assert_eq!(v3.args[0], "--doorstop-enable");
3934    assert_eq!(v4.args[0], "--doorstop-enabled");
3935    assert!(
3936      v3.args
3937        .contains(&format!("{TARGET}/BepInEx/core/BepInEx.Preloader.dll"))
3938    );
3939  }
3940
3941  #[test]
3942  fn a_modded_bepinex_launch_needs_a_preloader() {
3943    let windows = ctx(
3944      HostOs::Windows,
3945      StorePlatform::SteamDirect,
3946      Runtime::Native,
3947      LaunchMode::Modded,
3948    );
3949
3950    let result = plan(&LaunchFacts::default(), &windows);
3951
3952    assert!(
3953      matches!(result, Err(Error::Profile(message)) if message.contains("no BepInEx preloader"))
3954    );
3955  }
3956
3957  #[test]
3958  fn corlibs_add_the_search_path_override() {
3959    let windows = ctx(
3960      HostOs::Windows,
3961      StorePlatform::SteamDirect,
3962      Runtime::Native,
3963      LaunchMode::Modded,
3964    );
3965    let mut facts = with_preloader();
3966
3967    facts.has_corlibs = true;
3968
3969    let plan = plan(&facts, &windows).unwrap();
3970
3971    assert!(
3972      plan
3973        .args
3974        .contains(&"--doorstop-dll-search-override".to_string())
3975    );
3976    assert!(plan.args.contains(&format!("{TARGET}/unstripped_corlib")));
3977  }
3978
3979  #[test]
3980  fn a_listed_loader_script_is_run_on_linux_native() {
3981    let linux = ctx(
3982      HostOs::Linux,
3983      StorePlatform::SteamDirect,
3984      Runtime::Native,
3985      LaunchMode::Modded,
3986    );
3987    let mut facts = with_preloader();
3988
3989    facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
3990
3991    let plan = plan(&facts, &linux).unwrap();
3992
3993    assert!(matches!(
3994      plan.program,
3995      LaunchProgram::ProfileScript { ref path, .. }
3996        if path == &Path::new(TARGET).join("start_game_bepinex.sh")
3997    ));
3998    assert_eq!(plan.args[0], "--doorstop-enabled");
3999  }
4000
4001  #[test]
4002  fn a_proton_launch_through_steam_pastes_the_override_in_either_mode() {
4003    for mode in [LaunchMode::Modded, LaunchMode::Vanilla] {
4004      let proton = ctx(HostOs::Linux, StorePlatform::Steam, Runtime::Proton, mode);
4005      let plan = plan(&with_preloader(), &proton).unwrap();
4006
4007      assert_eq!(
4008        plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4009        Some(r#"WINEDLLOVERRIDES="winhttp=n,b" %command%"#.to_string()),
4010        "{mode:?}"
4011      );
4012    }
4013  }
4014
4015  #[test]
4016  fn a_linux_native_launch_through_steam_pastes_the_wrapper_line() {
4017    let native = ctx(
4018      HostOs::Linux,
4019      StorePlatform::Steam,
4020      Runtime::Native,
4021      LaunchMode::Modded,
4022    );
4023    let mut facts = with_preloader();
4024
4025    facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
4026
4027    let plan = plan(&facts, &native).unwrap();
4028
4029    assert_eq!(
4030      plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4031      Some(r#""/base/valheim/steam-wrapper.sh" %command%"#.to_string())
4032    );
4033  }
4034
4035  #[test]
4036  fn a_launch_steam_does_not_start_has_nothing_to_paste() {
4037    for (os, runtime) in [
4038      (HostOs::Windows, Runtime::Native),
4039      (HostOs::Linux, Runtime::Proton),
4040    ] {
4041      let direct = ctx(os, StorePlatform::SteamDirect, runtime, LaunchMode::Modded);
4042      let plan = plan(&with_preloader(), &direct).unwrap();
4043
4044      assert_eq!(
4045        plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4046        None,
4047        "{os:?} {runtime:?}"
4048      );
4049    }
4050  }
4051
4052  #[test]
4053  fn no_plan_needs_both_the_wrapper_and_the_proton_override() {
4054    let mut facts = with_preloader();
4055
4056    facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
4057
4058    for os in [HostOs::Windows, HostOs::Linux] {
4059      for store in [
4060        StorePlatform::Steam,
4061        StorePlatform::SteamDirect,
4062        StorePlatform::Other,
4063      ] {
4064        for runtime in [Runtime::Native, Runtime::Proton] {
4065          for mode in [LaunchMode::Modded, LaunchMode::Vanilla] {
4066            let Ok(plan) = plan(&facts, &ctx(os, store, runtime, mode)) else {
4067              continue;
4068            };
4069            let overrides = plan.env.iter().any(|(key, _)| key == "WINEDLLOVERRIDES");
4070
4071            assert!(
4072              !(plan.steam_wrapper.is_some() && overrides),
4073              "{os:?} {store:?} {runtime:?} {mode:?}"
4074            );
4075          }
4076        }
4077      }
4078    }
4079  }
4080
4081  #[test]
4082  fn linux_native_modded_without_a_loader_script_is_refused() {
4083    let linux = ctx(
4084      HostOs::Linux,
4085      StorePlatform::SteamDirect,
4086      Runtime::Native,
4087      LaunchMode::Modded,
4088    );
4089
4090    let result = plan(&with_preloader(), &linux);
4091
4092    assert!(matches!(result, Err(Error::Profile(message)) if message.contains("loader script")));
4093  }
4094
4095  #[test]
4096  fn the_server_script_is_ignored_for_a_game_instance() {
4097    let linux = ctx(
4098      HostOs::Linux,
4099      StorePlatform::SteamDirect,
4100      Runtime::Native,
4101      LaunchMode::Modded,
4102    );
4103    let mut facts = with_preloader();
4104
4105    facts.loader_scripts = vec!["start_server_bepinex.sh".to_string()];
4106
4107    assert!(plan(&facts, &linux).is_err());
4108  }
4109
4110  #[test]
4111  fn melonloader_regenerates_only_without_its_assemblies() {
4112    let eco = Ecosystem::bundled();
4113    let profile = eco
4114      .games()
4115      .filter_map(|game| game.profile())
4116      .find(|profile| profile.package_loader == LoaderKind::MelonLoader)
4117      .unwrap();
4118    let windows = ctx(
4119      HostOs::Windows,
4120      StorePlatform::SteamDirect,
4121      Runtime::Native,
4122      LaunchMode::Modded,
4123    );
4124    let mut facts = LaunchFacts::default();
4125
4126    let bare = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
4127
4128    facts.melonloader_assemblies = true;
4129
4130    let built = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
4131
4132    assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
4133    assert!(!built.contains(&"--melonloader.agfregenerate".to_string()));
4134  }
4135
4136  #[test]
4137  fn macos_is_refused_whatever_the_facts() {
4138    let mac = ctx(
4139      HostOs::MacOs,
4140      StorePlatform::SteamDirect,
4141      Runtime::Native,
4142      LaunchMode::Modded,
4143    );
4144
4145    assert!(plan(&with_preloader(), &mac).is_err());
4146  }
4147
4148  #[test]
4149  #[cfg(feature = "io")]
4150  fn launch_facts_read_what_the_target_holds() {
4151    let dir = tempfile::tempdir().unwrap();
4152    let root = dir.path();
4153
4154    std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
4155    std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
4156    std::fs::create_dir_all(root.join("MelonLoader/Il2CppAssemblies")).unwrap();
4157    std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"").unwrap();
4158    std::fs::write(root.join("run_bepinex.sh"), b"").unwrap();
4159    std::fs::write(root.join(".doorstop_version"), b"4.0.0").unwrap();
4160    std::fs::write(
4161      root.join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll"),
4162      b"",
4163    )
4164    .unwrap();
4165
4166    let facts = LaunchFacts::read(root);
4167
4168    assert_eq!(facts.doorstop_version, 4);
4169    assert_eq!(facts.preloader.as_deref(), Some("BepInEx.Preloader.dll"));
4170    assert!(facts.has_corlibs);
4171    assert_eq!(facts.loader_scripts, vec!["run_bepinex.sh".to_string()]);
4172    assert!(facts.melonloader_assemblies);
4173    assert_eq!(
4174      LaunchFacts::read(&root.join("missing")),
4175      LaunchFacts::default()
4176    );
4177  }
4178
4179  #[test]
4180  #[cfg(feature = "io")]
4181  fn launch_facts_read_the_loader_files_and_recorded_packages() {
4182    let dir = tempfile::tempdir().unwrap();
4183    let root = dir.path();
4184    let version: crate::models::Version = serde_json::from_str(
4185      r#"{"name":"GDWeave","full_name":"NotNet-GDWeave","description":"d","icon":"i",
4186      "version_number":"2.0.0","dependencies":[],"download_url":"u","downloads":1,
4187      "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
4188      "uuid4":"u","file_size":1}"#,
4189    )
4190    .unwrap();
4191
4192    std::fs::create_dir_all(root.join("GDWeave/core")).unwrap();
4193    std::fs::write(root.join("GDWeave/core/GDWeave.dll"), b"").unwrap();
4194    std::fs::create_dir_all(root.join("R2Northstar")).unwrap();
4195    std::fs::write(root.join("R2Northstar/Northstar.dll"), b"").unwrap();
4196    crate::profile::modlist::write(
4197      root,
4198      &[crate::profile::mod_entry_from_version(
4199        "NotNet-GDWeave",
4200        "NotNet",
4201        &version,
4202        1,
4203      )],
4204    )
4205    .unwrap();
4206
4207    let facts = LaunchFacts::read(root);
4208
4209    assert_eq!(
4210      facts.loaders,
4211      vec![LoaderKind::GdWeave, LoaderKind::Northstar]
4212    );
4213    assert_eq!(facts.recorded, vec!["NotNet-GDWeave".to_string()]);
4214  }
4215}