mobux 0.51.0

A touch-friendly tmux web UI for unhinged people who run terminal sessions from their phone while walking the dog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Building the Android TWA package from the running server.
//!
//! `make twa` only exists inside a source checkout, and the installed binary
//! runs as a systemd service whose working directory is the user's home — so
//! neither the build inputs nor the old cwd-relative artifact paths resolve
//! there. Everything the build needs is embedded and materialised under the
//! data dir instead, which makes "Generate package" work on a deployed
//! instance and on a dev checkout alike.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

pub const BUILD_SCRIPT: &str = include_str!("../bin/twa-build");
pub const SETUP_SCRIPT: &str = include_str!("../bin/setup-twa");
pub const INIT_JS: &str = include_str!("../twa/init.js");
pub const MANIFEST_TEMPLATE: &str = include_str!("../twa/twa-manifest.json.template");

/// OS packages the toolchain install shells out to and cannot supply itself:
/// SDKMAN and the Android SDK manager unpack their downloads with them. Every
/// other prerequisite is installed user-locally by the setup script.
pub const HOST_PACKAGES: [&str; 3] = ["curl", "unzip", "zip"];

/// Where a repo checkout's `make twa` writes its artifacts. Still honoured so
/// a dev instance started from the checkout serves what `make twa` produced.
pub const CHECKOUT_APK_PATH: &str = "web/static/install/mobux.apk";
pub const CHECKOUT_ASSETLINKS_PATH: &str = "web/static/.well-known/assetlinks.json";

pub fn work_dir(data_dir: &Path) -> PathBuf {
    data_dir.join("twa")
}

pub fn apk_path(data_dir: &Path) -> PathBuf {
    data_dir.join("install").join("mobux.apk")
}

/// What a finished build records next to the package: the host it was
/// signed for, so the install page names what the installed app opens rather
/// than what a new build would use.
pub fn build_record_path(data_dir: &Path) -> PathBuf {
    data_dir.join("install").join("mobux.apk.json")
}

pub fn record_build(data_dir: &Path, domain: &str) -> Result<()> {
    let path = build_record_path(data_dir);
    let record = serde_json::json!({ "domain": domain });
    std::fs::write(&path, record.to_string()).with_context(|| format!("writing {}", path.display()))
}

/// The host the package on disk was built for. `None` for a package with no
/// record, such as one a checkout's `make twa` produced.
pub fn built_domain(data_dir: &Path) -> Option<String> {
    let bytes = std::fs::read(build_record_path(data_dir)).ok()?;
    let record: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    record["domain"].as_str().map(str::to_owned)
}

pub fn assetlinks_path(data_dir: &Path) -> PathBuf {
    data_dir.join(".well-known").join("assetlinks.json")
}

/// The artifact a request should be served, preferring what this server built
/// over what a checkout's `make twa` left behind.
pub fn resolve_artifact(built: PathBuf, checkout: &str) -> PathBuf {
    if built.is_file() {
        return built;
    }
    PathBuf::from(checkout)
}

/// The two scripts the build runs: the toolchain install, and the build that
/// follows it.
pub struct Scripts {
    pub setup: PathBuf,
    pub build: PathBuf,
}

/// Write the embedded build inputs into the data dir and return the script
/// paths. Rewritten on every build so an upgraded binary replaces a stale copy.
pub fn materialize(data_dir: &Path) -> Result<Scripts> {
    let dir = work_dir(data_dir);
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("creating twa work dir: {}", dir.display()))?;

    let build = dir.join("twa-build");
    std::fs::write(&build, BUILD_SCRIPT).with_context(|| format!("writing {}", build.display()))?;
    let setup = dir.join("setup-twa");
    std::fs::write(&setup, SETUP_SCRIPT).with_context(|| format!("writing {}", setup.display()))?;
    std::fs::write(dir.join("init.js"), INIT_JS).context("writing twa init.js")?;
    std::fs::write(dir.join("twa-manifest.json.template"), MANIFEST_TEMPLATE)
        .context("writing twa manifest template")?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for script in [&build, &setup] {
            std::fs::set_permissions(script, std::fs::Permissions::from_mode(0o700))
                .with_context(|| format!("chmod {}", script.display()))?;
        }
    }

    Ok(Scripts { setup, build })
}

/// Ask the build script whether it can build. It runs the same toolchain
/// bootstrap and looks for the same tools the build does, so the pre-phase's
/// notion of "missing" cannot drift from what the build actually needs.
pub fn toolchain_check(build_script: &Path) -> std::process::Command {
    let mut command = std::process::Command::new("bash");
    command
        .arg(build_script)
        .arg("--check-toolchain")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    command
}

pub fn toolchain_present(build_script: &Path) -> bool {
    toolchain_check(build_script)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path)
        .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

#[cfg(not(unix))]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}

pub fn on_path(tool: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|dir| is_executable(&dir.join(tool)))
}

/// The host packages that are needed and absent, in a stable order.
pub fn missing_host_packages(present: impl Fn(&str) -> bool) -> Vec<&'static str> {
    HOST_PACKAGES
        .into_iter()
        .filter(|tool| !present(tool))
        .collect()
}

pub fn missing_host_packages_on_path() -> Vec<&'static str> {
    missing_host_packages(on_path)
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PackageManager {
    Apt,
    Dnf,
    Pacman,
    Zypper,
    Apk,
}

impl PackageManager {
    /// `None` on a host none of these matches. Guessing a command that the
    /// host has no way to run would be worse than saying so plainly.
    pub fn detect(present: impl Fn(&str) -> bool) -> Option<Self> {
        [
            ("apt-get", Self::Apt),
            ("dnf", Self::Dnf),
            ("pacman", Self::Pacman),
            ("zypper", Self::Zypper),
            ("apk", Self::Apk),
        ]
        .into_iter()
        .find(|(tool, _)| present(tool))
        .map(|(_, manager)| manager)
    }

    pub fn install_command(self, packages: &[&str]) -> String {
        let list = packages.join(" ");
        match self {
            Self::Apt => format!("sudo apt-get install -y {list}"),
            Self::Dnf => format!("sudo dnf install -y {list}"),
            Self::Pacman => format!("sudo pacman -S --noconfirm {list}"),
            Self::Zypper => format!("sudo zypper install -y {list}"),
            Self::Apk => format!("sudo apk add {list}"),
        }
    }
}

/// What the build stopped on and how the user clears it. The command is the
/// page's copy-paste affordance, so it is never folded into the message.
pub struct HostPackageGap {
    pub packages: Vec<String>,
    pub install_command: Option<String>,
    pub message: String,
}

fn english_list(items: &[&str]) -> String {
    match items {
        [] => String::new(),
        [one] => (*one).to_string(),
        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
    }
}

pub fn host_package_gap_with(manager: Option<PackageManager>, missing: &[&str]) -> HostPackageGap {
    let them = if missing.len() == 1 { "it" } else { "them" };
    HostPackageGap {
        packages: missing.iter().map(|p| (*p).to_string()).collect(),
        install_command: manager.map(|m| m.install_command(missing)),
        message: format!(
            "This host is missing {}. The Android build tools unpack their downloads with {them}, and only your system package manager can install {them}.",
            english_list(missing),
        ),
    }
}

pub fn host_package_gap(missing: &[&str]) -> HostPackageGap {
    host_package_gap_with(PackageManager::detect(on_path), missing)
}

/// The authority the APK will be pinned to. A configured `app.domain` wins;
/// otherwise it comes off the request's `Host` header, so the package points
/// at whatever address the user actually reaches this server on and nobody has
/// to type it. A default TLS port is dropped — `example.com:443` and
/// `example.com` are different TWA hosts to Android.
pub fn resolve_domain(
    configured: Option<&str>,
    host_header: Option<&str>,
) -> Result<String, String> {
    let usable = |s: &Option<&str>| {
        s.map(str::trim)
            .filter(|v| !v.is_empty())
            .map(str::to_owned)
    };
    let raw = usable(&configured)
        .or_else(|| usable(&host_header))
        .ok_or_else(|| "no Host header on the request and app.domain is not set".to_string())?;

    let domain = raw.strip_suffix(":443").unwrap_or(&raw);
    validate_domain(domain).map(|_| domain.to_string())
}

/// [`resolve_domain`] with the Cloudflare Access hostname ahead of both: a
/// package bound to the tunnel opens one origin, whichever address built it.
pub fn pinned_domain(
    access_hostname: Option<&str>,
    configured: Option<&str>,
    host_header: Option<&str>,
) -> Result<String, String> {
    match access_hostname.map(str::trim).filter(|h| !h.is_empty()) {
        Some(hostname) => resolve_domain(Some(hostname), None),
        None => resolve_domain(configured, host_header),
    }
}

fn validate_domain(domain: &str) -> Result<(), String> {
    if domain.is_empty() {
        return Err("empty domain".to_string());
    }
    let (host, port) = match domain.rsplit_once(':') {
        Some((h, p)) => (h, Some(p)),
        None => (domain, None),
    };
    if host.is_empty()
        || !host
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
    {
        return Err(format!("{domain:?} is not a usable host name"));
    }
    if let Some(p) = port {
        if p.parse::<u16>().is_err() {
            return Err(format!("{domain:?} has an invalid port"));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn domain_comes_from_the_host_header() {
        assert_eq!(
            resolve_domain(None, Some("box.example.com")).unwrap(),
            "box.example.com"
        );
        assert_eq!(
            resolve_domain(None, Some("sandbox:5152")).unwrap(),
            "sandbox:5152"
        );
    }

    #[test]
    fn a_configured_domain_wins_over_the_host_header() {
        assert_eq!(
            resolve_domain(Some("pinned.example.com"), Some("box.example.com")).unwrap(),
            "pinned.example.com"
        );
        assert_eq!(
            resolve_domain(Some("  "), Some("box.example.com")).unwrap(),
            "box.example.com"
        );
    }

    #[test]
    fn the_access_hostname_wins_over_the_configured_domain_and_the_host_header() {
        assert_eq!(
            pinned_domain(
                Some("mobux.example.com"),
                Some("pinned.example.com"),
                Some("box.tailnet.ts.net:5151")
            )
            .unwrap(),
            "mobux.example.com"
        );
    }

    #[test]
    fn without_an_access_hostname_the_package_follows_the_usual_domain() {
        assert_eq!(
            pinned_domain(None, Some(""), Some("box.tailnet.ts.net:5151")).unwrap(),
            "box.tailnet.ts.net:5151"
        );
        assert_eq!(
            pinned_domain(Some(" "), Some("pinned.example.com"), None).unwrap(),
            "pinned.example.com"
        );
    }

    #[test]
    fn default_tls_port_is_dropped() {
        assert_eq!(
            resolve_domain(None, Some("box.example.com:443")).unwrap(),
            "box.example.com"
        );
    }

    #[test]
    fn a_missing_host_header_is_an_error_not_a_guess() {
        assert!(resolve_domain(None, None).is_err());
        assert!(resolve_domain(None, Some("   ")).is_err());
    }

    #[test]
    fn a_host_header_carrying_a_scheme_or_path_is_rejected() {
        for bad in [
            "https://box.example.com",
            "box.example.com/app",
            "box:notaport",
        ] {
            assert!(
                resolve_domain(None, Some(bad)).is_err(),
                "should reject {bad:?}"
            );
        }
    }

    #[test]
    fn a_finished_build_records_the_host_it_was_signed_for() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(built_domain(dir.path()), None);
        std::fs::create_dir_all(dir.path().join("install")).unwrap();
        record_build(dir.path(), "mobux.example.com").unwrap();
        assert_eq!(
            built_domain(dir.path()).as_deref(),
            Some("mobux.example.com")
        );
    }

    #[test]
    fn materialize_writes_an_executable_script_and_its_inputs() {
        let dir = tempfile::tempdir().unwrap();
        let scripts = materialize(dir.path()).unwrap();
        assert!(scripts.build.is_file());
        assert!(scripts.setup.is_file());
        assert!(work_dir(dir.path()).join("init.js").is_file());
        assert!(work_dir(dir.path())
            .join("twa-manifest.json.template")
            .is_file());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            for script in [&scripts.build, &scripts.setup] {
                let mode = std::fs::metadata(script).unwrap().permissions().mode();
                assert_eq!(mode & 0o100, 0o100, "script must be owner-executable");
            }
        }
    }

    #[test]
    fn the_preflight_names_only_the_packages_that_are_absent() {
        assert!(missing_host_packages(|_| true).is_empty());
        assert_eq!(missing_host_packages(|tool| tool != "zip"), vec!["zip"]);
        assert_eq!(
            missing_host_packages(|tool| tool == "curl"),
            vec!["unzip", "zip"]
        );
    }

    #[test]
    fn the_install_command_matches_the_hosts_package_manager() {
        let missing = ["unzip", "zip"];
        for (tool, want) in [
            ("apt-get", "sudo apt-get install -y unzip zip"),
            ("dnf", "sudo dnf install -y unzip zip"),
            ("pacman", "sudo pacman -S --noconfirm unzip zip"),
            ("zypper", "sudo zypper install -y unzip zip"),
            ("apk", "sudo apk add unzip zip"),
        ] {
            let manager = PackageManager::detect(|t| t == tool).expect("a known manager");
            assert_eq!(manager.install_command(&missing), want);
        }
    }

    /// A host with no manager we know gets told what it needs, not a command
    /// for a package manager it does not have.
    #[test]
    fn an_unknown_package_manager_yields_no_command_rather_than_a_guess() {
        assert_eq!(PackageManager::detect(|_| false), None);

        let gap = host_package_gap_with(None, &["curl", "unzip", "zip"]);
        assert_eq!(gap.install_command, None);
        assert!(
            gap.message.contains("curl, unzip and zip"),
            "{}",
            gap.message
        );
        assert!(
            gap.message.contains("system package manager"),
            "{}",
            gap.message
        );
    }

    /// The command is the page's copy-paste affordance, so it is carried as a
    /// field rather than buried in the prose.
    #[test]
    fn the_preflight_reports_the_packages_and_the_command_separately() {
        let gap = host_package_gap_with(Some(PackageManager::Apt), &["zip"]);
        assert_eq!(gap.packages, vec!["zip".to_string()]);
        assert_eq!(
            gap.install_command.as_deref(),
            Some("sudo apt-get install -y zip")
        );
        assert!(gap.message.contains("missing zip"), "{}", gap.message);
        assert!(
            !gap.message.contains("apt-get"),
            "the command must not be duplicated into the prose: {}",
            gap.message
        );
    }

    /// The preflight exists to catch what the setup script would die on, so
    /// its list and the script's must stay the same list.
    #[test]
    fn the_preflight_covers_every_host_tool_the_setup_script_requires() {
        let required: Vec<&str> = SETUP_SCRIPT
            .lines()
            .map(str::trim)
            .filter_map(|line| line.strip_prefix("require_host_tool "))
            .map(str::trim)
            .collect();
        assert!(!required.is_empty(), "setup-twa must require host tools");
        let mut sorted = required.clone();
        sorted.sort_unstable();
        let mut known = HOST_PACKAGES.to_vec();
        known.sort_unstable();
        assert_eq!(sorted, known);
    }

    /// The toolchain pre-phase decides by asking the build script itself, so
    /// these two cases are the real detection, not a copy of it. `HOME` points
    /// at an empty dir so no SDKMAN or nvm install on the host can leak in.
    #[cfg(unix)]
    fn toolchain_check_with(tools: &[&str]) -> bool {
        use std::os::unix::fs::PermissionsExt;

        let home = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        for tool in ["bash", "dirname"] {
            let out = std::process::Command::new("sh")
                .arg("-c")
                .arg(format!("command -v {tool}"))
                .output()
                .expect("resolving a host tool");
            let target = String::from_utf8(out.stdout).unwrap().trim().to_string();
            assert!(!target.is_empty(), "{tool} must exist to run this test");
            std::os::unix::fs::symlink(target, bin.path().join(tool)).unwrap();
        }
        for tool in tools {
            let stub = bin.path().join(tool);
            std::fs::write(&stub, "#!/bin/sh\nexit 0\n").unwrap();
            std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let data_dir = tempfile::tempdir().unwrap();
        let scripts = materialize(data_dir.path()).unwrap();
        toolchain_check(&scripts.build)
            .env("PATH", bin.path())
            .env("HOME", home.path())
            .env_remove("SDKMAN_DIR")
            .env_remove("NVM_DIR")
            .env_remove("ANDROID_SDK_ROOT")
            .env_remove("ANDROID_HOME")
            .env_remove("NPM_PREFIX")
            .status()
            .expect("running the toolchain check")
            .success()
    }

    #[cfg(unix)]
    #[test]
    fn a_host_without_the_toolchain_reports_it_missing() {
        assert!(!toolchain_check_with(&[]));
        assert!(
            !toolchain_check_with(&["node", "java", "keytool"]),
            "a partial toolchain is still missing"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_host_with_the_toolchain_reports_it_present() {
        assert!(toolchain_check_with(&[
            "node",
            "java",
            "keytool",
            "bubblewrap"
        ]));
    }

    /// The build script runs under `set -euo pipefail`, so a password pipeline
    /// whose producer is killed by SIGPIPE aborts the whole build with a bare
    /// exit 141 before the keystore is ever generated.
    #[test]
    fn the_generated_keystore_password_survives_pipefail() {
        let marker = "generate_keystore_password() {";
        let body = BUILD_SCRIPT
            .split_once(marker)
            .and_then(|(_, rest)| rest.split_once("\n}\n"))
            .map(|(body, _)| body)
            .expect("twa-build must define generate_keystore_password()");

        let program = format!(
            "set -euo pipefail\n{marker}{body}\n}}\nfor _ in $(seq 20); do generate_keystore_password; echo; done\n"
        );
        let out = std::process::Command::new("bash")
            .arg("-c")
            .arg(&program)
            .output()
            .expect("running bash");

        assert_eq!(
            out.status.code(),
            Some(0),
            "password generation exited {:?}: {}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8(out.stdout).expect("password must be ascii");
        let passwords: Vec<&str> = stdout.lines().collect();
        assert_eq!(passwords.len(), 20);
        for password in passwords {
            assert_eq!(password.len(), 32, "wrong length: {password:?}");
            assert!(
                password.chars().all(|c| c.is_ascii_alphanumeric()),
                "not alphanumeric: {password:?}"
            );
        }
    }

    /// The launcher Google ships for every cmdline-tools binary: it walks `$0`
    /// through `while [ -h ]` — file symlinks only — and derives the classpath
    /// root from where that lands.
    #[cfg(unix)]
    const FAKE_SDKMANAGER: &str = r#"#!/usr/bin/env bash
PRG="$0"
while [ -h "$PRG" ]; do
    ls=$(ls -ld "$PRG")
    link=${ls#*' -> '}
    case $link in
    /*) PRG="$link" ;;
    *) PRG="$(dirname "$PRG")/$link" ;;
    esac
done
APP_HOME=$(cd "$(dirname "$PRG")/.." && pwd -P)
if [ ! -f "$APP_HOME/lib/sdkmanager-classpath.jar" ]; then
    echo "Error: Could not find or load main class com.android.sdklib.tool.sdkmanager.SdkManagerCli" >&2
    exit 1
fi
echo "12.0"
"#;

    #[cfg(unix)]
    fn fake_android_sdk() -> tempfile::TempDir {
        use std::os::unix::fs::PermissionsExt;

        let sdk = tempfile::tempdir().unwrap();
        let tools = sdk.path().join("cmdline-tools").join("latest");
        std::fs::create_dir_all(tools.join("bin")).unwrap();
        std::fs::create_dir_all(tools.join("lib")).unwrap();
        std::fs::write(tools.join("lib").join("sdkmanager-classpath.jar"), b"jar").unwrap();

        let launcher = tools.join("bin").join("sdkmanager");
        std::fs::write(&launcher, FAKE_SDKMANAGER).unwrap();
        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
        sdk
    }

    #[cfg(unix)]
    fn bash(program: &str) -> std::process::Output {
        std::process::Command::new("bash")
            .arg("-c")
            .arg(program)
            .output()
            .expect("running bash")
    }

    /// Run the setup script's link step against a fake SDK. The script returns
    /// early when sourced, so nothing gets installed.
    #[cfg(unix)]
    fn link_android_bin(sdk: &Path) -> std::process::Output {
        bash(&format!(
            "set -euo pipefail\nexport ANDROID_SDK_ROOT='{}'\n. '{}'\nensure_android_bin_links\n",
            sdk.display(),
            concat!(env!("CARGO_MANIFEST_DIR"), "/bin/setup-twa"),
        ))
    }

    #[cfg(unix)]
    fn sdkmanager_version(sdk: &Path) -> std::process::Output {
        bash(&format!("'{}/bin/sdkmanager' --version", sdk.display()))
    }

    /// Bubblewrap only accepts an SDK with a `<SDK>/bin`, so setup makes one.
    /// As a symlinked directory it satisfies bubblewrap and breaks every tool
    /// behind it, which is what a real APK build hits the moment bubblewrap
    /// shells out to sdkmanager.
    #[cfg(unix)]
    #[test]
    fn the_sdk_bin_dir_keeps_the_launchers_working() {
        let sdk = fake_android_sdk();

        let broken = bash(&format!(
            "ln -s cmdline-tools/latest/bin '{}/bin'",
            sdk.path().display()
        ));
        assert!(broken.status.success());
        let out = sdkmanager_version(sdk.path());
        assert!(
            !out.status.success() && String::from_utf8_lossy(&out.stderr).contains("SdkManagerCli"),
            "a directory symlink must break the launcher, or this test proves nothing"
        );

        let linked = link_android_bin(sdk.path());
        assert!(
            linked.status.success(),
            "link step failed: {}",
            String::from_utf8_lossy(&linked.stderr)
        );
        assert!(!sdk.path().join("bin").is_symlink());

        let out = sdkmanager_version(sdk.path());
        assert!(
            out.status.success(),
            "sdkmanager failed through {}/bin: {}",
            sdk.path().display(),
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "12.0");
    }

    #[cfg(unix)]
    #[test]
    fn re_running_setup_repairs_a_stale_link() {
        let sdk = fake_android_sdk();
        assert!(link_android_bin(sdk.path()).status.success());

        let link = sdk.path().join("bin").join("sdkmanager");
        std::fs::remove_file(&link).unwrap();
        std::os::unix::fs::symlink("cmdline-tools/latest/bin/sdkmanager", &link).unwrap();
        assert!(!sdkmanager_version(sdk.path()).status.success());

        assert!(link_android_bin(sdk.path()).status.success());
        assert!(sdkmanager_version(sdk.path()).status.success());
    }

    #[test]
    fn artifact_resolution_prefers_the_built_copy() {
        let dir = tempfile::tempdir().unwrap();
        let built = apk_path(dir.path());
        assert_eq!(
            resolve_artifact(built.clone(), CHECKOUT_APK_PATH),
            PathBuf::from(CHECKOUT_APK_PATH)
        );
        std::fs::create_dir_all(built.parent().unwrap()).unwrap();
        std::fs::write(&built, b"apk").unwrap();
        assert_eq!(resolve_artifact(built.clone(), CHECKOUT_APK_PATH), built);
    }
}