clairlune 0.26.0

Procedural, animated ASCII-art desktop wallpapers. Local, seeded and deterministic; no AI, no network.
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Installing a newer version in place, the one-click way: the download
//! for this kind of install (the Windows setup.exe, the Mac DMG) is fetched
//! from the GitHub release with the system's `curl`, checked against the
//! SHA-256 GitHub lists for it, and readied; then a small helper script
//! waits for Clairlune to quit, puts the new version in place and starts it
//! again. Installs that something else manages (Scoop, cargo) say how to
//! update instead.
//!
//! Removing Clairlune works the same way: a helper waits for it to quit,
//! deletes its folders and, where Clairlune can, the app itself.

use crate::update::Asset;
use std::path::{Path, PathBuf};

/// How this copy of Clairlune was installed.
#[derive(Clone, Debug, PartialEq)]
pub enum Install {
    /// Windows: by setup.exe (for this account), at this exe.
    WindowsSetup { exe: PathBuf },
    /// macOS: this app bundle, in a folder Clairlune can write to.
    MacApp { bundle: PathBuf },
    /// Something else: what it is, and how to update it.
    Manual { name: String, how: String },
}

impl Install {
    /// How it was installed, in a few words (for problem reports).
    pub fn name(&self) -> String {
        match self {
            Install::WindowsSetup { .. } => "the Windows installer".into(),
            Install::MacApp { .. } => "the app (DMG or Homebrew)".into(),
            Install::Manual { name, .. } => name.clone(),
        }
    }

    /// Whether Clairlune can install a new version itself.
    pub fn in_place(&self) -> bool {
        !matches!(self, Install::Manual { .. })
    }

    /// What to do by hand, where Clairlune can't.
    pub fn how(&self) -> Option<&str> {
        match self {
            Install::Manual { how, .. } => Some(how),
            _ => None,
        }
    }

    /// What "Remove Clairlune" does with the app itself: `Ok` names what it
    /// removes, `Err` says how to remove it by hand.
    pub fn removal(&self) -> Result<&'static str, String> {
        match self {
            Install::WindowsSetup { .. } => Ok("the app (its uninstaller runs)"),
            Install::MacApp { .. } => Ok("the app (moved to the Trash)"),
            Install::Manual { name, .. } => Err(match name.as_str() {
                "Scoop" => "Then remove the app with: scoop uninstall clairlune".into(),
                "cargo install" => "Then remove the app with: cargo uninstall clairlune".into(),
                _ => "Then delete the app where you keep it.".into(),
            }),
        }
    }

    /// The release download for this install of `version`.
    pub fn asset_name(&self, version: &str) -> Option<String> {
        match self {
            Install::WindowsSetup { .. } => Some(format!("clairlune_{version}_x64-setup.exe")),
            Install::MacApp { .. } => {
                let arch = if cfg!(target_arch = "aarch64") {
                    "aarch64"
                } else {
                    "x64"
                };
                Some(format!("Clairlune_{version}_{arch}.dmg"))
            }
            Install::Manual { .. } => None,
        }
    }
}

/// This copy's install.
pub fn detect() -> Install {
    let Ok(exe) = std::env::current_exe() else {
        return manual_download("an unknown kind of install");
    };
    classify(&exe, std::env::consts::OS, &|p| p.exists(), &writable)
}

fn manual_download(name: &str) -> Install {
    Install::Manual {
        name: name.into(),
        how: "Download the new version from its release page.".into(),
    }
}

/// [`detect`], from the facts.
fn classify(
    exe: &Path,
    os: &str,
    exists: &dyn Fn(&Path) -> bool,
    writable: &dyn Fn(&Path) -> bool,
) -> Install {
    let text = exe.to_string_lossy().replace('\\', "/").to_lowercase();
    if text.contains("/.cargo/bin/") {
        return Install::Manual {
            name: "cargo install".into(),
            how: "Update it with: cargo install clairlune".into(),
        };
    }
    match os {
        "windows" => {
            if text.contains("/scoop/apps/") {
                Install::Manual {
                    name: "Scoop".into(),
                    how: "Update it with: scoop update clairlune".into(),
                }
            } else if exe
                .parent()
                .is_some_and(|dir| exists(&dir.join("uninstall.exe")))
            {
                Install::WindowsSetup {
                    exe: exe.to_path_buf(),
                }
            } else {
                manual_download("a portable copy")
            }
        }
        _ => match exe
            .ancestors()
            .find(|p| p.extension().is_some_and(|e| e == "app"))
        {
            Some(bundle) if bundle.parent().is_some_and(writable) => Install::MacApp {
                bundle: bundle.to_path_buf(),
            },
            Some(_) => manual_download("the app, in a folder Clairlune can't write to"),
            None => manual_download("a copy outside an app bundle"),
        },
    }
}

/// Whether Clairlune may write in `dir` (tried, not guessed).
fn writable(dir: &Path) -> bool {
    let probe = dir.join(format!(".clairlune-write-{}", std::process::id()));
    let ok = std::fs::create_dir(&probe).is_ok();
    let _ = std::fs::remove_dir(&probe);
    ok
}

/// A new version, downloaded, checked and ready to go in place.
#[derive(Debug)]
pub struct Prepared {
    pub install: Install,
    pub version: String,
    /// The download (setup.exe or DMG).
    pub file: PathBuf,
    /// macOS: the new app, copied out of the DMG next to the old one.
    pub staged: Option<PathBuf>,
}

/// Where downloads go while they're readied.
fn work_dir() -> PathBuf {
    std::env::temp_dir().join("clairlune-update")
}

/// Downloads `asset` for `install`, checks it and readies it. `progress`
/// hears the share done, 0 to 100.
pub fn prepare(
    install: &Install,
    asset: &Asset,
    version: &str,
    progress: &dyn Fn(u32),
) -> Result<Prepared, String> {
    let sha256 = asset
        .sha256
        .as_deref()
        .ok_or("the release lists no checksum for the download")?;
    let file = match install {
        Install::Manual { .. } => return Err("this install updates another way".into()),
        _ => {
            let dir = work_dir();
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
            dir.join(&asset.name)
        }
    };
    download(&asset.url, asset.size, &file, progress)?;
    let got = sha256_file(&file).map_err(|e| e.to_string())?;
    if !got.eq_ignore_ascii_case(sha256) {
        let _ = std::fs::remove_file(&file);
        return Err("the download doesn't match its checksum".into());
    }
    let staged = match install {
        Install::MacApp { bundle } => Some(stage_mac_app(&file, bundle, version)?),
        _ => None,
    };
    Ok(Prepared {
        install: install.clone(),
        version: version.to_string(),
        file,
        staged,
    })
}

/// Downloads `url` (`size` bytes) to `dest`, telling `progress` as it goes.
fn download(url: &str, size: u64, dest: &Path, progress: &dyn Fn(u32)) -> Result<(), String> {
    let agent = format!("Clairlune/{}", env!("CARGO_PKG_VERSION"));
    let mut cmd = std::process::Command::new(if cfg!(windows) { "curl.exe" } else { "curl" });
    cmd.args([
        "--silent",
        "--show-error",
        "--fail",
        "--location",
        "--max-time",
        "900",
        "--user-agent",
        &agent,
        "--output",
    ])
    .arg(dest)
    .arg(url)
    .stdin(std::process::Stdio::null())
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::piped());
    no_window(&mut cmd);
    let mut child = cmd.spawn().map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            "curl isn't installed".to_string()
        } else {
            e.to_string()
        }
    })?;
    let mut last = u32::MAX;
    let status = loop {
        if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
            break status;
        }
        let have = std::fs::metadata(dest).map_or(0, |m| m.len());
        let share = (have.saturating_mul(100) / size.max(1)).min(100) as u32;
        if share != last {
            progress(share);
            last = share;
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    };
    if !status.success() {
        let mut err = String::new();
        if let Some(mut e) = child.stderr.take() {
            use std::io::Read;
            let _ = e.read_to_string(&mut err);
        }
        let err = err.trim().trim_start_matches("curl: ");
        return Err(if err.is_empty() {
            "the download failed".into()
        } else {
            err.chars().take(120).collect()
        });
    }
    let have = std::fs::metadata(dest).map_or(0, |m| m.len());
    if have != size {
        return Err(format!("the download is {have} bytes, not {size}"));
    }
    progress(100);
    Ok(())
}

/// The file's SHA-256, as hex.
pub fn sha256_file(path: &Path) -> std::io::Result<String> {
    use sha2::{Digest, Sha256};
    use std::io::Read;
    let mut f = std::fs::File::open(path)?;
    let mut hash = Sha256::new();
    let mut buf = vec![0u8; 1 << 16];
    loop {
        let n = f.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hash.update(&buf[..n]);
    }
    Ok(hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// macOS: copies the app out of the DMG to a hidden folder next to the old
/// one (the same disk, so the swap is a rename) and checks it: its seal
/// holds and it is the version wanted.
fn stage_mac_app(dmg: &Path, bundle: &Path, version: &str) -> Result<PathBuf, String> {
    let run = |cmd: &mut std::process::Command| -> Result<String, String> {
        let out = cmd.output().map_err(|e| e.to_string())?;
        if out.status.success() {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        } else {
            Err(String::from_utf8_lossy(&out.stderr)
                .trim()
                .chars()
                .take(160)
                .collect())
        }
    };
    let parent = bundle.parent().ok_or("the app has no folder")?;
    let staged = parent.join(".Clairlune-update.app");
    let _ = std::fs::remove_dir_all(&staged);
    let mount = work_dir().join("mount");
    std::fs::create_dir_all(&mount).map_err(|e| e.to_string())?;
    run(std::process::Command::new("hdiutil")
        .args([
            "attach",
            "-nobrowse",
            "-readonly",
            "-noautoopen",
            "-mountpoint",
        ])
        .arg(&mount)
        .arg(dmg))
    .map_err(|e| format!("couldn't open the DMG: {e}"))?;
    let copied = run(std::process::Command::new("ditto")
        .arg(mount.join("Clairlune.app"))
        .arg(&staged));
    let _ = run(std::process::Command::new("hdiutil")
        .args(["detach", "-quiet"])
        .arg(&mount));
    copied.map_err(|e| format!("couldn't copy the new app: {e}"))?;
    let checked = run(std::process::Command::new("codesign")
        .args(["--verify", "--deep", "--strict"])
        .arg(&staged))
    .map_err(|e| format!("the new app's seal doesn't hold: {e}"))
    .and_then(|_| {
        run(std::process::Command::new("defaults")
            .arg("read")
            .arg(staged.join("Contents").join("Info.plist"))
            .arg("CFBundleShortVersionString"))
    })
    .and_then(|v| {
        if v == version {
            Ok(())
        } else {
            Err(format!("the DMG holds version {v}, not {version}"))
        }
    });
    if let Err(e) = checked {
        let _ = std::fs::remove_dir_all(&staged);
        return Err(e);
    }
    Ok(staged)
}

/// Starts the helper that, once this process (`pid`) is gone, puts the new
/// version in place and starts it with `relaunch` (or doesn't start it,
/// `None`). The caller quits right after.
pub fn finish(p: &Prepared, pid: u32, relaunch: Option<&[&str]>) -> Result<(), String> {
    let mut cmd = match &p.install {
        Install::WindowsSetup { exe } => {
            let script = windows_script(pid, &p.file, exe, relaunch);
            let mut c = std::process::Command::new("powershell.exe");
            c.args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
                "-WindowStyle",
                "Hidden",
                "-Command",
                &script,
            ]);
            c
        }
        Install::MacApp { bundle } => {
            let staged = p.staged.as_ref().ok_or("the new app isn't ready")?;
            let mut c = std::process::Command::new("/bin/sh");
            c.arg("-c")
                .arg(mac_swap_script(pid, staged, bundle, &p.file, relaunch));
            c
        }
        Install::Manual { .. } => return Err("this install updates another way".into()),
    };
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    no_window(&mut cmd);
    cmd.spawn().map(|_| ()).map_err(|e| e.to_string())
}

/// Starts the helper that, once this process (`pid`) is gone, deletes
/// Clairlune's folders (`dirs`; only folders named `clairlune`, as a
/// guard) and removes the app itself where it can. The caller quits right
/// after.
pub fn remove_after_exit(install: &Install, pid: u32, dirs: &[PathBuf]) -> Result<(), String> {
    let dirs: Vec<&PathBuf> = dirs.iter().filter(|d| is_clairlune_dir(d)).collect();
    let mut cmd = if cfg!(windows) {
        let mut s = format!(
            "$ErrorActionPreference = 'SilentlyContinue'; Wait-Process -Id {pid} -Timeout 120; "
        );
        if let Install::WindowsSetup { exe } = install
            && let Some(dir) = exe.parent()
        {
            // `_?=` runs it where it is (not from a copy that returns at
            // once), so the folder goes after it's done.
            let uninstaller = ps_quote(&dir.join("uninstall.exe").to_string_lossy());
            let arg = ps_quote(&format!("_?={}", dir.to_string_lossy()));
            s.push_str(&format!(
                "Start-Process -FilePath {uninstaller} -ArgumentList '/S',{arg} -Wait; Remove-Item -LiteralPath {} -Recurse -Force; ",
                ps_quote(&dir.to_string_lossy())
            ));
        }
        for d in &dirs {
            s.push_str(&format!(
                "Remove-Item -LiteralPath {} -Recurse -Force; ",
                ps_quote(&d.to_string_lossy())
            ));
        }
        let mut c = std::process::Command::new("powershell.exe");
        c.args([
            "-NoProfile",
            "-NonInteractive",
            "-ExecutionPolicy",
            "Bypass",
            "-WindowStyle",
            "Hidden",
            "-Command",
            &s,
        ]);
        c
    } else {
        let mut s = format!(
            "i=0; while kill -0 {pid} 2>/dev/null && [ $i -lt 600 ]; do sleep 0.2; i=$((i+1)); done; "
        );
        for d in &dirs {
            s.push_str(&format!("rm -rf {}; ", sh_quote(&d.to_string_lossy())));
        }
        if let Install::MacApp { bundle } = install {
            // To the Trash, under a name of its own there.
            let name = format!(
                "Clairlune {}.app",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map_or(0, |d| d.as_secs())
            );
            s.push_str(&format!(
                "mkdir -p \"$HOME/.Trash\" && mv {} \"$HOME/.Trash/\"{}; ",
                sh_quote(&bundle.to_string_lossy()),
                sh_quote(&name)
            ));
        }
        let mut c = std::process::Command::new("/bin/sh");
        c.arg("-c").arg(s);
        c
    };
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    no_window(&mut cmd);
    cmd.spawn().map(|_| ()).map_err(|e| e.to_string())
}

/// Only a folder named `clairlune` (any case) is ever deleted whole.
fn is_clairlune_dir(dir: &Path) -> bool {
    dir.file_name()
        .is_some_and(|n| n.to_string_lossy().eq_ignore_ascii_case("clairlune"))
        && dir.components().count() > 2
}

/// What identifies the program file on disk: a new copy put in its place
/// (Homebrew, a new DMG copy dragged over) has another
/// file underneath the same path.
#[derive(Clone, Debug, PartialEq)]
pub struct ExeStamp {
    len: u64,
    modified: Option<std::time::SystemTime>,
    /// Unix: device and inode (a replaced file is a new one).
    node: Option<(u64, u64)>,
}

/// The stamp of the program file this process runs from, or `None` while
/// it can't be read (mid-update).
pub fn exe_stamp() -> Option<ExeStamp> {
    let path = std::env::current_exe().ok()?;
    let m = std::fs::metadata(path).ok()?;
    #[cfg(unix)]
    let node = {
        use std::os::unix::fs::MetadataExt;
        Some((m.dev(), m.ino()))
    };
    #[cfg(not(unix))]
    let node = None;
    Some(ExeStamp {
        len: m.len(),
        modified: m.modified().ok(),
        node,
    })
}

/// Starts this program again, from where it is now on disk, once this
/// process (`pid`) is gone, with `args` (a new copy was put in its place).
/// The caller quits right after.
pub fn restart_after_exit(pid: u32, args: &[&str]) -> Result<(), String> {
    let exe = std::env::current_exe().map_err(|e| format!("no program path: {e}"))?;
    let mut cmd = if cfg!(windows) {
        let mut s = format!(
            "$ErrorActionPreference = 'SilentlyContinue'; Wait-Process -Id {pid} -Timeout 60; Start-Process -FilePath {}",
            ps_quote(&exe.to_string_lossy())
        );
        if !args.is_empty() {
            let list: Vec<String> = args.iter().map(|a| ps_quote(a)).collect();
            s.push_str(&format!(" -ArgumentList {}", list.join(",")));
        }
        let mut c = std::process::Command::new("powershell.exe");
        c.args([
            "-NoProfile",
            "-NonInteractive",
            "-WindowStyle",
            "Hidden",
            "-Command",
            &s,
        ]);
        c
    } else {
        let args: Vec<String> = args.iter().map(|a| sh_quote(a)).collect();
        let start = match exe
            .ancestors()
            .find(|p| p.extension().is_some_and(|e| e == "app"))
        {
            // macOS: through Launch Services, as the app was opened.
            Some(bundle) if cfg!(target_os = "macos") => {
                let mut s = format!("open {}", sh_quote(&bundle.to_string_lossy()));
                if !args.is_empty() {
                    s.push_str(&format!(" --args {}", args.join(" ")));
                }
                s
            }
            _ => format!(
                "nohup {} {} >/dev/null 2>&1 &",
                sh_quote(&exe.to_string_lossy()),
                args.join(" ")
            ),
        };
        let s = format!(
            "i=0; while kill -0 {pid} 2>/dev/null && [ $i -lt 300 ]; do sleep 0.2; i=$((i+1)); done; {start}"
        );
        let mut c = std::process::Command::new("/bin/sh");
        c.arg("-c").arg(s);
        c
    };
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    no_window(&mut cmd);
    cmd.spawn().map(|_| ()).map_err(|e| e.to_string())
}

/// PowerShell's single-quoted string.
fn ps_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "''"))
}

/// Windows: wait for Clairlune to quit, run setup.exe silently (`/NS`: no
/// new shortcuts; the first install made them), then start it again.
fn windows_script(pid: u32, setup: &Path, exe: &Path, relaunch: Option<&[&str]>) -> String {
    let setup = ps_quote(&setup.to_string_lossy());
    let exe = ps_quote(&exe.to_string_lossy());
    let mut s = format!(
        "$ErrorActionPreference = 'SilentlyContinue'; \
         Wait-Process -Id {pid} -Timeout 120; \
         Start-Process -FilePath {setup} -ArgumentList '/S','/NS' -Wait; \
         Remove-Item -LiteralPath {setup} -Force; "
    );
    match relaunch {
        Some([]) => s.push_str(&format!("Start-Process -FilePath {exe}")),
        Some(args) => {
            let list: Vec<String> = args.iter().map(|a| ps_quote(a)).collect();
            s.push_str(&format!(
                "Start-Process -FilePath {exe} -ArgumentList {}",
                list.join(",")
            ));
        }
        None => {}
    }
    s
}

/// A POSIX shell's single-quoted string.
fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// macOS: wait for Clairlune to quit, move the old app aside, the new one
/// in (putting the old back if that fails), then start it again with
/// `open` and tidy up.
fn mac_swap_script(
    pid: u32,
    new: &Path,
    target: &Path,
    download: &Path,
    relaunch: Option<&[&str]>,
) -> String {
    let new = sh_quote(&new.to_string_lossy());
    let target_q = sh_quote(&target.to_string_lossy());
    let old = sh_quote(&format!("{}.old", target.to_string_lossy()));
    let download = sh_quote(&download.to_string_lossy());
    let mut s = format!(
        "i=0; while kill -0 {pid} 2>/dev/null && [ $i -lt 600 ]; do sleep 0.2; i=$((i+1)); done; \
         rm -rf {old}; \
         if mv {target_q} {old}; then \
           if mv {new} {target_q}; then rm -rf {old}; else mv {old} {target_q}; fi; \
         fi; \
         rm -f {download}; "
    );
    if let Some(args) = relaunch {
        let args: Vec<String> = args.iter().map(|a| sh_quote(a)).collect();
        if args.is_empty() {
            s.push_str(&format!("open {target_q}"));
        } else {
            s.push_str(&format!("open {target_q} --args {}", args.join(" ")));
        }
    }
    s
}

/// Windows: no console window flashing up for a helper.
fn no_window(cmd: &mut std::process::Command) {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        cmd.creation_flags(CREATE_NO_WINDOW);
    }
    #[cfg(not(windows))]
    let _ = cmd;
}

/// `clairlune --install-latest` (for CI): installs the latest release over
/// this copy, whatever its version, without the app, then exits; the
/// helper starts the new version with `--version` (which only prints it).
/// Returns the exit code.
pub fn install_latest_now() -> i32 {
    let install = detect();
    eprintln!("install: {}", install.name());
    let release = match crate::update::fetch() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("couldn't ask GitHub: {e}");
            return 1;
        }
    };
    let Some(name) = install.asset_name(&release.version) else {
        eprintln!("{}", install.how().unwrap_or("nothing to install"));
        return 1;
    };
    let Some(asset) = release.assets.iter().find(|a| a.name == name) else {
        eprintln!("the release has no {name}");
        return 1;
    };
    eprintln!("downloading {} ({} bytes)", asset.name, asset.size);
    let prepared = match prepare(&install, asset, &release.version, &|_| {}) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("couldn't ready {}: {e}", release.version);
            return 1;
        }
    };
    match finish(&prepared, std::process::id(), Some(&["--version"])) {
        Ok(()) => {
            eprintln!("installing {} once this exits", release.version);
            0
        }
        Err(e) => {
            eprintln!("couldn't start the installer: {e}");
            1
        }
    }
}

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

    fn kind(exe: &str, os: &str, files: &[&str]) -> Install {
        let files: Vec<String> = files.iter().map(|f| f.to_string()).collect();
        classify(
            Path::new(exe),
            os,
            &|p| files.iter().any(|f| Path::new(f) == p),
            &|_| true,
        )
    }

    #[test]
    fn each_kind_of_install_is_told_apart() {
        // Forward slashes: every OS's Path splits them (the test runs on all).
        let setup = "C:/Users/a/AppData/Local/Clairlune/clairlune.exe";
        assert!(matches!(
            kind(
                setup,
                "windows",
                &["C:/Users/a/AppData/Local/Clairlune/uninstall.exe"]
            ),
            Install::WindowsSetup { .. }
        ));
        assert_eq!(kind(setup, "windows", &[]).name(), "a portable copy");
        let scoop = kind(
            r"C:\Users\a\scoop\apps\clairlune\current\clairlune.exe",
            "windows",
            &[],
        );
        assert_eq!(scoop.how(), Some("Update it with: scoop update clairlune"));
        let cargo = kind(r"C:\Users\a\.cargo\bin\clairlune.exe", "windows", &[]);
        assert_eq!(cargo.name(), "cargo install");
        assert_eq!(
            kind(
                "/Applications/Clairlune.app/Contents/MacOS/clairlune",
                "macos",
                &[]
            ),
            Install::MacApp {
                bundle: PathBuf::from("/Applications/Clairlune.app")
            }
        );
    }

    #[test]
    fn the_download_is_the_one_for_this_install() {
        let w = Install::WindowsSetup {
            exe: PathBuf::from("x"),
        };
        assert_eq!(
            w.asset_name("0.16.0").as_deref(),
            Some("clairlune_0.16.0_x64-setup.exe")
        );
        let m = Install::MacApp {
            bundle: PathBuf::from("x"),
        };
        assert!(m.asset_name("0.16.0").unwrap().ends_with(".dmg"));
        assert_eq!(manual_download("x").asset_name("0.16.0"), None);
    }

    #[test]
    fn the_helpers_quote_paths_with_quotes_in_them() {
        let ps = windows_script(
            42,
            Path::new(r"C:\Temp\it's\setup.exe"),
            Path::new(r"C:\Users\o'brien\clairlune.exe"),
            Some(&["--background"]),
        );
        assert!(ps.contains(r"'C:\Temp\it''s\setup.exe'"), "{ps}");
        assert!(ps.contains("Wait-Process -Id 42"), "{ps}");
        assert!(ps.ends_with("-ArgumentList '--background'"), "{ps}");
        let sh = mac_swap_script(
            7,
            Path::new("/Apps/.new.app"),
            Path::new("/Apps/Jo's Clairlune.app"),
            Path::new("/tmp/x.dmg"),
            Some(&[]),
        );
        assert!(sh.contains(r"'/Apps/Jo'\''s Clairlune.app'"), "{sh}");
        assert!(sh.ends_with(r"open '/Apps/Jo'\''s Clairlune.app'"), "{sh}");
        assert!(
            !windows_script(1, Path::new("s"), Path::new("e"), None)
                .contains("Start-Process -FilePath 'e'")
        );
    }

    #[test]
    fn this_program_has_a_stamp_that_stays_put() {
        let a = exe_stamp().expect("the test binary has a stamp");
        assert_eq!(exe_stamp(), Some(a));
    }

    #[test]
    fn only_clairlune_folders_are_deleted_whole() {
        assert!(is_clairlune_dir(Path::new(
            "/home/a/.local/share/clairlune"
        )));
        assert!(is_clairlune_dir(Path::new(
            "C:/Users/a/AppData/Local/Clairlune"
        )));
        assert!(!is_clairlune_dir(Path::new("/home/a")));
        assert!(!is_clairlune_dir(Path::new("/clairlune")));
        assert!(!is_clairlune_dir(Path::new("C:/Users/a/AppData/Local")));
    }

    #[test]
    fn removal_says_what_goes_and_how_to_finish() {
        let w = Install::WindowsSetup {
            exe: PathBuf::from("x"),
        };
        assert!(w.removal().is_ok());
        let scoop = Install::Manual {
            name: "Scoop".into(),
            how: String::new(),
        };
        assert_eq!(
            scoop.removal(),
            Err("Then remove the app with: scoop uninstall clairlune".to_string())
        );
    }

    #[test]
    fn a_file_hashes_like_sha256() {
        let dir = std::env::temp_dir().join(format!("clairlune-sha-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let f = dir.join("abc");
        std::fs::write(&f, b"abc").unwrap();
        assert_eq!(
            sha256_file(&f).unwrap(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Downloads this platform's file of the latest release for real and
    /// checks it (nothing is installed):
    /// `cargo test -p clairlune install -- --ignored`.
    #[test]
    #[ignore]
    fn the_latest_download_checks_out() {
        let r = crate::update::fetch().unwrap();
        let install = if cfg!(windows) {
            Install::WindowsSetup {
                exe: PathBuf::from("clairlune.exe"),
            }
        } else {
            Install::MacApp {
                bundle: std::env::temp_dir().join("Clairlune.app"),
            }
        };
        let name = install.asset_name(&r.version).unwrap();
        let asset = r.assets.iter().find(|a| a.name == name).unwrap();
        let seen = std::cell::RefCell::new(Vec::new());
        let p = prepare(&install, asset, &r.version, &|n| seen.borrow_mut().push(n)).unwrap();
        assert_eq!(seen.borrow().last(), Some(&100));
        eprintln!("ready: {p:?}");
        let _ = std::fs::remove_file(&p.file);
        if let Some(s) = &p.staged {
            let _ = std::fs::remove_dir_all(s);
        }
    }
}