pinready 0.27.6

Cross-platform configurator and launcher supporting the adoption of Visual Pinball 10.8.1 — for testers and early adopters, not a replacement for a stable production setup
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
// Visual Pinball release checker, downloader, and installer.
// Queries a GitHub fork for releases and downloads the correct artifact
// for the current platform.

use anyhow::{Context, Result, bail};
use crossbeam_channel::Sender;
use regex::Regex;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Default GitHub repository for Visual Pinball releases.
pub const DEFAULT_FORK_REPO: &str = "Le-Syl21/vpinball";

/// Information about a GitHub release.
#[derive(Debug, Clone)]
pub struct ReleaseInfo {
    pub tag: String,
    pub asset_name: String,
    pub asset_url: String,
    pub asset_size: u64,
}

/// Parse VPX `--version` output into a version string mirroring the release artifact tag format.
///
/// Input:  `Starting VPX - v10.8.1 Beta (Rev. 4955 (da4e2db), macos BGFX 64bits)`
/// Output: `v10.8.1-4955-da4e2db`
///
/// Falls back to just the version number if the revision or SHA cannot be found.
#[cfg(any(test, not(target_os = "windows")))]
fn parse_vpx_version_output(s: &str) -> Option<String> {
    static VPX_VERSION_RE: OnceLock<Regex> = OnceLock::new();
    let re = VPX_VERSION_RE.get_or_init(|| {
        Regex::new(r"(?x)\b(?P<ver>v\d+\.\d+\.\d+)\b(?:.*?\bRev\.\s*(?P<rev>\d+)\s*\((?P<sha>[0-9A-Fa-f]{7})\))?")
        .expect("valid VPX version regex")
    });

    let caps = re.captures(s)?;
    let base = caps.name("ver")?.as_str();

    match (caps.name("rev"), caps.name("sha")) {
        (Some(rev), Some(sha)) => Some(format!("{}-{}-{}", base, rev.as_str(), sha.as_str())),
        _ => Some(base.to_string()),
    }
}

#[cfg(any(test, target_os = "windows"))]
fn parse_vpx_product_version(s: &str) -> Option<String> {
    let cleaned = s.trim_matches('\0').trim();
    if cleaned.is_empty() {
        return None;
    }

    static PRODUCT_VERSION_RE: OnceLock<Regex> = OnceLock::new();
    let re = PRODUCT_VERSION_RE.get_or_init(|| {
        Regex::new(r"^(?P<base>\d+\.\d+\.\d+)\.(?P<rev>\d+)\.(?P<sha>[0-9a-fA-F]+)$")
            .expect("valid product version regex")
    });

    let caps = re.captures(cleaned)?;
    let base = caps.name("base")?.as_str();
    let rev = caps.name("rev")?.as_str();
    let sha = caps.name("sha")?.as_str().to_ascii_lowercase();
    Some(format!("v{base}-{rev}-{sha}"))
}

#[cfg(target_os = "windows")]
fn query_windows_file_version(exe_path: &Path) -> Option<String> {
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;
    use std::ptr;
    use winapi::shared::minwindef::{DWORD, LPVOID, UINT};
    use winapi::um::winver::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW};

    fn query_string_value(buffer: &[u8], sub_block: &str) -> Option<String> {
        let mut value_ptr: LPVOID = ptr::null_mut();
        let mut value_len: UINT = 0;
        let sub_block_wide: Vec<u16> = sub_block.encode_utf16().chain(Some(0)).collect();

        let queried = unsafe {
            VerQueryValueW(
                buffer.as_ptr() as *const _,
                sub_block_wide.as_ptr(),
                &mut value_ptr,
                &mut value_len,
            )
        };
        if queried == 0 || value_ptr.is_null() || value_len == 0 {
            return None;
        }

        let raw =
            unsafe { std::slice::from_raw_parts(value_ptr as *const u16, value_len as usize) };
        let text = String::from_utf16_lossy(raw);
        Some(text.trim_matches('\0').trim().to_string())
    }

    let wide_path: Vec<u16> = OsStr::new(exe_path).encode_wide().chain(Some(0)).collect();

    let mut handle: DWORD = 0;
    let info_size = unsafe { GetFileVersionInfoSizeW(wide_path.as_ptr(), &mut handle) };
    if info_size == 0 {
        return None;
    }

    let mut buffer = vec![0u8; info_size as usize];
    let got_info = unsafe {
        GetFileVersionInfoW(
            wide_path.as_ptr(),
            0,
            info_size,
            buffer.as_mut_ptr() as LPVOID,
        )
    };
    if got_info == 0 {
        return None;
    }

    // Keep lookup deterministic and simple: use the English string table.
    query_string_value(&buffer, "\\StringFileInfo\\040904B0\\ProductVersion")
        .and_then(|product| parse_vpx_product_version(&product))
}

/// Progress updates sent during download/install.
pub enum UpdateProgress {
    Downloading(u64, u64), // (bytes_downloaded, total_bytes)
    Extracting,
    Done(PathBuf), // path to the installed executable
    Error(String),
}

// ---------------------------------------------------------------------------
// Platform detection
// ---------------------------------------------------------------------------

/// File extension of the artifact for the current platform.
fn artifact_extension() -> &'static str {
    if cfg!(target_os = "windows") {
        "zip"
    } else if cfg!(target_os = "macos") {
        "dmg"
    } else {
        "tar.gz"
    }
}

/// Returns (platform, arch) strings matching the workflow artifact names.
fn platform_arch() -> (&'static str, &'static str) {
    let platform = if cfg!(target_os = "linux") {
        "linux"
    } else if cfg!(target_os = "windows") {
        "windows"
    } else if cfg!(target_os = "macos") {
        "macos"
    } else {
        "unknown"
    };

    let arch = if cfg!(target_arch = "x86_64") {
        "x64"
    } else if cfg!(target_arch = "x86") {
        "x86"
    } else if cfg!(target_arch = "aarch64") {
        detect_arm_board()
    } else {
        "unknown"
    };

    (platform, arch)
}

/// On aarch64 Linux, distinguish between RPi and RK3588 SBCs by reading
/// the device-tree model string. Falls back to "aarch64" on other OSes.
#[cfg(target_arch = "aarch64")]
fn detect_arm_board() -> &'static str {
    // Only relevant on Linux SBCs
    if cfg!(target_os = "linux") {
        if let Ok(model) = std::fs::read_to_string("/proc/device-tree/model") {
            let lower = model.to_lowercase();
            if lower.contains("raspberry") {
                return "rpi-linux-aarch64";
            }
            if lower.contains("rk3588") || lower.contains("rock") || lower.contains("orange pi 5") {
                return "rk3588-linux-aarch64";
            }
        }
        // Generic ARM Linux — try RPi as default
        "rpi-linux-aarch64"
    } else if cfg!(target_os = "macos") {
        // The VPX fork ships macOS ARM builds as `macos-arm64-Release.dmg`,
        // not `macos-aarch64`. Keep the matching name here even though the
        // PinReady CI itself standardized to `aarch64` for Homebrew.
        "arm64"
    } else {
        "aarch64"
    }
}

#[cfg(not(target_arch = "aarch64"))]
fn detect_arm_board() -> &'static str {
    "unknown"
}

// ---------------------------------------------------------------------------
// For aarch64, the artifact name needs special handling because the board
// name is embedded differently. Override artifact_name for SBC builds.
// ---------------------------------------------------------------------------

// On aarch64 Linux, the artifact name includes the board type:
// `VPinballX_BGFX-{tag}-rpi-linux-aarch64-Release.zip`
// On other platforms, the standard format is used.
// This function handles both cases correctly because `platform_arch()`
// already returns the full board-platform-arch triple for SBCs.

// ---------------------------------------------------------------------------
// GitHub API
// ---------------------------------------------------------------------------

/// Check the latest release on a GitHub repository.
/// This is a blocking call — run it from a background thread.
pub fn check_latest_release(repo: &str) -> Result<ReleaseInfo> {
    // Use /releases (not /releases/latest) because the latest release may be
    // marked as a pre-release, which /releases/latest silently skips.
    let url = format!("https://api.github.com/repos/{repo}/releases?per_page=1");

    let response = ureq::get(&url)
        .header("User-Agent", "PinReady")
        .header("Accept", "application/vnd.github.v3+json")
        .call()
        .context("Failed to query GitHub releases")?;

    let body = response.into_body().read_to_string()?;
    let releases: serde_json::Value =
        serde_json::from_str(&body).context("Failed to parse GitHub release JSON")?;

    let json = releases
        .as_array()
        .and_then(|arr| arr.first())
        .context("No releases found")?;

    let tag = json["tag_name"]
        .as_str()
        .context("Missing tag_name in release")?
        .to_string();

    // Find the matching asset for this platform by pattern
    // Assets may have different version numbers than the release tag,
    // so we match on the platform/arch/extension suffix.
    let (platform, arch) = platform_arch();
    let ext = artifact_extension();
    let suffix = format!("-{platform}-{arch}-Release.{ext}");
    let prefix = "VPinballX_BGFX-";

    let assets = json["assets"]
        .as_array()
        .context("Missing assets in release")?;

    for asset in assets {
        let name = asset["name"].as_str().unwrap_or_default();
        if name.starts_with(prefix) && name.ends_with(&suffix) {
            let url = asset["browser_download_url"]
                .as_str()
                .context("Missing download URL")?
                .to_string();
            let size = asset["size"].as_u64().unwrap_or(0);

            return Ok(ReleaseInfo {
                tag,
                asset_name: name.to_string(),
                asset_url: url,
                asset_size: size,
            });
        }
    }

    bail!(
        "No matching asset for this platform (expected: {prefix}*{suffix}). \
         Available: {}",
        assets
            .iter()
            .filter_map(|a| a["name"].as_str())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

// ---------------------------------------------------------------------------
// Download & install
// ---------------------------------------------------------------------------

/// Default installation directory for Visual Pinball.
pub fn default_install_dir() -> PathBuf {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join("Visual_Pinball")
}

/// Resolve the real executable path from a user-provided path.
/// On macOS, if the path points to a `.app` bundle, look inside
/// `Contents/MacOS/` for the actual binary.
pub fn resolve_vpx_exe(path: &Path) -> PathBuf {
    let p = PathBuf::from(path);
    if cfg!(target_os = "macos")
        && let Some(ext) = p.extension()
        && ext == "app"
        && p.is_dir()
    {
        let macos_dir = p.join("Contents/MacOS");
        if let Ok(entries) = std::fs::read_dir(&macos_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();
                if name_str.starts_with("VPinballX") {
                    return entry.path();
                }
            }
        }
    }
    p
}

/// Name of the main Visual Pinball executable for the current platform.
pub fn vpx_executable_name() -> &'static str {
    if cfg!(target_os = "windows") {
        if cfg!(target_arch = "x86_64") {
            "VPinballX_BGFX64.exe"
        } else {
            "VPinballX_BGFX.exe"
        }
    } else {
        "VPinballX_BGFX"
    }
}

/// Why an install into a user-chosen folder failed, when the OS says so.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallFailure {
    /// Windows error 5 / EACCES: no write access to the folder.
    Denied,
    /// Windows error 3 / ENOENT: the path can't be reached.
    NotFound,
}

/// Look through an install error for the I/O error behind it.
pub fn classify_install_error(err: &anyhow::Error) -> Option<InstallFailure> {
    err.chain()
        .filter_map(|e| e.downcast_ref::<std::io::Error>())
        .find_map(|io| match io.kind() {
            std::io::ErrorKind::PermissionDenied => Some(InstallFailure::Denied),
            std::io::ErrorKind::NotFound => Some(InstallFailure::NotFound),
            _ => None,
        })
}

/// Download a release asset and extract it into `install_dir`.
/// Sends progress updates through `progress_tx`.
/// This is a blocking call — run it from a background thread.
pub fn download_and_install(
    release: &ReleaseInfo,
    install_dir: &Path,
    progress_tx: Sender<UpdateProgress>,
) -> Result<()> {
    // Download to the system temp folder: a normal user can create a folder
    // in the root of C:\ (C:\VPinball) but not a file there, so a zip next
    // to the install folder was refused with "Access denied" (OS error 5).
    let tmp_path =
        std::env::temp_dir().join(format!(".pinready_vpx_download_{}.zip", std::process::id()));

    let result = download_and_install_inner(release, install_dir, &tmp_path, &progress_tx);

    // Clean up temp file
    let _ = std::fs::remove_file(&tmp_path);

    result
}

fn download_and_install_inner(
    release: &ReleaseInfo,
    install_dir: &Path,
    tmp_path: &Path,
    progress_tx: &Sender<UpdateProgress>,
) -> Result<()> {
    // Download
    let response = ureq::get(&release.asset_url)
        .header("User-Agent", "PinReady")
        .header("Accept", "application/octet-stream")
        .call()
        .context("Failed to download release asset")?;

    let total = release.asset_size;
    let mut downloaded: u64 = 0;
    let mut file = std::fs::File::create(tmp_path)?;
    let mut buf = [0u8; 32768];

    let mut reader = response.into_body().into_reader();
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        std::io::Write::write_all(&mut file, &buf[..n])?;
        downloaded += n as u64;
        let _ = progress_tx.send(UpdateProgress::Downloading(downloaded, total));
    }
    drop(file);

    // Extract
    let _ = progress_tx.send(UpdateProgress::Extracting);

    std::fs::create_dir_all(install_dir)?;

    let ext = artifact_extension();
    if ext == "tar.gz" {
        extract_tar_gz(tmp_path, install_dir)?;
    } else if ext == "zip" {
        extract_zip(tmp_path, install_dir)?;
    } else {
        // dmg — just copy the file, user will mount manually
        let dest = install_dir.join(tmp_path.file_name().unwrap_or_default());
        std::fs::copy(tmp_path, &dest)?;
    }

    // Make sure the main executable is executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let exe_path = install_dir.join(vpx_executable_name());
        if exe_path.exists() {
            std::fs::set_permissions(&exe_path, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    let exe_path = install_dir.join(vpx_executable_name());
    let _ = progress_tx.send(UpdateProgress::Done(exe_path));

    Ok(())
}

pub(crate) fn extract_tar_gz(archive_path: &Path, dest: &Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let gz = flate2::read::GzDecoder::new(file);
    let mut archive = tar::Archive::new(gz);
    archive.set_preserve_permissions(true);
    archive.unpack(dest).context("Failed to extract tar.gz")?;
    Ok(())
}

pub(crate) fn extract_zip(archive_path: &Path, dest: &Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let mut archive = zip::ZipArchive::new(file).context("Failed to open zip archive")?;

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let name = entry.name()?.into_owned();
        let out_path = dest.join(&name);

        if entry.is_dir() {
            std::fs::create_dir_all(&out_path)?;
        } else {
            if let Some(parent) = out_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            let mut out_file = std::fs::File::create(&out_path)?;
            std::io::copy(&mut entry, &mut out_file)?;

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Some(mode) = entry.unix_mode() {
                    std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))?;
                }
            }
        }
    }
    Ok(())
}

/// Query the version from a manually installed VPX executable.
///
/// On Windows, reads ProductVersion from the executable version resource
/// (without launching the GUI executable).
/// On other platforms, runs `--version` and parses output like:
/// `Starting VPX - v10.8.1 Beta (Rev. 4955 (da4e2db), macos BGFX 64bits)`.
pub fn query_vpx_version(exe_path: &str) -> Option<String> {
    let exe_path = resolve_vpx_exe(Path::new(exe_path));

    #[cfg(target_os = "windows")]
    {
        query_windows_file_version(&exe_path)
    }

    #[cfg(not(target_os = "windows"))]
    {
        use std::process::Command;

        let output = Command::new(&exe_path).arg("--version").output().ok()?;
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let combined = format!("{}{}", stdout, stderr);
        parse_vpx_version_output(&combined)
    }
}

// ---------------------------------------------------------------------------
// PinReady self-update
// ---------------------------------------------------------------------------

/// GitHub repository where PinReady releases live.
pub const PINREADY_REPO: &str = "Le-Syl21/PinReady";

/// Compile-time PinReady version (matches Cargo.toml, no `v` prefix).
pub const CURRENT_PINREADY_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Expected release asset name for this platform.
///
/// Mirrors CI's artifact naming:
///   pinready-linux-x86_64.tar.gz
///   pinready-linux-aarch64.tar.gz
///   pinready-macos-aarch64.tar.gz
///   pinready-macos-x86_64.tar.gz
///   pinready-windows-x86_64.zip
fn pinready_asset_name() -> String {
    let os = if cfg!(target_os = "linux") {
        "linux"
    } else if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(target_os = "windows") {
        "windows"
    } else {
        "unknown"
    };
    let arch = if cfg!(target_arch = "x86_64") {
        "x86_64"
    } else if cfg!(target_arch = "aarch64") {
        "aarch64"
    } else {
        "unknown"
    };
    let ext = if cfg!(target_os = "windows") {
        "zip"
    } else {
        "tar.gz"
    };
    format!("pinready-{os}-{arch}.{ext}")
}

/// Internal binary name inside the release archive.
fn pinready_binary_name() -> &'static str {
    if cfg!(target_os = "windows") {
        "pinready.exe"
    } else {
        "pinready"
    }
}

/// Query the PinReady repository for the latest release + matching asset.
pub fn check_pinready_release() -> Result<ReleaseInfo> {
    let url = format!("https://api.github.com/repos/{PINREADY_REPO}/releases?per_page=1");

    let response = ureq::get(&url)
        .header("User-Agent", "PinReady")
        .header("Accept", "application/vnd.github.v3+json")
        .call()
        .context("Failed to query GitHub releases")?;

    let body = response.into_body().read_to_string()?;
    let releases: serde_json::Value =
        serde_json::from_str(&body).context("Failed to parse GitHub release JSON")?;

    let json = releases
        .as_array()
        .and_then(|arr| arr.first())
        .context("No PinReady releases found")?;

    let tag = json["tag_name"]
        .as_str()
        .context("Missing tag_name in release")?
        .to_string();

    let target = pinready_asset_name();
    let assets = json["assets"]
        .as_array()
        .context("Missing assets in release")?;

    for asset in assets {
        let name = asset["name"].as_str().unwrap_or_default();
        if name == target {
            let url = asset["browser_download_url"]
                .as_str()
                .context("Missing download URL")?
                .to_string();
            let size = asset["size"].as_u64().unwrap_or(0);
            return Ok(ReleaseInfo {
                tag,
                asset_name: name.to_string(),
                asset_url: url,
                asset_size: size,
            });
        }
    }

    bail!(
        "No PinReady asset named {target}. Available: {}",
        assets
            .iter()
            .filter_map(|a| a["name"].as_str())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

/// Returns true if the remote release tag differs from the running version.
/// Tag format on releases is `v0.6.2`; `CURRENT_PINREADY_VERSION` has no `v` prefix.
pub fn is_pinready_update_available(release: &ReleaseInfo) -> bool {
    release.tag.trim_start_matches('v') != CURRENT_PINREADY_VERSION
}

/// Download the PinReady release, extract the binary, swap the running
/// executable via `self_replace`, and spawn a fresh instance. The caller
/// must `std::process::exit(0)` immediately after this returns Ok(()).
pub fn download_pinready_and_replace(
    release: &ReleaseInfo,
    progress_tx: Sender<UpdateProgress>,
) -> Result<()> {
    let tmp_dir = std::env::temp_dir();
    let archive_path = tmp_dir.join(&release.asset_name);
    let new_binary_path = tmp_dir.join(format!("pinready_new_{}", std::process::id()));

    // Download
    let response = ureq::get(&release.asset_url)
        .header("User-Agent", "PinReady")
        .header("Accept", "application/octet-stream")
        .call()
        .context("Failed to download PinReady release")?;

    let total = release.asset_size;
    let mut downloaded: u64 = 0;
    let mut file = std::fs::File::create(&archive_path)?;
    let mut buf = [0u8; 32768];
    let mut reader = response.into_body().into_reader();
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        std::io::Write::write_all(&mut file, &buf[..n])?;
        downloaded += n as u64;
        let _ = progress_tx.send(UpdateProgress::Downloading(downloaded, total));
    }
    drop(file);

    log::info!(
        "PinReady update: downloaded {} bytes to {}",
        downloaded,
        archive_path.display()
    );
    let _ = progress_tx.send(UpdateProgress::Extracting);

    // Extract binary to a known temp path
    extract_pinready_binary(&archive_path, &new_binary_path, pinready_binary_name())?;
    log::info!(
        "PinReady update: extracted binary to {}",
        new_binary_path.display()
    );

    // Make executable on unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&new_binary_path, std::fs::Permissions::from_mode(0o755))?;
    }

    // Capture the running binary path BEFORE self_replace. On Linux,
    // self_replace unlink()s the original inode and creates a new file at
    // the same path; once that's done, /proc/self/exe still resolves but
    // its readlink suffix becomes " (deleted)" — and std::env::current_exe()
    // returns that literal string with the suffix included, which is not a
    // valid filesystem path. Spawning it fails with ENOENT and the update
    // silently aborts. Reading current_exe() before the swap dodges that.
    let exe = std::env::current_exe().context("Failed to resolve current exe")?;

    // Swap the running binary. self_replace handles the Windows rename-trick
    // and atomic rename on unix.
    self_replace::self_replace(&new_binary_path)
        .context("Failed to swap the running PinReady binary")?;
    log::info!(
        "PinReady update: self_replace done, relaunching from {}",
        exe.display()
    );

    // Spawn a fresh instance using the *new* binary (now at current_exe()).
    // The caller is expected to exit(0) so this new process becomes the
    // user-facing one. We pass `--from-update` so the new process knows
    // to retry the PID-lock acquisition for ~5 s — without that, the new
    // process races against this one's flock release, sees AlreadyRunning,
    // sends a focus request to us (we're about to exit), and quits
    // silently. End result: no PinReady running after update.
    let child = std::process::Command::new(&exe)
        .arg("--from-update")
        .spawn()
        .context("Failed to relaunch PinReady")?;
    log::info!(
        "PinReady update: spawned child PID {} via {} --from-update",
        child.id(),
        exe.display()
    );

    // Cleanup temp files (best effort — don't fail the update if cleanup fails)
    let _ = std::fs::remove_file(&archive_path);
    let _ = std::fs::remove_file(&new_binary_path);

    let _ = progress_tx.send(UpdateProgress::Done(std::path::PathBuf::new()));
    Ok(())
}

fn extract_pinready_binary(archive: &Path, dest: &Path, binary_name: &str) -> Result<()> {
    let ext = archive.extension().and_then(|s| s.to_str()).unwrap_or("");
    if ext == "zip" {
        let file = std::fs::File::open(archive)?;
        let mut zip = zip::ZipArchive::new(file)?;
        for i in 0..zip.len() {
            let mut entry = zip.by_index(i)?;
            // Match by the trailing component so we tolerate archives with a
            // top-level directory.
            let name = entry.name()?.into_owned();
            if name == binary_name || name.ends_with(&format!("/{binary_name}")) {
                let mut out = std::fs::File::create(dest)?;
                std::io::copy(&mut entry, &mut out)?;
                return Ok(());
            }
        }
    } else {
        // Assume tar.gz
        let file = std::fs::File::open(archive)?;
        let gz = flate2::read::GzDecoder::new(file);
        let mut tar = tar::Archive::new(gz);
        for entry in tar.entries()? {
            let mut entry = entry?;
            let path = entry.path()?.to_path_buf();
            let matches = path
                .file_name()
                .and_then(|s| s.to_str())
                .is_some_and(|n| n == binary_name);
            if matches {
                let mut out = std::fs::File::create(dest)?;
                std::io::copy(&mut entry, &mut out)?;
                return Ok(());
            }
        }
    }
    bail!("Binary {binary_name} not found in {}", archive.display())
}

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

    #[test]
    fn full_vpx_output_produces_artifact_tag_format() {
        assert_eq!(
            parse_vpx_version_output(
                "Starting VPX - v10.8.1 Beta (Rev. 4955 (da4e2db), macos BGFX 64bits)"
            ),
            Some("v10.8.1-4955-da4e2db".to_string())
        );
    }

    #[test]
    fn version_only_fallback_when_no_rev_sha() {
        assert_eq!(
            parse_vpx_version_output("v10.8.1"),
            Some("v10.8.1".to_string())
        );
    }

    #[test]
    fn returns_none_for_unparseable_output() {
        assert_eq!(parse_vpx_version_output("invalid"), None);
        assert_eq!(parse_vpx_version_output("4955"), None);
    }

    #[test]
    fn product_version_dot_format_is_normalized() {
        assert_eq!(
            parse_vpx_product_version("10.8.1.4957.db2a00"),
            Some("v10.8.1-4957-db2a00".to_string())
        );
        assert_eq!(
            parse_vpx_product_version("Visual Pinball BGFX 10.8.1"),
            None
        );
    }
}

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

    #[test]
    fn default_fork_repo_is_set() {
        assert!(!DEFAULT_FORK_REPO.is_empty());
        assert!(DEFAULT_FORK_REPO.contains('/'));
    }

    #[test]
    fn artifact_extension_linux() {
        // On Linux where tests run
        let ext = artifact_extension();
        assert!(
            ext == "tar.gz" || ext == "zip" || ext == "dmg",
            "unexpected extension: {ext}"
        );
    }

    #[test]
    fn platform_arch_returns_known_values() {
        let (platform, arch) = platform_arch();
        assert!(
            ["linux", "windows", "macos", "unknown"].contains(&platform),
            "unexpected platform: {platform}"
        );
        assert!(!arch.is_empty(), "arch should not be empty");
    }

    #[test]
    fn vpx_executable_name_not_empty() {
        let name = vpx_executable_name();
        assert!(!name.is_empty());
        assert!(
            name.starts_with("VPinballX"),
            "expected VPinballX prefix: {name}"
        );
    }

    #[test]
    fn install_errors_are_classified() {
        use std::io::{Error, ErrorKind};
        let denied = anyhow::Error::new(Error::from(ErrorKind::PermissionDenied));
        assert_eq!(
            classify_install_error(&denied),
            Some(InstallFailure::Denied)
        );
        let missing = anyhow::Error::new(Error::from(ErrorKind::NotFound)).context("extract");
        assert_eq!(
            classify_install_error(&missing),
            Some(InstallFailure::NotFound)
        );
        let other = anyhow::anyhow!("network down");
        assert_eq!(classify_install_error(&other), None);
    }

    #[test]
    fn default_install_dir_contains_visual_pinball() {
        let dir = default_install_dir();
        let s = dir.to_string_lossy();
        assert!(
            s.contains("Visual_Pinball"),
            "expected Visual_Pinball in: {s}"
        );
    }

    #[test]
    fn resolve_vpx_exe_returns_same_on_linux() {
        // On Linux, resolve_vpx_exe should return the path unchanged
        let path = Path::new("/usr/local/bin/VPinballX_BGFX");
        let resolved = resolve_vpx_exe(path);
        assert_eq!(resolved, path.to_path_buf());
    }

    #[test]
    fn resolve_vpx_exe_nonexistent_path() {
        let path = Path::new("/nonexistent/path/VPinballX_BGFX");
        let resolved = resolve_vpx_exe(path);
        assert_eq!(resolved, path.to_path_buf());
    }

    #[test]
    fn extract_tar_gz_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("test.tar.gz");
        let dest = dir.path().join("extracted");

        // Create a tar.gz with a test file
        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default());
            let mut tar = tar::Builder::new(gz);

            let content = b"hello pinball";
            let mut header = tar::Header::new_gnu();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            tar.append_data(&mut header, "test.txt", &content[..])
                .unwrap();
            tar.finish().unwrap();
        }

        extract_tar_gz(&archive_path, &dest).unwrap();
        let extracted = std::fs::read_to_string(dest.join("test.txt")).unwrap();
        assert_eq!(extracted, "hello pinball");
    }

    #[test]
    fn extract_zip_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("test.zip");
        let dest = dir.path().join("extracted");

        // Create a zip with a test file
        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let mut zip = zip::ZipWriter::new(file);
            let options = zip::write::SimpleFileOptions::default();
            zip.start_file("test.txt", options).unwrap();
            zip.write_all(b"hello vpx").unwrap();
            zip.finish().unwrap();
        }

        extract_zip(&archive_path, &dest).unwrap();
        let extracted = std::fs::read_to_string(dest.join("test.txt")).unwrap();
        assert_eq!(extracted, "hello vpx");
    }
}