zc2 0.0.29

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! `zc update [--from-source]` — self-update the running `zc` binary.
//!
//! Default mode downloads the latest prebuilt release asset for the running
//! platform (`zc-linux-x86_64`, `zc-linux-arm64`, ...) from the
//! `zakuro-ai/zc` GitHub releases and replaces
//! the currently-running binary in place. `--from-source` instead clones the
//! (private) `zakuro-ai/zc` repo, runs `cargo build --release`, and installs
//! the freshly-built binary over the current one. The repo is private, so
//! both need a GitHub token that can see it (see [`resolve_token`]).
//!
//! Binary replacement is done by writing the new bytes to a temp file in the
//! same directory as the current executable, chmod'ing it 0755, then
//! `rename()`-ing it over the running binary's path — this works on Linux
//! even while the original file is busy/executing.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use ureq::config::{ConfigBuilder, RedirectAuthHeaders};
use ureq::http::{StatusCode, Uri};
use ureq::typestate::AgentScope;

const REPO_API_LATEST: &str = "https://api.github.com/repos/zakuro-ai/zc/releases/latest";
const REPO_CLONE_HOST: &str = "github.com/zakuro-ai/zc";
/// The `Accept` header that makes a release asset's API `url` answer with the
/// asset's bytes (through a redirect) instead of its JSON description.
const OCTET_STREAM: &str = "application/octet-stream";
/// The most `zc update` reads of a release binary. ureq's default body limit
/// (10 MiB) is smaller than a release binary: v0.0.26's are 14–17 MB.
const MAX_BINARY_BYTES: u64 = 256 * 1024 * 1024;
/// What `zc update` says when the releases API answers 404 and no token was
/// found: GitHub answers 404 for a private repo it won't show you.
const PRIVATE_RELEASES: &str = "zc releases are private. Sign in with `gh auth login` (or set GH_PAT / GITHUB_TOKEN) and run zc update again.";
/// The fallback suggested when the prebuilt release can't be installed.
const FROM_SOURCE_FALLBACK: &str = "Fallback: try building from source instead — `zc update --from-source` (it also needs a GitHub token with access to zakuro-ai/zc).";
/// Release asset name for the host platform. Must match the names uploaded by
/// .github/workflows/release.yml.
fn asset_name() -> &'static str {
    match (cfg!(target_os = "macos"), cfg!(target_arch = "aarch64")) {
        (true, true) => "zc-darwin-arm64",
        (true, false) => "zc-darwin-x86_64",
        (false, true) => "zc-linux-arm64",
        (false, false) => "zc-linux-x86_64",
    }
}

/// Which update strategy to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Download the latest prebuilt release binary.
    PrebuiltRelease,
    /// Clone the source repo and `cargo build --release`.
    FromSource,
}

/// Parse `zc update [--from-source]` args into a [`Mode`]. Pure/testable —
/// takes plain string slices, no process spawning.
pub fn parse_mode(args: &[String]) -> Mode {
    if args.iter().any(|a| a == "--from-source") {
        Mode::FromSource
    } else {
        Mode::PrebuiltRelease
    }
}

/// Resolve a GitHub auth token, in precedence order:
///   1. `try_gh()` — e.g. `gh auth token` via the GitHub CLI
///   2. `get_env("GH_PAT")`
///   3. `get_env("GITHUB_TOKEN")`
///
/// Both dependencies are injected so this is unit-testable without spawning
/// a real `gh` process or touching real process env vars.
pub fn resolve_token<F1, F2>(try_gh: F1, get_env: F2) -> Option<String>
where
    F1: FnOnce() -> Option<String>,
    F2: Fn(&str) -> Option<String>,
{
    if let Some(t) = try_gh() {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GH_PAT") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GITHUB_TOKEN") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    None
}

/// Real `gh auth token` lookup — returns `None` if `gh` isn't installed,
/// isn't authenticated, or the call otherwise fails.
fn gh_auth_token() -> Option<String> {
    let out = Command::new("gh").args(["auth", "token"]).output().ok()?;
    if !out.status.success() {
        return None;
    }
    let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if token.is_empty() {
        None
    } else {
        Some(token)
    }
}

fn real_env(key: &str) -> Option<String> {
    std::env::var(key).ok()
}

/// Entry point mirroring the other subcommand modules' `run_cli` convention
/// (see `vpn::run_cli`). Returns the process exit code: 0 once the new binary
/// is installed, 1 on any failure.
pub fn run_cli(args: &[String]) -> i32 {
    match parse_mode(args) {
        Mode::PrebuiltRelease => update_from_release(),
        Mode::FromSource => update_from_source(),
    }
}

/// Atomically replace the file at `exe_path` with `bytes`: write to a temp
/// file alongside it, chmod 0755, then `rename()` over the target. `rename`
/// within the same filesystem works on Linux even while `exe_path` is the
/// currently-running binary.
fn replace_binary_atomic(exe_path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    let dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let tmp_path: PathBuf = dir.join(format!(".zc-update-{}.tmp", std::process::id()));
    std::fs::write(&tmp_path, bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
    }
    std::fs::rename(&tmp_path, exe_path)?;
    Ok(())
}

fn current_exe_or_bail() -> Option<PathBuf> {
    match std::env::current_exe() {
        Ok(p) => Some(p),
        Err(e) => {
            eprintln!(
                "Error: could not determine the current executable path: {}",
                e
            );
            None
        }
    }
}

/// Can we create (and remove) a file in `dir`? Used to decide whether we can
/// update the running binary in place, or must fall back to ~/.local/bin.
fn dir_writable(dir: &Path) -> bool {
    let probe = dir.join(format!(".zc-write-probe-{}", std::process::id()));
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

fn local_bin_zc() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join(".local").join("bin").join("zc")
}

/// Choose a user-writable install target. Prefer replacing the running binary in
/// place; if its directory isn't writable (e.g. root-owned /usr/local/bin), fall
/// back to ~/.local/bin/zc so the update never needs sudo. Returns
/// `(path, installed_to_local_bin)`.
fn resolve_install_target() -> (PathBuf, bool) {
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            if dir_writable(dir) {
                return (exe, false);
            }
        }
    }
    (local_bin_zc(), true)
}

/// Append `line` to `path` unless it's already present. Returns Ok(true) if it
/// was added, Ok(false) if it was already there.
fn append_line_once(path: &Path, line: &str) -> std::io::Result<bool> {
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    if existing.lines().any(|l| l.trim() == line.trim()) {
        return Ok(false);
    }
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    let sep = if existing.is_empty() || existing.ends_with('\n') {
        ""
    } else {
        "\n"
    };
    writeln!(
        f,
        "{}# added by `zc update` — put ~/.local/bin on PATH\n{}",
        sep, line
    )?;
    Ok(true)
}

/// The shell rc file to persist a PATH change into, inferred from $SHELL.
fn shell_rc_path() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let shell = std::env::var("SHELL").unwrap_or_default();
    let file = if shell.contains("zsh") {
        ".zshrc"
    } else if shell.contains("bash") {
        ".bashrc"
    } else {
        ".profile"
    };
    Some(PathBuf::from(home).join(file))
}

/// After a ~/.local/bin install, make sure that dir is on PATH: append the
/// export to the shell rc if missing, and tell the user how to pick it up.
fn ensure_local_bin_on_path(installed: &Path) {
    let bin_dir = installed
        .parent()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let on_path = std::env::var("PATH")
        .map(|p| p.split(':').any(|d| d == bin_dir))
        .unwrap_or(false);

    if on_path {
        println!("Installed to {}.", installed.display());
        println!("Run `hash -r` (or open a new terminal) so your shell uses the new binary.");
        return;
    }

    let export = "export PATH=\"$HOME/.local/bin:$PATH\"".to_string();
    let appended = shell_rc_path().and_then(|rc| {
        let ok = append_line_once(&rc, &export).unwrap_or(false);
        ok.then_some(rc)
    });

    println!("Installed to {}.", installed.display());
    match appended {
        Some(rc) => {
            println!("Added ~/.local/bin to your PATH in {}.", rc.display());
            println!(
                "Open a new terminal (or `source {}`) and run `zc`.",
                rc.display()
            );
        }
        None => {
            println!("Add ~/.local/bin to your PATH so `zc` is found:");
            println!("    {}", export);
        }
    }
    // An older zc elsewhere on PATH (e.g. /usr/local/bin) is now shadowed by the
    // prepended dir; remove it if you like: `sudo rm /usr/local/bin/zc`.
}

/// Where to download a release asset from, and the `Accept` header to send.
#[derive(Debug, PartialEq, Eq)]
struct AssetSource {
    url: String,
    accept: &'static str,
}

/// The source of the asset called `name` in `release` (a releases API
/// response), or `None` when the release has no such asset.
///
/// The asset's API `url`, fetched with `Accept: application/octet-stream`,
/// redirects to the bytes, and works for a private repo when the token can
/// see it. `browser_download_url` answers 404 for a private repo, token or
/// not, so it is only the fallback for a response without `url`.
fn select_asset(release: &serde_json::Value, name: &str) -> Option<AssetSource> {
    let asset = release
        .get("assets")?
        .as_array()?
        .iter()
        .find(|a| a.get("name").and_then(|n| n.as_str()) == Some(name))?;
    let field = |key: &str| asset.get(key).and_then(|v| v.as_str()).map(str::to_string);
    match field("url") {
        Some(url) => Some(AssetSource {
            url,
            accept: OCTET_STREAM,
        }),
        None => field("browser_download_url").map(|url| AssetSource { url, accept: "*/*" }),
    }
}

/// `token` if a request to `url` may carry it: only an https request whose
/// host is exactly `api.github.com`. The download URL comes from the release
/// JSON, and its `browser_download_url` fallback is on github.com.
fn token_for<'a>(url: &str, token: Option<&'a str>) -> Option<&'a str> {
    let uri: Uri = url.parse().ok()?;
    let github_api = uri.scheme_str() == Some("https")
        && uri
            .host()
            .is_some_and(|h| h.eq_ignore_ascii_case("api.github.com"));
    token.filter(|_| github_api)
}

/// Headers for a request to GitHub: `User-Agent`, `Accept`, and
/// `Authorization` when given a token. Callers pass the token through
/// [`token_for`] first, and the download drops it on the redirect to the
/// storage host (see [`download_config`]).
fn github_headers(accept: &str, token: Option<&str>) -> Vec<(&'static str, String)> {
    let mut headers = vec![
        ("User-Agent", "zc-update".to_string()),
        ("Accept", accept.to_string()),
    ];
    if let Some(t) = token {
        headers.push(("Authorization", format!("Bearer {t}")));
    }
    headers
}

/// The releases API call: a small JSON document, so 30 s. Error statuses come
/// back as responses rather than errors, so a 404 can be explained.
fn api_config() -> ConfigBuilder<AgentScope> {
    ureq::Agent::config_builder()
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_global(Some(Duration::from_secs(30)))
        .http_status_as_error(false)
}

/// The asset download: 300 s, since under the API call's 30 s a 14–17 MB
/// release binary would need about 0.5 MB/s. GitHub answers the asset's API
/// `url` with a 302 to a signed storage URL, and the storage host rejects a
/// request that carries both that signature and an `Authorization` header,
/// so redirects are followed without it: `RedirectAuthHeaders::Never`
/// removes `Authorization` from every redirected request. It is also ureq's
/// default; setting it here means nothing depends on that.
fn download_config() -> ConfigBuilder<AgentScope> {
    ureq::Agent::config_builder()
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_global(Some(Duration::from_secs(300)))
        .http_status_as_error(false)
        .redirect_auth_headers(RedirectAuthHeaders::Never)
}

/// What to print when the releases API answers `status` instead of 200.
fn api_status_message(status: StatusCode, have_token: bool) -> String {
    if status != StatusCode::NOT_FOUND {
        format!("GitHub releases API returned HTTP {status}\n{FROM_SOURCE_FALLBACK}")
    } else if !have_token {
        PRIVATE_RELEASES.to_string()
    } else {
        format!(
            "GitHub releases API returned HTTP {status}: the GitHub token zc found may not have access to zakuro-ai/zc (the repo is private), or there is no release yet.\n\
             Check its account with `gh auth status`; zc uses gh's token first, then GH_PAT, then GITHUB_TOKEN.\n\
             {FROM_SOURCE_FALLBACK}"
        )
    }
}

/// GET `src` and return the final response's body, following redirects as
/// `agent` is configured to. `token` goes in the first request's
/// `Authorization` header, so callers pass it through [`token_for`] first.
fn download(
    agent: &ureq::Agent,
    src: &AssetSource,
    token: Option<&str>,
) -> Result<Vec<u8>, String> {
    let mut req = agent.get(&src.url);
    for (name, value) in github_headers(src.accept, token) {
        req = req.header(name, value);
    }
    let resp = req
        .call()
        .map_err(|e| format!("Failed to download release asset: {e}"))?;
    if resp.status() != StatusCode::OK {
        return Err(format!("Download failed: HTTP {}", resp.status()));
    }
    resp.into_body()
        .with_config()
        .limit(MAX_BINARY_BYTES)
        .read_to_vec()
        .map_err(|e| format!("Failed to read downloaded binary: {e}"))
}

fn update_from_release() -> i32 {
    println!("Checking latest zc release...");

    // zakuro-ai/zc is private: without a token the releases API answers 404.
    let token = resolve_token(gh_auth_token, real_env);

    let api = ureq::Agent::new_with_config(api_config().build());
    let mut req = api.get(REPO_API_LATEST);
    let api_token = token_for(REPO_API_LATEST, token.as_deref());
    for (name, value) in github_headers("application/vnd.github+json", api_token) {
        req = req.header(name, value);
    }

    let resp = match req.call() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Failed to reach GitHub releases API: {}", e);
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    if resp.status() != StatusCode::OK {
        eprintln!("{}", api_status_message(resp.status(), api_token.is_some()));
        return 1;
    }

    let body = match resp.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Failed to read releases API response: {}", e);
            return 1;
        }
    };

    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Failed to parse releases API response: {}", e);
            return 1;
        }
    };

    let version = data
        .get("tag_name")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let src = match select_asset(&data, asset_name()) {
        Some(s) => s,
        None => {
            eprintln!("No {} asset found on release {}.", asset_name(), version);
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    println!("Downloading {} ({})...", asset_name(), version);

    let downloader = ureq::Agent::new_with_config(download_config().build());
    let bytes = match download(&downloader, &src, token_for(&src.url, token.as_deref())) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{e}");
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, &bytes) {
        eprintln!("Failed to install the new binary: {}", e);
        return 1;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    println!("updated to {}", version);
    0
}

fn update_from_source() -> i32 {
    let token = match resolve_token(gh_auth_token, real_env) {
        Some(t) => t,
        None => {
            eprintln!("no GitHub token found; run `gh auth login` or set GH_PAT/GITHUB_TOKEN");
            return 1;
        }
    };

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let tmp_dir = std::env::temp_dir().join(format!("zc-update-src-{}", std::process::id()));
    if let Err(e) = std::fs::create_dir_all(&tmp_dir) {
        eprintln!("Failed to create temp dir {}: {}", tmp_dir.display(), e);
        return 1;
    }

    println!("Cloning zakuro-ai/zc (source build)...");
    let clone_url = format!("https://x-access-token:{}@{}", token, REPO_CLONE_HOST);
    let clone_status = Command::new("git")
        .args(["clone", "--depth", "1", &clone_url, "."])
        .current_dir(&tmp_dir)
        .status();

    match clone_status {
        Ok(s) if s.success() => {}
        Ok(s) => {
            eprintln!("git clone failed (exit {}).", s);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
        Err(e) => {
            eprintln!("Failed to run git clone: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    }

    println!("Building (cargo build --release)... this can take a few minutes.");
    let (prog, pre_args) = cargo_invocation();
    let build_output = Command::new(&prog)
        .args(pre_args.iter().map(String::as_str))
        .args(["build", "--release"])
        .current_dir(&tmp_dir)
        .output();

    let build_output = match build_output {
        Ok(o) => o,
        Err(e) => {
            eprintln!("Failed to run cargo build: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    if !build_output.status.success() {
        let stderr = String::from_utf8_lossy(&build_output.stderr);
        let tail: String = stderr
            .lines()
            .rev()
            .take(30)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect::<Vec<_>>()
            .join("\n");
        eprintln!("cargo build --release failed. Build output (tail):");
        eprintln!("{}", tail);
        if stderr.contains("lock file version") {
            eprintln!();
            eprintln!(
                "This is a toolchain problem, not a code problem: the cargo that ran is\n\
                 too old to read this repo's Cargo.lock (v4 needs Rust >= 1.78).\n\
                 Install rustup so the pinned `stable` toolchain is used, or run the\n\
                 build yourself with a newer cargo:\n\
                 \n\
                 \trustup run stable cargo build --release"
            );
        }
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return 1;
    }

    let mut built_bin: Option<PathBuf> = None;
    for c in ["zc", "zc2"] {
        let p = tmp_dir.join("target/release").join(c);
        if p.is_file() {
            built_bin = Some(p);
            break;
        }
    }
    let built_bin = match built_bin {
        Some(p) => p,
        None => {
            eprintln!("Build finished but no zc binary found under target/release/.");
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    let bytes = match std::fs::read(&built_bin) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Failed to read built binary: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, &bytes) {
        eprintln!("Failed to install the new binary: {}", e);
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return 1;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    // Best-effort version string from the built binary itself.
    let version = Command::new(&exe_path)
        .arg("--version")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|| "source build".to_string());

    let _ = std::fs::remove_dir_all(&tmp_dir);

    println!("updated to {}", version);
    0
}

/// How to invoke cargo for a source build: `("rustup", ["run","stable","cargo"])`
/// when rustup is available, else plain `("cargo", [])`.
///
/// The repo pins `channel = "stable"` in rust-toolchain.toml, but that pin is
/// only honoured by the rustup *shim*. A distro cargo at /usr/bin/cargo is a
/// real binary that ignores it, and if it predates lockfile v4 the build dies
/// with "lock file version 4 requires `-Znext-lockfile-bump`" before compiling
/// a line -- which is exactly what a user with both installed hits, because
/// /usr/bin usually precedes ~/.cargo/bin on PATH.
///
/// Going through rustup means the toolchain file decides, not PATH order.
fn cargo_invocation() -> (String, Vec<String>) {
    let rustup_ok = Command::new("rustup")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if rustup_ok {
        (
            "rustup".to_string(),
            ["run", "stable", "cargo"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        )
    } else {
        ("cargo".to_string(), Vec::new())
    }
}

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

    #[test]
    fn append_line_once_is_idempotent() {
        let dir = std::env::temp_dir().join(format!("zc-rc-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let rc = dir.join("rc");
        let line = "export PATH=\"$HOME/.local/bin:$PATH\"";
        assert!(super::append_line_once(&rc, line).unwrap()); // added
        assert!(!super::append_line_once(&rc, line).unwrap()); // already present
        let body = std::fs::read_to_string(&rc).unwrap();
        assert_eq!(body.matches(line).count(), 1);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_mode_default_is_prebuilt_release() {
        let args: Vec<String> = vec![];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_other_flags_still_prebuilt_release() {
        let args: Vec<String> = vec!["--verbose".to_string()];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_from_source_flag_selects_source_build() {
        let args: Vec<String> = vec!["--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn parse_mode_from_source_among_other_args() {
        let args: Vec<String> = vec!["--verbose".to_string(), "--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn resolve_token_prefers_gh() {
        let t = resolve_token(
            || Some("gh-token".to_string()),
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_gh_pat() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("pat-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_github_token() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => None,
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-env-token"));
    }

    #[test]
    fn resolve_token_none_found() {
        let t = resolve_token(|| None, |_k| None);
        assert_eq!(t, None);
    }

    #[test]
    fn resolve_token_skips_blank_values() {
        // A blank gh token or blank env var should not shadow a real one
        // further down the precedence chain.
        let t = resolve_token(
            || Some("   ".to_string()),
            |k| match k {
                "GH_PAT" => Some("".to_string()),
                "GITHUB_TOKEN" => Some("real-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("real-token"));
    }

    const API_ASSET: &str = "https://api.github.com/repos/zakuro-ai/zc/releases/assets/2";
    const BROWSER_ASSET: &str =
        "https://github.com/zakuro-ai/zc/releases/download/v0.0.26/zc-darwin-arm64";

    #[test]
    fn asset_selection_prefers_the_api_url_with_octet_stream() {
        let release = serde_json::json!({ "tag_name": "v0.0.26", "assets": [
            {
                "name": "zc-linux-x86_64",
                "url": "https://api.github.com/repos/zakuro-ai/zc/releases/assets/1",
                "browser_download_url": "https://github.com/zakuro-ai/zc/releases/download/v0.0.26/zc-linux-x86_64",
            },
            { "name": "zc-darwin-arm64", "url": API_ASSET, "browser_download_url": BROWSER_ASSET },
        ]});
        assert_eq!(
            select_asset(&release, "zc-darwin-arm64"),
            Some(AssetSource {
                url: API_ASSET.to_string(),
                accept: "application/octet-stream",
            })
        );
        assert_eq!(select_asset(&release, "zc-linux-arm64"), None);
    }

    #[test]
    fn asset_selection_falls_back_to_the_browser_download_url() {
        let release = serde_json::json!({ "assets": [
            { "name": "zc-darwin-arm64", "browser_download_url": BROWSER_ASSET },
        ]});
        assert_eq!(
            select_asset(&release, "zc-darwin-arm64"),
            Some(AssetSource {
                url: BROWSER_ASSET.to_string(),
                accept: "*/*",
            })
        );
    }

    #[test]
    fn a_token_becomes_an_authorization_header_on_github_requests_only() {
        let with = github_headers(OCTET_STREAM, Some("t0ken"));
        assert!(
            with.contains(&("Authorization", "Bearer t0ken".to_string())),
            "{with:?}"
        );
        assert!(
            with.contains(&("Accept", OCTET_STREAM.to_string())),
            "{with:?}"
        );
        assert!(
            with.contains(&("User-Agent", "zc-update".to_string())),
            "{with:?}"
        );
        let without = github_headers(OCTET_STREAM, None);
        assert!(
            without.iter().all(|(k, _)| *k != "Authorization"),
            "{without:?}"
        );
        // The storage host GitHub redirects the download to never gets it.
        assert_eq!(
            download_config().build().redirect_auth_headers(),
            RedirectAuthHeaders::Never
        );
    }

    #[test]
    fn the_download_gets_300_s_and_the_api_call_30_s() {
        assert_eq!(
            download_config().build().timeouts().global,
            Some(Duration::from_secs(300))
        );
        assert_eq!(
            api_config().build().timeouts().global,
            Some(Duration::from_secs(30))
        );
    }

    #[test]
    fn without_a_token_a_404_says_the_releases_are_private() {
        assert_eq!(
            api_status_message(StatusCode::NOT_FOUND, false),
            "zc releases are private. Sign in with `gh auth login` (or set GH_PAT / GITHUB_TOKEN) and run zc update again."
        );
        // Any other status, token or not, is GitHub's answer and the
        // source-build fallback.
        for have_token in [false, true] {
            let m = api_status_message(StatusCode::FORBIDDEN, have_token);
            assert!(
                m.starts_with("GitHub releases API returned HTTP 403 Forbidden\n"),
                "{m}"
            );
            assert!(m.ends_with(FROM_SOURCE_FALLBACK), "{m}");
        }
    }

    /// A token that can't see the private repo gets a 404 too, as does a repo
    /// with no release: say so, and point at where zc got the token.
    #[test]
    fn with_a_token_a_404_says_it_may_lack_access_or_there_is_no_release() {
        let m = api_status_message(StatusCode::NOT_FOUND, true);
        for part in [
            "HTTP 404 Not Found",
            "may not have access to zakuro-ai/zc (the repo is private)",
            "or there is no release yet",
            "`gh auth status`",
            "GH_PAT",
            "GITHUB_TOKEN",
        ] {
            assert!(m.contains(part), "missing {part:?} in: {m}");
        }
        assert!(m.ends_with(FROM_SOURCE_FALLBACK), "{m}");
    }

    #[test]
    fn the_token_goes_to_api_github_com_only() {
        let sends_token = |url: &str| {
            github_headers(OCTET_STREAM, token_for(url, Some("t0ken")))
                .iter()
                .any(|(k, v)| *k == "Authorization" && v == "Bearer t0ken")
        };
        for url in [
            REPO_API_LATEST,
            API_ASSET,
            "https://API.GitHub.com/repos/zakuro-ai/zc/releases/latest",
        ] {
            assert!(sends_token(url), "{url} gets the token");
        }
        for url in [
            BROWSER_ASSET, // the browser_download_url fallback, on github.com
            "https://objects.githubusercontent.com/github-production-release-asset/1?sig=x",
            "https://api.github.com.evil.example/repos/zakuro-ai/zc", // host only starts with it
            "https://evil.example/api.github.com/repos/zakuro-ai/zc", // only in the path
            "https://api.github.com@evil.example/repos/zakuro-ai/zc", // userinfo; host is evil
            "http://api.github.com/repos/zakuro-ai/zc",               // not https
            "not a url",
        ] {
            assert!(!sends_token(url), "{url} must not get the token");
        }
        assert_eq!(token_for(REPO_API_LATEST, None), None);
    }

    /// A one-shot HTTP server on 127.0.0.1: answers the first request with
    /// `response` and hands back that request's head (request line and
    /// headers).
    fn one_shot_server(response: Vec<u8>) -> (String, std::thread::JoinHandle<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let handle = std::thread::spawn(move || {
            let (mut s, _) = listener.accept().unwrap();
            let mut head = Vec::new();
            let mut b = [0u8; 1024];
            while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut b) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => head.extend_from_slice(&b[..n]),
                }
            }
            s.write_all(&response).unwrap();
            String::from_utf8_lossy(&head).into_owned()
        });
        (base, handle)
    }

    /// GitHub's asset API answers with a 302 to a signed storage URL, and the
    /// storage host rejects a request that also carries the token.
    #[test]
    fn the_download_follows_the_redirect_without_the_token() {
        let blob = b"\x7fELF not really a zc binary".to_vec();
        let mut ok = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            blob.len()
        )
        .into_bytes();
        ok.extend_from_slice(&blob);
        let (storage, storage_req) = one_shot_server(ok);
        let (api, api_req) = one_shot_server(
            format!(
                "HTTP/1.1 302 Found\r\nLocation: {storage}/signed?sig=abc\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
            )
            .into_bytes(),
        );

        // No proxy from the environment: the fake servers are on loopback.
        let agent = ureq::Agent::new_with_config(download_config().proxy(None).build());
        let src = AssetSource {
            url: format!("{api}/repos/zakuro-ai/zc/releases/assets/2"),
            accept: OCTET_STREAM,
        };
        let bytes = download(&agent, &src, Some("t0ken")).expect("download succeeds");
        assert_eq!(bytes, blob);

        let api_req = api_req.join().unwrap().to_ascii_lowercase();
        assert!(
            api_req.contains("\r\nauthorization: bearer t0ken\r\n"),
            "{api_req}"
        );
        assert!(
            api_req.contains("\r\naccept: application/octet-stream\r\n"),
            "{api_req}"
        );
        let storage_req = storage_req.join().unwrap().to_ascii_lowercase();
        assert!(
            storage_req.starts_with("get /signed?sig=abc http/1.1\r\n"),
            "{storage_req}"
        );
        assert!(!storage_req.contains("authorization"), "{storage_req}");
    }
}

#[cfg(test)]
mod cargo_invocation_tests {
    /// The shape matters: `rustup run stable cargo build --release`, so the
    /// repo's rust-toolchain.toml decides the toolchain instead of PATH order.
    /// Without this, a distro cargo at /usr/bin (which precedes ~/.cargo/bin on
    /// a default PATH) silently wins and dies on the v4 lock file.
    #[test]
    fn rustup_invocation_puts_cargo_after_run_stable() {
        let (prog, pre) = super::cargo_invocation();
        if prog == "rustup" {
            assert_eq!(pre, vec!["run", "stable", "cargo"]);
        } else {
            assert_eq!(prog, "cargo");
            assert!(pre.is_empty(), "plain cargo takes no leading args");
        }
    }
}