shine-cli 2.0.0

Give personal automation a reviewable lifecycle
Documentation
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
use anyhow::{Result, bail};

use crate::config::{self, Config};
#[cfg(unix)]
use crate::privilege;
use crate::update_check::{self, ReleaseChannel, UpdateStatus};
use crate::{apps, colors, env, info, list, output, platform, shells, sys, version};
use shine_core::lifecycle::LifecycleOperation;
use shine_core::runtime::{
    AppPlanRequest, PlanningInputVersions, ShellPlanRequest, SysManagedPlanRequest,
};

pub async fn handle_update(
    config: &Config,
    target: Option<&str>,
    diff: bool,
    verbose: bool,
    refresh_release: bool,
    run_generators: bool,
) -> Result<()> {
    let compatibility = crate::preset_migration::active_compatibility_plan(target).await?;
    let migration_required = crate::preset_migration::compatibility_required(&compatibility);
    crate::preset_migration::print_compatibility(&compatibility);

    if let Some(target) = target {
        info::handle_update_target(config, target, run_generators).await?;
        if migration_required {
            bail!(
                "{}",
                crate::preset_migration::compatibility_failure_message(&compatibility)
            );
        }
        return Ok(());
    }

    let config_updates = if verbose {
        match Box::pin(list::handle_status_list(config, diff, run_generators)).await {
            Ok(()) => {
                println!();
                Ok(true)
            }
            Err(error) => Err(error),
        }
    } else {
        Box::pin(list::handle_update_list(config, diff, run_generators)).await
    };
    let (mut printed_update, config_update_error) = match config_updates {
        Ok(printed) => (printed, None),
        Err(error) => {
            eprintln!(
                "{}",
                colors::yellow_stderr(&format!(
                    "warning: configuration update check failed: {error:#}"
                ))
            );
            (false, Some(error))
        }
    };

    let current = version::semver();
    if verbose {
        println!("Checking for updates (current: {current})...");
    }

    let update_status = if refresh_release {
        update_check::check_for_update_forced(config).await
    } else {
        update_check::check_for_update(config).await
    };

    match update_status {
        Ok(UpdateStatus::UpToDate) => {
            if verbose {
                println!(
                    "{}",
                    colors::green(&format!("shine {current} is up to date."))
                );
            }
        }
        Ok(UpdateStatus::UpdateAvailable { latest }) => {
            if printed_update && !verbose {
                println!();
            }
            println!(
                "{}",
                colors::yellow(&format!(
                    "A newer version of shine is available: {current} -> {latest}."
                ))
            );
            println!("Run `shine self upgrade` to install it.");
            printed_update = true;
        }
        Ok(UpdateStatus::UpdateRequired { latest }) => {
            if printed_update && !verbose {
                println!();
            }
            println!(
                "{}",
                colors::yellow(&format!(
                    "A newer patch release of shine is available: {current} -> {latest}."
                ))
            );
            println!("Run `shine self upgrade` to install it.");
            printed_update = true;
        }
        Err(e) => {
            eprintln!("{}", format_update_check_failure_warning(&e));
        }
    }

    if !printed_update && config_update_error.is_none() && !migration_required {
        println!("{}", colors::dim("Nothing to update."));
    }

    if let Some(error) = config_update_error {
        return Err(error);
    }
    if migration_required {
        bail!(
            "{}",
            crate::preset_migration::compatibility_failure_message(&compatibility)
        );
    }

    Ok(())
}

fn format_update_check_failure_warning(err: &anyhow::Error) -> String {
    colors::yellow_stderr(&format!("warning: skipped shine version check: {err}"))
}

pub async fn handle_self_upgrade(config: &Config, channel: Option<ReleaseChannel>) -> Result<()> {
    let current = version::semver();
    let selected_channel = channel.unwrap_or(ReleaseChannel::Stable);
    let force_install = channel.is_some();
    println!(
        "Checking for {} upgrades (current: {current})...",
        selected_channel.as_str()
    );

    match update_check::upgrade_to_release(config, selected_channel, force_install).await {
        Ok(update_check::UpgradeResult::AlreadyUpToDate { channel, latest }) => {
            println!(
                "{}",
                colors::green(&format!(
                    "shine {current} is up to date on the {} channel ({latest}).",
                    channel.as_str()
                ))
            );
        }
        Ok(update_check::UpgradeResult::Upgraded {
            channel,
            previous: _,
            previous_display,
            release_tag,
            installed_version,
            installed_path,
        }) => {
            println!(
                "{}",
                colors::green(&format_self_upgrade_message(
                    channel,
                    &previous_display,
                    &installed_version,
                    &release_tag,
                ))
            );
            sync_self_install_dest(config, &installed_path).await;
        }
        Err(e) => {
            update_check::invalidate_update_cache(config).await;
            bail!("Upgrade failed: {e}");
        }
    }

    Ok(())
}

fn format_self_upgrade_message(
    channel: ReleaseChannel,
    previous_display: &str,
    installed_version: &str,
    release_tag: &str,
) -> String {
    match channel {
        ReleaseChannel::Stable => {
            format!("Upgraded shine from {previous_display} to {installed_version}.")
        }
        ReleaseChannel::Preview => {
            if previous_display.contains("-preview") {
                format!(
                    "Updated shine preview from {previous_display} to {installed_version} ({release_tag})."
                )
            } else {
                format!(
                    "Installed shine preview {installed_version} over stable {previous_display} ({release_tag})."
                )
            }
        }
    }
}

pub async fn handle_config_upgrade(
    config: &Config,
    target: Option<&str>,
    verbose: bool,
    prune_stale: bool,
    yes: bool,
) -> Result<()> {
    let compatibility = crate::preset_migration::active_compatibility_plan(target).await?;
    crate::preset_migration::print_compatibility(&compatibility);
    if crate::preset_migration::compatibility_required(&compatibility) {
        bail!(
            "{}",
            crate::preset_migration::compatibility_failure_message(&compatibility)
        );
    }
    if let Some(target) = target {
        return handle_config_target_upgrade(config, target, verbose, prune_stale, yes).await;
    }
    if verbose {
        println!("{}", colors::bold("Upgrading installed configs"));
        config::print_presets_note(config);
    }

    let mut sep = if verbose {
        output::SectionSeparator::new()
    } else {
        output::SectionSeparator::with_preamble(colors::bold("Upgrading installed configs"))
    };

    let env_report = Box::pin(env::upgrade::handle_upgrade(config, false, verbose)).await?;
    let os_id = sys::detect_os_id().await?;
    let reviewed = crate::lifecycle_plan::review_upgrade_plans(
        config,
        [
            crate::lifecycle_plan::LifecyclePlanRequest::shell(
                ShellPlanRequest {
                    operation: LifecycleOperation::Upgrade,
                    target: None,
                    force: false,
                    purge: false,
                    input_versions: PlanningInputVersions::default(),
                },
                config,
            ),
            crate::lifecycle_plan::LifecyclePlanRequest::app(
                AppPlanRequest {
                    operation: LifecycleOperation::Upgrade,
                    target: None,
                    force: false,
                    purge: false,
                    prune_stale,
                    input_versions: PlanningInputVersions::default(),
                },
                config,
            ),
            crate::lifecycle_plan::LifecyclePlanRequest::sys(
                SysManagedPlanRequest {
                    operation: LifecycleOperation::Upgrade,
                    os_id,
                    target: None,
                    input_versions: PlanningInputVersions::default(),
                },
                config,
            ),
        ],
        yes,
        verbose,
    )
    .await?;
    let mut prepared = crate::lifecycle_plan::prepare_plans(config, reviewed).await?;
    let shell_prepared = prepared.remove(0);
    let app_prepared = prepared.remove(0);
    let sys_prepared = prepared.remove(0);

    let (shell_report, shell_lifecycle) =
        Box::pin(shells::handle_upgrade_installed_with_result_prepared(
            config,
            verbose,
            shell_prepared,
            &mut sep,
        ))
        .await?;
    let (app_report, app_lifecycle) = Box::pin(
        apps::handle_upgrade_installed_with_output_with_result_prepared(
            config,
            prune_stale,
            verbose,
            app_prepared,
            &mut sep,
        ),
    )
    .await?;
    let (sys_report, _sys_lifecycle) = Box::pin(sys::handle_upgrade_managed_with_result_prepared(
        config,
        verbose,
        sys_prepared,
        &mut sep,
    ))
    .await?;

    let updated = env_report.updated
        + changed_shell_categories(&shell_lifecycle)
        + usize::from(shell_report.path_changed)
        + changed_app_categories(&app_lifecycle)
        + sys_report.updated;
    let user_modified = env_report.user_modified + preserved_app_resources(&app_lifecycle);

    let summary = config_upgrade_summary_parts(updated, user_modified, shell_report.link_conflicts);
    if verbose || sep.has_printed() {
        output::footer("Done", &summary);
    } else {
        println!("{}", colors::dim("Nothing to upgrade."));
    }
    for hint in &app_report.restart_hints {
        println!("  {} {}", colors::symbol("!"), colors::yellow(hint));
    }

    let fatal_app_failures = app_upgrade_failure_count(&app_report);
    if fatal_app_failures > 0 {
        bail!("{} app configuration item(s) failed", fatal_app_failures);
    }

    if sys_report.failed > 0 {
        bail!(
            "{} managed system configuration item(s) failed",
            sys_report.failed
        );
    }

    Ok(())
}

async fn handle_config_target_upgrade(
    config: &Config,
    target: &str,
    verbose: bool,
    prune_stale: bool,
    yes: bool,
) -> Result<()> {
    use crate::shim::{PresetKind, resolve_preset_kind};

    let target = target.trim();
    if target.is_empty() {
        bail!("upgrade target must not be empty");
    }

    let mut sep = if verbose {
        println!("{}", colors::bold(&format!("Upgrading {target}")));
        config::print_presets_note(config);
        output::SectionSeparator::new()
    } else {
        output::SectionSeparator::with_preamble(colors::bold(&format!("Upgrading {target}")))
    };

    let (updated, user_modified, link_conflicts, failed, restart_hints) =
        if let Some(item) = target.strip_prefix("sys/") {
            if item.is_empty() || item.contains('/') {
                bail!("invalid system target `{target}`; expected sys/<item>");
            }
            if prune_stale {
                bail!("`--prune-stale` applies only to app targets");
            }
            let (report, lifecycle) =
                Box::pin(sys::handle_upgrade_managed_target_with_result_approved(
                    config,
                    Some(item),
                    verbose,
                    yes,
                    &mut sep,
                ))
                .await?;
            (
                lifecycle.summary().changed,
                lifecycle.summary().preserved + lifecycle.summary().conflicts,
                0,
                report.failed,
                Default::default(),
            )
        } else {
            let normalized = if let Some(rest) = target.strip_prefix("app/") {
                let category = rest.split('/').next().unwrap_or_default();
                format!("app/{category}")
            } else if let Some(rest) = target.strip_prefix("shell/") {
                let category = rest.split('/').next().unwrap_or_default();
                format!("shell/{category}")
            } else {
                target.to_string()
            };
            let (kind, category) = resolve_preset_kind(config, &normalized).await?;
            match kind {
                PresetKind::App => {
                    let (report, lifecycle) =
                        Box::pin(apps::handle_upgrade_installed_target_with_result_approved(
                            config,
                            Some(&category),
                            prune_stale,
                            verbose,
                            yes,
                            &mut sep,
                        ))
                        .await?;
                    (
                        changed_app_categories(&lifecycle),
                        preserved_app_resources(&lifecycle),
                        0,
                        app_upgrade_failure_count(&report),
                        report.restart_hints,
                    )
                }
                PresetKind::Shell => {
                    if prune_stale {
                        bail!("`--prune-stale` applies only to app targets");
                    }
                    let (report, lifecycle) = Box::pin(
                        shells::handle_upgrade_installed_target_with_result_approved(
                            config,
                            Some(&category),
                            verbose,
                            yes,
                            &mut sep,
                        ),
                    )
                    .await?;
                    (
                        changed_shell_categories(&lifecycle) + usize::from(report.path_changed),
                        0,
                        lifecycle.summary().conflicts,
                        0,
                        Default::default(),
                    )
                }
            }
        };

    let summary = config_upgrade_summary_parts(updated, user_modified, link_conflicts);
    if verbose || sep.has_printed() {
        output::footer("Done", &summary);
    } else {
        println!("{}", colors::dim("Nothing to upgrade."));
    }
    for hint in restart_hints {
        println!("  {} {}", colors::symbol("!"), colors::yellow(&hint));
    }
    if failed > 0 {
        bail!("{failed} managed configuration item(s) failed");
    }
    Ok(())
}

fn config_upgrade_summary_parts(
    updated: usize,
    user_modified: usize,
    link_conflicts: usize,
) -> Vec<String> {
    let mut parts = Vec::new();
    output::push_count(&mut parts, updated, colors::green, "updated");
    output::push_count(
        &mut parts,
        user_modified,
        colors::yellow,
        "user-modified (kept)",
    );
    output::push_count(&mut parts, link_conflicts, colors::yellow, "link conflicts");
    parts
}

fn app_upgrade_failure_count(report: &apps::AppUpgradeReport) -> usize {
    report.failed
}

fn changed_shell_categories(result: &shine_core::lifecycle::LifecycleResultV1) -> usize {
    result
        .outcomes
        .iter()
        .filter(|outcome| {
            outcome.status == shine_core::lifecycle::LifecycleStatus::Changed
                && outcome.target.starts_with("shell/")
                && outcome.effects.iter().any(|effect| {
                    !matches!(effect, shine_core::lifecycle::LifecycleEffect::CacheWritten)
                })
        })
        .filter_map(|outcome| outcome.target.split('/').nth(1))
        .collect::<std::collections::BTreeSet<_>>()
        .len()
}

fn is_app_auxiliary_resource(resource: Option<&str>) -> bool {
    matches!(
        resource,
        Some(
            "preset-cache"
                | "purge"
                | "hook:post-install"
                | "hook:post-upgrade"
                | "artifact:teardown"
        )
    )
}

fn changed_app_categories(result: &shine_core::lifecycle::LifecycleResultV1) -> usize {
    result
        .outcomes
        .iter()
        .filter(|outcome| {
            outcome.status == shine_core::lifecycle::LifecycleStatus::Changed
                && outcome.target.starts_with("app/")
                && !is_app_auxiliary_resource(outcome.resource.as_deref())
        })
        .map(|outcome| outcome.target.as_str())
        .collect::<std::collections::BTreeSet<_>>()
        .len()
}

fn preserved_app_resources(result: &shine_core::lifecycle::LifecycleResultV1) -> usize {
    result
        .outcomes
        .iter()
        .filter(|outcome| {
            matches!(
                outcome.status,
                shine_core::lifecycle::LifecycleStatus::Preserved
                    | shine_core::lifecycle::LifecycleStatus::Conflict
            ) && outcome.target.starts_with("app/")
                && !is_app_auxiliary_resource(outcome.resource.as_deref())
        })
        .count()
}

/// After a successful self-upgrade, try to sync the new binary to the self-install destination.
/// If the copy fails due to permissions, print a targeted hint instead of failing.
async fn sync_self_install_dest(config: &Config, src: &std::path::Path) {
    let dest = match &config.self_install_dest {
        Some(d) => d,
        None => return,
    };
    match sync_self_install_dest_from(src, dest).await {
        Ok(SelfInstallSync::Synced) => println!(
            "{}",
            colors::green(&format!("Synced system copy at {}", dest.display()))
        ),
        Ok(SelfInstallSync::AlreadyCurrent) => {}
        // Unix already tried `sudo` automatically inside `install_binary_with_elevation`;
        // reaching here means it was declined or unavailable non-interactively. Windows has
        // no such auto-elevation path, so it still needs the manual hint.
        Err(e) if cfg!(windows) && has_io_error_kind(&e, std::io::ErrorKind::PermissionDenied) => {
            let hint = format!(
                "Installed copy at {} needs manual sync; rerun from an elevated terminal if needed.",
                dest.display()
            );
            println!("{}", colors::yellow(&hint));
        }
        Err(e) => eprintln!(
            "Warning: failed to sync system copy at {}: {e}",
            dest.display()
        ),
    }
}

enum SelfInstallSync {
    Synced,
    AlreadyCurrent,
}

async fn sync_self_install_dest_from(
    src: &std::path::Path,
    dest: &std::path::Path,
) -> Result<SelfInstallSync> {
    if dest.exists() {
        let canonical_src = src.canonicalize().unwrap_or_else(|_| src.to_path_buf());
        let canonical_dest = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
        if canonical_src == canonical_dest {
            return Ok(SelfInstallSync::AlreadyCurrent);
        }
    }

    install_binary_with_elevation(src, dest)
        .await
        .map(|()| SelfInstallSync::Synced)
}

fn has_io_error_kind(err: &anyhow::Error, kind: std::io::ErrorKind) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|io_err| io_err.kind() == kind)
    })
}

pub async fn handle_self_install(
    mut config: Config,
    dest: Option<std::path::PathBuf>,
) -> Result<()> {
    use anyhow::{Context as _, bail};

    let src = std::env::current_exe().context("failed to resolve current executable path")?;
    let dest = match dest {
        Some(dest) => dest,
        None => platform::default_self_install_dest()?,
    };

    if dest.exists() {
        let canonical_src = src.canonicalize().unwrap_or_else(|_| src.clone());
        let canonical_dest = dest.canonicalize().unwrap_or_else(|_| dest.clone());
        if canonical_src == canonical_dest {
            let example = if cfg!(windows) {
                r"C:\path\to\new\shine.exe self install"
            } else {
                "sudo /path/to/new/shine self install"
            };
            bail!(
                "source and destination are the same binary: {}. Run the newer binary by full path, e.g. `{example}`, to overwrite this copy.",
                dest.display()
            );
        }
    }

    install_binary_with_elevation(&src, &dest)
        .await
        .with_context(|| self_install_failure_hint(&dest))?;

    // Remember where we installed so `shine self upgrade` can sync this copy automatically.
    config.self_install_dest = Some(dest.clone());
    config
        .save()
        .await
        .context("failed to save self_install_dest to config")?;

    println!(
        "{}",
        colors::green(&format!("installed to {}", dest.display()))
    );
    print_self_install_activation_hint(&dest);

    Ok(())
}

fn self_install_failure_hint(dest: &std::path::Path) -> String {
    format!("failed to copy to {}", dest.display())
}

fn print_self_install_activation_hint(dest: &std::path::Path) {
    let Some(dir) = dest.parent() else {
        return;
    };
    if platform::current_path_contains_dir(dir) {
        println!(
            "{}",
            colors::dim("The install directory is already on PATH.")
        );
    } else {
        println!(
            "{}",
            colors::yellow(&format!(
                "Install directory is not on PATH: {}",
                dir.display()
            ))
        );
        println!("{}", colors::dim(&platform::path_install_hint(dir)));
    }
}

fn install_binary_atomically(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    use anyhow::Context as _;

    let parent = dest
        .parent()
        .with_context(|| format!("destination has no parent: {}", dest.display()))?;
    std::fs::create_dir_all(parent)
        .with_context(|| format!("failed to create destination dir: {}", parent.display()))?;

    let temp = parent.join(format!(".shine-self-install-{}", uuid::Uuid::new_v4()));
    std::fs::copy(src, &temp).with_context(|| {
        format!(
            "failed to stage binary from {} to {}",
            src.display(),
            temp.display()
        )
    })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(src)
            .map(|m| m.permissions().mode())
            .unwrap_or(0o755);
        std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(mode))
            .with_context(|| format!("failed to set permissions on {}", temp.display()))?;
    }

    match std::fs::rename(&temp, dest) {
        Ok(()) => Ok(()),
        Err(err) => {
            let _ = std::fs::remove_file(&temp);
            Err(err)
                .with_context(|| format!("failed to replace {} with staged binary", dest.display()))
        }
    }
}

/// Installs the binary, auto-elevating via `sudo` on Unix if the plain copy
/// fails because the destination isn't user-writable (e.g. `/usr/local/bin`
/// owned by root). The CLI-owned administrator adapter serializes this with
/// other privileged Shine writes so parallel installs cannot race.
async fn install_binary_with_elevation(
    src: &std::path::Path,
    dest: &std::path::Path,
) -> Result<()> {
    match install_binary_atomically(src, dest) {
        Ok(()) => Ok(()),
        Err(e)
            if !cfg!(windows)
                && has_io_error_kind(&e, std::io::ErrorKind::PermissionDenied)
                && !std::env::var("USER").is_ok_and(|user| user == "root") =>
        {
            let _lock = crate::admin_fs::admin_lock().await?;
            install_binary_privileged(src, dest).await
        }
        Err(e) => Err(e),
    }
}

#[cfg(unix)]
async fn install_binary_privileged(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    use anyhow::Context as _;
    use std::os::unix::fs::PermissionsExt;

    if !privilege::ensure_admin(1).await? {
        anyhow::bail!("administrator permission was not granted");
    }

    let parent = dest
        .parent()
        .with_context(|| format!("destination has no parent: {}", dest.display()))?;
    let mode = std::fs::metadata(src)
        .map(|m| m.permissions().mode())
        .unwrap_or(0o755);

    let status = crate::admin_fs::sudo_command()
        .arg("mkdir")
        .arg("-p")
        .arg(parent)
        .status()
        .await
        .context("failed to create privileged destination directory")?;
    if !status.success() {
        anyhow::bail!("administrator permission was not granted");
    }

    let status = crate::admin_fs::sudo_command()
        .args(["install", "-m", &format!("{mode:o}"), "--"])
        .arg(src)
        .arg(dest)
        .status()
        .await
        .context("failed to install shine binary with administrator privileges")?;
    if !status.success() {
        anyhow::bail!("failed to install shine binary with administrator privileges");
    }

    Ok(())
}

#[cfg(not(unix))]
async fn install_binary_privileged(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    // No auto-elevation path on Windows: privileged binary copies go through
    // an elevated terminal instead. Fall back to the plain unprivileged copy
    // so the caller's original error surfaces if it still fails.
    install_binary_atomically(src, dest)
}

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

    async fn make_temp_dir() -> std::path::PathBuf {
        crate::test_support::make_temp_dir("shine-self-install-test").await
    }

    fn config_in(dir: &std::path::Path) -> Config {
        crate::test_support::test_config(dir)
    }

    #[test]
    fn install_binary_atomically_overwrites_existing_dest() {
        let dir = std::env::temp_dir().join(format!("shine-self-install-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let src = dir.join("new-shine");
        let dest = dir.join("shine");

        std::fs::write(&src, b"new").unwrap();
        std::fs::write(&dest, b"old").unwrap();

        install_binary_atomically(&src, &dest).unwrap();

        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn sync_self_install_dest_creates_missing_parent() {
        let dir = std::env::temp_dir().join(format!("shine-self-sync-{}", uuid::Uuid::new_v4()));
        let src = dir.join("new-shine");
        let dest = dir.join("usr/local/bin/shine");

        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&src, b"new").unwrap();

        let outcome = sync_self_install_dest_from(&src, &dest).await.unwrap();

        assert!(matches!(outcome, SelfInstallSync::Synced));
        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn sync_self_install_dest_skips_current_exe_path() {
        let dir = std::env::temp_dir().join(format!("shine-self-sync-{}", uuid::Uuid::new_v4()));
        let src = dir.join("shine");

        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&src, b"new").unwrap();

        let outcome = sync_self_install_dest_from(&src, &src).await.unwrap();

        assert!(matches!(outcome, SelfInstallSync::AlreadyCurrent));
        assert_eq!(std::fs::read(&src).unwrap(), b"new");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn self_install_errors_when_source_is_destination() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir);
        let current = std::env::current_exe().unwrap();

        let err = handle_self_install(config, Some(current))
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("source and destination are the same binary"),
            "error should explain self-overwrite: {err:#}"
        );

        tokio::fs::remove_dir_all(&dir).await.unwrap();
    }

    #[test]
    fn update_check_failure_warning_is_non_fatal_wording() {
        let err = anyhow::anyhow!(
            "GitHub stable release request failed: HTTP 403 Forbidden: API rate limit exceeded"
        );
        let warning = format_update_check_failure_warning(&err);

        assert!(warning.contains("warning: skipped shine version check"));
        assert!(warning.contains("HTTP 403 Forbidden"));
        assert!(!warning.contains("Update check failed"));
    }

    #[test]
    fn config_upgrade_summary_parts_includes_only_nonzero_counts() {
        assert_eq!(
            config_upgrade_summary_parts(2, 0, 0),
            vec!["2 updated".to_string()]
        );
    }

    #[test]
    fn config_upgrade_summary_parts_empty_when_all_zero() {
        assert!(config_upgrade_summary_parts(0, 0, 0).is_empty());
    }

    #[test]
    fn config_upgrade_summary_parts_reports_actionable_counters() {
        assert_eq!(
            config_upgrade_summary_parts(1, 2, 3),
            vec![
                "1 updated".to_string(),
                "2 user-modified (kept)".to_string(),
                "3 link conflicts".to_string(),
            ]
        );
    }

    #[test]
    fn app_upgrade_failure_count_uses_the_authoritative_report_total() {
        let report = apps::AppUpgradeReport {
            failed: 3,
            ..Default::default()
        };

        assert_eq!(app_upgrade_failure_count(&report), 3);
    }

    #[test]
    fn format_self_upgrade_message_handles_stable_channel() {
        assert_eq!(
            format_self_upgrade_message(ReleaseChannel::Stable, "0.21.3", "0.21.4", "v0.21.4",),
            "Upgraded shine from 0.21.3 to 0.21.4."
        );
    }

    #[test]
    fn format_self_upgrade_message_handles_stable_to_preview_install() {
        assert_eq!(
            format_self_upgrade_message(
                ReleaseChannel::Preview,
                "0.21.3",
                "1.0.0-preview",
                "preview",
            ),
            "Installed shine preview 1.0.0-preview over stable 0.21.3 (preview)."
        );
    }

    #[test]
    fn format_self_upgrade_message_handles_preview_to_preview_update() {
        assert_eq!(
            format_self_upgrade_message(
                ReleaseChannel::Preview,
                "1.0.0-preview",
                "1.0.1-preview",
                "preview",
            ),
            "Updated shine preview from 1.0.0-preview to 1.0.1-preview (preview)."
        );
    }
}