flintbase 0.3.1

Google / Firebase API key analyzer and APK secret scanner — tests keys against 20+ endpoints and extracts hardcoded credentials from Android apps
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use colored::Colorize;
use comfy_table::{modifiers::UTF8_ROUND_CORNERS, presets::UTF8_FULL, Cell, Color, Table};

// ═════════════════════════════════════════════════════════════════════════════
// Platform Discovery
// ═════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct Platform {
    pub os: Os,
    pub arch: Arch,
    pub distro: Option<Distro>,
    pub pkg_managers: Vec<PkgManager>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Os {
    Linux,
    MacOs,
    Windows,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Arch {
    X86_64,
    Aarch64,
    Unknown,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Distro {
    pub id: String,        // e.g. "ubuntu", "fedora", "arch"
    pub id_like: String,   // e.g. "debian", "rhel fedora"
    pub name: String,      // e.g. "Ubuntu 24.04"
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PkgManager {
    Apt,
    Dnf,
    Pacman,
    Zypper,
    Brew,
    Cargo,
    Port,   // macOS MacPorts
}

impl std::fmt::Display for PkgManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PkgManager::Apt => write!(f, "apt"),
            PkgManager::Dnf => write!(f, "dnf"),
            PkgManager::Pacman => write!(f, "pacman"),
            PkgManager::Zypper => write!(f, "zypper"),
            PkgManager::Brew => write!(f, "brew"),
            PkgManager::Cargo => write!(f, "cargo"),
            PkgManager::Port => write!(f, "port"),
        }
    }
}

impl std::fmt::Display for Os {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Os::Linux => write!(f, "Linux"),
            Os::MacOs => write!(f, "macOS"),
            Os::Windows => write!(f, "Windows"),
            Os::Unknown => write!(f, "Unknown"),
        }
    }
}

impl std::fmt::Display for Arch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Arch::X86_64 => write!(f, "x86_64"),
            Arch::Aarch64 => write!(f, "aarch64"),
            Arch::Unknown => write!(f, "unknown"),
        }
    }
}

/// Detect the current platform: OS, architecture, distro, and available package managers.
pub fn detect_platform() -> Platform {
    let os = detect_os();
    let arch = detect_arch();
    let distro = if os == Os::Linux {
        detect_linux_distro()
    } else {
        None
    };
    let pkg_managers = detect_pkg_managers();

    Platform {
        os,
        arch,
        distro,
        pkg_managers,
    }
}

fn detect_os() -> Os {
    match env::consts::OS {
        "linux" => Os::Linux,
        "macos" => Os::MacOs,
        "windows" => Os::Windows,
        _ => Os::Unknown,
    }
}

fn detect_arch() -> Arch {
    match env::consts::ARCH {
        "x86_64" => Arch::X86_64,
        "aarch64" => Arch::Aarch64,
        _ => Arch::Unknown,
    }
}

fn detect_linux_distro() -> Option<Distro> {
    let contents = fs::read_to_string("/etc/os-release").ok()?;
    let mut id = String::new();
    let mut id_like = String::new();
    let mut pretty_name = String::new();

    for line in contents.lines() {
        if let Some(val) = line.strip_prefix("ID=") {
            id = val.trim_matches('"').to_lowercase();
        } else if let Some(val) = line.strip_prefix("ID_LIKE=") {
            id_like = val.trim_matches('"').to_lowercase();
        } else if let Some(val) = line.strip_prefix("PRETTY_NAME=") {
            pretty_name = val.trim_matches('"').to_string();
        }
    }

    if id.is_empty() && pretty_name.is_empty() {
        return None;
    }

    Some(Distro {
        id,
        id_like,
        name: pretty_name,
    })
}

/// Detect whether the Linux system uses musl or glibc.
/// Returns "musl" or "gnu". Falls back to "gnu" if detection fails.
fn detect_linux_libc() -> &'static str {
    // Method 1: check if `ldd --version` output mentions musl
    if let Ok(output) = Command::new("ldd").arg("--version").output() {
        let stdout = String::from_utf8_lossy(&output.stdout).to_lowercase();
        let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
        if stdout.contains("musl") || stderr.contains("musl") {
            return "musl";
        }
    }

    // Method 2: check for the existence of musl-libc shared lib
    if Path::new("/lib/ld-musl-x86_64.so.1").exists()
        || Path::new("/lib/ld-musl-aarch64.so.1").exists()
    {
        return "musl";
    }

    // Method 3: check if /etc/os-release ID is "alpine" (always musl)
    if let Ok(contents) = fs::read_to_string("/etc/os-release") {
        for line in contents.lines() {
            if let Some(val) = line.strip_prefix("ID=") {
                if val.trim_matches('"').to_lowercase() == "alpine" {
                    return "musl";
                }
            }
        }
    }

    "gnu"
}

fn detect_pkg_managers() -> Vec<PkgManager> {
    let checks: &[(&str, PkgManager)] = &[
        ("apt", PkgManager::Apt),
        ("dnf", PkgManager::Dnf),
        ("pacman", PkgManager::Pacman),
        ("zypper", PkgManager::Zypper),
        ("brew", PkgManager::Brew),
        ("cargo", PkgManager::Cargo),
        ("port", PkgManager::Port),
    ];

    checks
        .iter()
        .filter(|(bin, _)| which_exists(bin))
        .map(|(_, pm)| *pm)
        .collect()
}

/// Print detected platform info.
pub fn print_platform_info(platform: &Platform) {
    println!("\n{}", "Platform Detection".bright_cyan().bold());
    println!("  OS:           {}", platform.os.to_string().bold());
    println!("  Architecture: {}", platform.arch.to_string().bold());
    if let Some(ref d) = platform.distro {
        println!("  Distro:       {}", d.name.bold());
        if !d.id_like.is_empty() {
            println!("  Family:       {}", d.id_like.dimmed());
        }
    }
    let pm_names: Vec<String> = platform.pkg_managers.iter().map(|p| p.to_string()).collect();
    println!(
        "  Pkg Managers: {}",
        if pm_names.is_empty() {
            "(none detected)".dimmed().to_string()
        } else {
            pm_names.join(", ").green().to_string()
        }
    );
}

// ═════════════════════════════════════════════════════════════════════════════
// Tool Status Checking
// ═════════════════════════════════════════════════════════════════════════════

/// Status of a single external tool dependency.
#[derive(Debug)]
pub struct ToolStatus {
    pub name: String,
    pub binary: String,
    pub available: bool,
    pub version: Option<String>,
    pub install_hint: String,
    pub required_for: String,
}

struct ToolDescriptor {
    name: &'static str,
    binary: &'static str,
    version_args: &'static [&'static str],
    install_hint: &'static str,
    required_for: &'static str,
}

fn tool_descriptors() -> Vec<ToolDescriptor> {
    vec![
        ToolDescriptor {
            name: "apkeep",
            binary: "apkeep",
            version_args: &["--version"],
            install_hint: "cargo install apkeep\n       OR download from https://github.com/EFForg/apkeep/releases",
            required_for: "APK downloading from Play Store / APKPure",
        },
        ToolDescriptor {
            name: "jadx",
            binary: "jadx",
            version_args: &["--version"],
            install_hint: "Download from https://github.com/skylot/jadx/releases\n       Extract and add bin/ to PATH. Requires Java.",
            required_for: "APK decompilation to Java source",
        },
        ToolDescriptor {
            name: "Java Runtime",
            binary: "java",
            version_args: &["--version"],
            install_hint: "sudo apt install default-jre\n       OR install from https://adoptium.net",
            required_for: "Required by jadx for decompilation",
        },
        ToolDescriptor {
            name: "noseyparker",
            binary: "noseyparker",
            version_args: &["--version"],
            install_hint: "cargo install noseyparker\n       OR brew install noseyparker\n       OR download from https://github.com/praetorian-inc/noseyparker/releases",
            required_for: "Secret scanning of decompiled sources",
        },
    ]
}

fn check_tool(desc: &ToolDescriptor) -> ToolStatus {
    let available = which_exists(desc.binary);
    let version = if available {
        get_version(desc.binary, desc.version_args)
    } else {
        None
    };

    ToolStatus {
        name: desc.name.to_string(),
        binary: desc.binary.to_string(),
        available,
        version,
        install_hint: desc.install_hint.to_string(),
        required_for: desc.required_for.to_string(),
    }
}

pub fn check_all() -> Vec<ToolStatus> {
    tool_descriptors().iter().map(check_tool).collect()
}

#[allow(dead_code)]
pub fn all_available(statuses: &[ToolStatus]) -> bool {
    statuses.iter().all(|s| s.available)
}

pub fn print_status_table(statuses: &[ToolStatus]) {
    println!("\n{}", "Dependency Status".bright_cyan().bold());

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL)
        .apply_modifier(UTF8_ROUND_CORNERS);

    table.set_header(vec![
        Cell::new("Tool").fg(Color::Cyan),
        Cell::new("Status"),
        Cell::new("Version"),
        Cell::new("Required For"),
    ]);

    for s in statuses {
        let (status_text, status_color) = if s.available {
            ("FOUND", Color::Green)
        } else {
            ("MISSING", Color::Red)
        };

        table.add_row(vec![
            Cell::new(&s.name).fg(Color::White),
            Cell::new(status_text).fg(status_color),
            Cell::new(s.version.as_deref().unwrap_or("")),
            Cell::new(&s.required_for),
        ]);
    }

    println!("{table}");
}

pub fn print_install_instructions(statuses: &[ToolStatus]) {
    let missing: Vec<&ToolStatus> = statuses.iter().filter(|s| !s.available).collect();

    if missing.is_empty() {
        println!(
            "\n{}",
            "All dependencies are available. You're ready to go!"
                .green()
                .bold()
        );
        return;
    }

    println!(
        "\n{} {} missing tool(s):",
        "Setup Required:".yellow().bold(),
        missing.len()
    );

    for tool in &missing {
        println!();
        println!("  {} {}", "".yellow(), tool.name.bold());
        println!("    Binary: {}", tool.binary.dimmed());
        println!("    Install:");
        for line in tool.install_hint.lines() {
            println!("       {}", line);
        }
    }

    println!();
    println!(
        "  {}  Run {} to attempt automatic installation.",
        "Tip:".yellow().bold(),
        "flintbase setup --install".bold()
    );
}

/// Run the full setup check (used by `flintbase setup`).
pub fn run_setup_check() {
    let platform = detect_platform();
    print_platform_info(&platform);

    let statuses = check_all();
    print_status_table(&statuses);
    print_install_instructions(&statuses);
}

/// Quick pre-flight for the APK pipeline.
pub fn ensure_apk_tools_available() -> Result<(), String> {
    let statuses = check_all();
    let missing: Vec<&ToolStatus> = statuses.iter().filter(|s| !s.available).collect();

    if missing.is_empty() {
        return Ok(());
    }

    let names: Vec<&str> = missing.iter().map(|s| s.binary.as_str()).collect();
    Err(format!(
        "Missing required tools: {}. Run `flintbase setup --install` to auto-install, or `flintbase setup` for manual instructions.",
        names.join(", ")
    ))
}

// ═════════════════════════════════════════════════════════════════════════════
// Auto-Install
// ═════════════════════════════════════════════════════════════════════════════

/// Resolve the install directory for user-local binaries.
/// Prefers ~/.local/bin (XDG standard), creates it if needed.
fn user_bin_dir() -> PathBuf {
    let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let dir = PathBuf::from(home).join(".local").join("bin");
    let _ = fs::create_dir_all(&dir);
    dir
}

/// Resolve the install directory for extracted tool suites (jadx, etc.).
fn user_opt_dir() -> PathBuf {
    let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let dir = PathBuf::from(home)
        .join(".local")
        .join("share")
        .join("flintbase");
    let _ = fs::create_dir_all(&dir);
    dir
}

/// Check if a path is already in PATH.
fn is_in_path(dir: &Path) -> bool {
    if let Ok(path_var) = env::var("PATH") {
        path_var
            .split(':')
            .any(|p| Path::new(p) == dir)
    } else {
        false
    }
}

/// Prompt the user with a yes/no question. Returns true for yes (default).
fn prompt_yes_no(question: &str) -> bool {
    print!("  {} [Y/n] ", question);
    let _ = io::stdout().flush();
    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_err() {
        return false;
    }
    let trimmed = input.trim().to_lowercase();
    trimmed.is_empty() || trimmed == "y" || trimmed == "yes"
}

/// Detect the user's shell config file path (resolved to absolute).
fn detect_shell_rc() -> (String, PathBuf) {
    let shell = env::var("SHELL").unwrap_or_default();
    let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());

    if shell.contains("zsh") {
        ("~/.zshrc".to_string(), PathBuf::from(&home).join(".zshrc"))
    } else if shell.contains("fish") {
        (
            "~/.config/fish/config.fish".to_string(),
            PathBuf::from(&home).join(".config/fish/config.fish"),
        )
    } else {
        ("~/.bashrc".to_string(), PathBuf::from(&home).join(".bashrc"))
    }
}

/// Check if a shell config file already contains a PATH export for the given dir.
fn rc_already_has_path(rc_path: &Path, dir: &Path) -> bool {
    if let Ok(contents) = fs::read_to_string(rc_path) {
        let dir_str = dir.to_string_lossy();
        contents.contains(&*dir_str)
    } else {
        false
    }
}

/// Offer to add a directory to the user's PATH by appending to their shell config.
/// Returns true if the config was modified (so the caller can remind them to reload).
fn offer_add_to_path(dir: &Path) -> bool {
    if is_in_path(dir) {
        return false;
    }

    let (rc_display, rc_path) = detect_shell_rc();

    // Don't duplicate if it's already in the config file
    if rc_already_has_path(&rc_path, dir) {
        println!(
            "  {} {} is already in {} but not active in this shell.",
            "Note:".yellow().bold(),
            dir.display(),
            rc_display
        );
        println!(
            "    Reload your shell or run: {}",
            format!("source {}", rc_display).dimmed()
        );
        return false;
    }

    println!();
    println!(
        "  {} {} is not in your PATH.",
        "Note:".yellow().bold(),
        dir.display()
    );

    let shell = env::var("SHELL").unwrap_or_default();
    let is_fish = shell.contains("fish");

    if prompt_yes_no(&format!("Add {} to your PATH in {}?", dir.display(), rc_display)) {
        let line = if is_fish {
            format!(
                "\n# Added by flintbase setup\nfish_add_path {}\n",
                dir.display()
            )
        } else {
            format!(
                "\n# Added by flintbase setup\nexport PATH=\"{}:$PATH\"\n",
                dir.display()
            )
        };

        // Ensure parent directory exists (for fish config)
        if let Some(parent) = rc_path.parent() {
            let _ = fs::create_dir_all(parent);
        }

        match fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&rc_path)
        {
            Ok(mut f) => {
                if write!(f, "{}", line).is_ok() {
                    println!(
                        "  {} Appended to {}",
                        "".green(),
                        rc_display
                    );
                    println!(
                        "    Reload your shell or run: {}",
                        format!("source {}", rc_display).dimmed()
                    );
                    return true;
                }
                println!(
                    "  {} Failed to write to {}",
                    "".red(),
                    rc_display
                );
            }
            Err(e) => {
                println!(
                    "  {} Could not open {}: {}",
                    "".red(),
                    rc_display,
                    e
                );
            }
        }
    } else {
        // User declined — show the manual command
        if is_fish {
            println!(
                "    To add manually: {}",
                format!("fish_add_path {}", dir.display()).dimmed()
            );
        } else {
            println!(
                "    To add manually: {}",
                format!(
                    "echo 'export PATH=\"{}:$PATH\"' >> {}",
                    dir.display(),
                    rc_display
                )
                .dimmed()
            );
        }
    }

    false
}

/// Run automatic installation of all missing tools.
pub fn run_auto_install() {
    let platform = detect_platform();
    print_platform_info(&platform);

    let statuses = check_all();
    print_status_table(&statuses);

    let missing: Vec<&ToolStatus> = statuses.iter().filter(|s| !s.available).collect();

    if missing.is_empty() {
        println!(
            "\n{}",
            "All dependencies are already installed. Nothing to do!"
                .green()
                .bold()
        );
        return;
    }

    println!(
        "\n{} Attempting to install {} missing tool(s)...",
        "Auto-Install:".bright_cyan().bold(),
        missing.len()
    );

    let missing_names: Vec<String> = missing.iter().map(|s| s.binary.clone()).collect();

    // Install in dependency order: java first (jadx needs it), then the rest
    let order = ["java", "jadx", "apkeep", "noseyparker"];
    let mut any_path_hint = false;

    for tool_name in &order {
        if !missing_names.iter().any(|n| n == tool_name) {
            continue;
        }

        println!(
            "\n{} {}",
            "Installing:".bold(),
            tool_name.bright_cyan().bold()
        );
        println!("{}", "".repeat(50));

        let result = match *tool_name {
            "java" => install_java(&platform),
            "jadx" => install_jadx(&platform),
            "apkeep" => install_apkeep(&platform),
            "noseyparker" => install_noseyparker(&platform),
            _ => Err(format!("No auto-install handler for {}", tool_name)),
        };

        match result {
            Ok(path_hint) => {
                // Verify installation
                if which_exists(tool_name) {
                    println!(
                        "  {} {} installed successfully!",
                        "".green().bold(),
                        tool_name
                    );
                } else if let Some(ref dir) = path_hint {
                    println!(
                        "  {} {} installed to {}",
                        "".green().bold(),
                        tool_name,
                        dir.display()
                    );
                    if offer_add_to_path(dir) {
                        any_path_hint = true;
                    }
                } else {
                    println!(
                        "  {} {} install command succeeded but binary not found in PATH",
                        "".yellow(),
                        tool_name
                    );
                }
            }
            Err(e) => {
                println!(
                    "  {} Failed to install {}: {}",
                    "".red().bold(),
                    tool_name,
                    e
                );
            }
        }
    }

    // Check common tool directories that may not be in PATH
    let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let common_dirs = [
        PathBuf::from(&home).join(".cargo/bin"),
        PathBuf::from(&home).join(".local/bin"),
    ];
    for dir in &common_dirs {
        if dir.exists() && !is_in_path(dir) {
            if offer_add_to_path(dir) {
                any_path_hint = true;
            }
        }
    }

    // Final verification
    println!("\n{}", "".repeat(50));
    println!("{}", "Post-Install Verification".bright_cyan().bold());
    let final_statuses = check_all();
    print_status_table(&final_statuses);

    let still_missing: Vec<&ToolStatus> =
        final_statuses.iter().filter(|s| !s.available).collect();

    if still_missing.is_empty() && !any_path_hint {
        println!(
            "\n{}",
            "All tools installed successfully! You're ready to use `flintbase apk`."
                .green()
                .bold()
        );
    } else if still_missing.is_empty() && any_path_hint {
        println!(
            "\n{}",
            "All tools installed! Reload your shell (or update PATH as shown above) and you're ready."
                .green()
                .bold()
        );
    } else {
        let names: Vec<&str> = still_missing.iter().map(|s| s.binary.as_str()).collect();
        println!(
            "\n{} Still missing: {}",
            "Warning:".yellow().bold(),
            names.join(", ").red()
        );
        println!("  Please install them manually using the hints above.");
    }
}

// ── Per-Tool Installers ──────────────────────────────────────────────────────

/// Return a distro-appropriate install hint for the `unzip` package.
fn unzip_install_hint(platform: &Platform) -> &'static str {
    if platform.has_pm(PkgManager::Apt) {
        "sudo apt install unzip"
    } else if platform.has_pm(PkgManager::Dnf) {
        "sudo dnf install unzip"
    } else if platform.has_pm(PkgManager::Pacman) {
        "sudo pacman -S unzip"
    } else if platform.has_pm(PkgManager::Zypper) {
        "sudo zypper install unzip"
    } else if platform.has_pm(PkgManager::Brew) {
        "brew install unzip"
    } else {
        "install the 'unzip' package with your system package manager"
    }
}

/// Install Java Runtime.
/// Returns Ok(None) if installed globally, Ok(Some(path)) if path hint needed.
fn install_java(platform: &Platform) -> Result<Option<PathBuf>, String> {
    match platform.os {
        Os::Linux => {
            if platform.has_pm(PkgManager::Apt) {
                run_sudo_cmd("apt", &["install", "-y", "default-jre"])
            } else if platform.has_pm(PkgManager::Dnf) {
                run_sudo_cmd("dnf", &["install", "-y", "java-latest-openjdk"])
            } else if platform.has_pm(PkgManager::Pacman) {
                run_sudo_cmd("pacman", &["-S", "--noconfirm", "jre-openjdk"])
            } else if platform.has_pm(PkgManager::Zypper) {
                run_sudo_cmd("zypper", &["install", "-y", "java-21-openjdk"])
            } else if platform.has_pm(PkgManager::Brew) {
                run_cmd("brew", &["install", "openjdk"])
            } else {
                Err("No supported package manager found. Install Java from https://adoptium.net".into())
            }
        }
        Os::MacOs => {
            if platform.has_pm(PkgManager::Brew) {
                run_cmd("brew", &["install", "openjdk"])
            } else {
                Err("Install Homebrew first (https://brew.sh), then: brew install openjdk".into())
            }
        }
        _ => Err("Auto-install for Java not supported on this OS. Install from https://adoptium.net".into()),
    }
}

/// Install jadx by downloading the release ZIP from GitHub.
fn install_jadx(platform: &Platform) -> Result<Option<PathBuf>, String> {
    // jadx is a cross-platform ZIP — just needs Java
    let opt_dir = user_opt_dir();
    let jadx_dir = opt_dir.join("jadx");
    let bin_dir = user_bin_dir();

    println!("  Fetching latest jadx version from GitHub...");

    // Get latest version tag
    let version = fetch_github_latest_tag("skylot", "jadx")
        .map_err(|e| format!("Failed to query GitHub: {}", e))?;

    let version_num = version.trim_start_matches('v');
    let zip_name = format!("jadx-{}.zip", version_num);
    let download_url = format!(
        "https://github.com/skylot/jadx/releases/download/{}/{}",
        version, zip_name
    );

    println!("  Downloading jadx {}...", version.bold());
    let tmp_zip = opt_dir.join(&zip_name);
    download_file(&download_url, &tmp_zip)?;

    // Extract
    println!("  Extracting to {}...", jadx_dir.display());
    if jadx_dir.exists() {
        let _ = fs::remove_dir_all(&jadx_dir);
    }
    fs::create_dir_all(&jadx_dir).map_err(|e| e.to_string())?;

    // Try unzip first, then jar xf as fallback
    let unzip_ok = if which_exists("unzip") {
        Command::new("unzip")
            .arg("-o")
            .arg("-q")
            .arg(&tmp_zip)
            .arg("-d")
            .arg(&jadx_dir)
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    } else {
        false
    };

    if !unzip_ok {
        // Try python3 -m zipfile
        if which_exists("python3") {
            let ok = Command::new("python3")
                .arg("-m")
                .arg("zipfile")
                .arg("-e")
                .arg(&tmp_zip)
                .arg(&jadx_dir)
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if !ok {
                let _ = fs::remove_file(&tmp_zip);
                return Err(format!(
                    "Failed to extract jadx ZIP. Install `unzip`: {}",
                    unzip_install_hint(platform)
                ));
            }
        } else {
            let _ = fs::remove_file(&tmp_zip);
            return Err(format!(
                "No unzip or python3 available. Install `unzip`: {}",
                unzip_install_hint(platform)
            ));
        }
    }

    let _ = fs::remove_file(&tmp_zip);

    // Make jadx binaries executable
    let jadx_bin = jadx_dir.join("bin").join("jadx");
    if jadx_bin.exists() {
        let _ = set_executable(&jadx_bin);
        let _ = set_executable(&jadx_dir.join("bin").join("jadx-gui"));
    }

    // Symlink jadx into user bin dir
    let link_path = bin_dir.join("jadx");
    let _ = fs::remove_file(&link_path); // remove old link if exists

    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(&jadx_bin, &link_path)
            .map_err(|e| format!("Failed to symlink: {}", e))?;
    }

    println!(
        "  Installed jadx {}{}",
        version,
        link_path.display()
    );

    if platform.os == Os::Linux || platform.os == Os::MacOs {
        Ok(Some(bin_dir))
    } else {
        Ok(None)
    }
}

/// Install apkeep — prefer cargo install, fallback to binary download.
fn install_apkeep(platform: &Platform) -> Result<Option<PathBuf>, String> {
    // Strategy 1: cargo install (works everywhere with Rust toolchain)
    if platform.has_pm(PkgManager::Cargo) {
        println!("  Installing via cargo install apkeep...");
        let status = Command::new("cargo")
            .arg("install")
            .arg("apkeep")
            .status()
            .map_err(|e| e.to_string())?;
        if status.success() {
            return Ok(None); // cargo installs to ~/.cargo/bin which should be in PATH
        }
        println!(
            "  {} cargo install failed, trying binary download...",
            "".yellow()
        );
    }

    // Strategy 2: Download pre-built binary from GitHub
    let target = match (platform.os, platform.arch) {
        (Os::Linux, Arch::X86_64) => "x86_64-unknown-linux-gnu",
        (Os::Linux, Arch::Aarch64) => "aarch64-unknown-linux-gnu",
        (Os::MacOs, Arch::X86_64) => "x86_64-apple-darwin",
        (Os::MacOs, Arch::Aarch64) => "aarch64-apple-darwin",
        _ => return Err("No pre-built apkeep binary for this platform. Install Rust and use: cargo install apkeep".into()),
    };

    let version = fetch_github_latest_tag("EFForg", "apkeep")
        .map_err(|e| format!("Failed to query GitHub: {}", e))?;
    let version_num = version.trim_start_matches('v');
    let asset_name = format!("apkeep-{}", target);
    let download_url = format!(
        "https://github.com/EFForg/apkeep/releases/download/{}/{}",
        version_num, asset_name
    );

    println!("  Downloading apkeep {} for {}...", version_num.bold(), target);
    let bin_dir = user_bin_dir();
    let dest = bin_dir.join("apkeep");
    download_file(&download_url, &dest)?;
    set_executable(&dest)?;

    println!("  Installed apkeep → {}", dest.display());
    Ok(Some(bin_dir))
}

/// Install noseyparker — prefer brew, then pre-built GitHub binary.
///
/// NOTE: `cargo install noseyparker` is NOT supported upstream; the project
/// requires building from source with vectorscan/hyperscan and many system
/// dependencies.  We therefore skip the cargo strategy entirely and rely on
/// Homebrew (macOS / Linuxbrew) and GitHub release binaries.
///
/// GitHub release assets (as of v0.24.0):
///   - noseyparker-v{VER}-aarch64-apple-darwin.tar.gz
///   - noseyparker-v{VER}-aarch64-unknown-linux-gnu.tar.gz
///   - noseyparker-v{VER}-aarch64-unknown-linux-musl.tar.gz
///   - noseyparker-v{VER}-x86_64-apple-darwin.tar.gz
///   - noseyparker-v{VER}-x86_64-unknown-linux-gnu.tar.gz
///   - noseyparker-v{VER}-x86_64-unknown-linux-musl.tar.gz
fn install_noseyparker(platform: &Platform) -> Result<Option<PathBuf>, String> {
    // Strategy 1: Homebrew (easiest, includes all deps)
    if platform.has_pm(PkgManager::Brew) {
        println!("  Installing via brew install noseyparker...");
        let status = Command::new("brew")
            .arg("install")
            .arg("noseyparker")
            .status()
            .map_err(|e| e.to_string())?;
        if status.success() {
            return Ok(None);
        }
        println!(
            "  {} brew install failed, trying binary download...",
            "".yellow()
        );
    }

    // Strategy 2: Download pre-built binary from GitHub releases
    let target = match (platform.os, platform.arch) {
        (Os::Linux, Arch::X86_64) => {
            let libc = detect_linux_libc();
            if libc == "musl" {
                "x86_64-unknown-linux-musl"
            } else {
                "x86_64-unknown-linux-gnu"
            }
        }
        (Os::Linux, Arch::Aarch64) => {
            let libc = detect_linux_libc();
            if libc == "musl" {
                "aarch64-unknown-linux-musl"
            } else {
                "aarch64-unknown-linux-gnu"
            }
        }
        (Os::MacOs, Arch::X86_64) => "x86_64-apple-darwin",
        (Os::MacOs, Arch::Aarch64) => "aarch64-apple-darwin",
        _ => {
            return Err(
                "No pre-built noseyparker binary for this platform. \
                 Install manually via: brew install noseyparker  \
                 or build from source: https://github.com/praetorian-inc/noseyparker"
                    .into(),
            )
        }
    };

    // Fetch latest release version from GitHub
    let version = fetch_github_latest_tag("praetorian-inc", "noseyparker")
        .map_err(|e| format!("Failed to query GitHub releases: {}", e))?;

    // Asset names use the full tag including the 'v' prefix:
    //   noseyparker-v0.24.0-x86_64-unknown-linux-gnu.tar.gz
    let asset_name = format!("noseyparker-{}-{}.tar.gz", version, target);
    let download_url = format!(
        "https://github.com/praetorian-inc/noseyparker/releases/download/{}/{}",
        version, asset_name
    );

    println!(
        "  Downloading noseyparker {} for {} ...",
        version.bold(),
        target
    );
    let opt_dir = user_opt_dir();
    let tmp_tar = opt_dir.join(&asset_name);
    download_file(&download_url, &tmp_tar)?;

    // Extract tarball
    let np_dir = opt_dir.join("noseyparker");
    // Clean up any previous installation in this directory
    if np_dir.exists() {
        let _ = fs::remove_dir_all(&np_dir);
    }
    let _ = fs::create_dir_all(&np_dir);

    let extract_ok = Command::new("tar")
        .arg("xzf")
        .arg(&tmp_tar)
        .arg("-C")
        .arg(&np_dir)
        .arg("--strip-components=1")
        .status()
        .map(|s| s.success())
        .unwrap_or(false);

    let _ = fs::remove_file(&tmp_tar);

    if !extract_ok {
        return Err("Failed to extract noseyparker tarball.".into());
    }

    // Find the binary and symlink it into ~/.local/bin
    let bin_dir = user_bin_dir();
    let np_bin = find_binary_in_dir(&np_dir, "noseyparker");

    if let Some(src) = np_bin {
        set_executable(&src)?;
        let dest = bin_dir.join("noseyparker");
        let _ = fs::remove_file(&dest);
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&src, &dest)
                .map_err(|e| format!("Failed to symlink: {}", e))?;
        }
        println!(
            "  {} Installed noseyparker → {}",
            "".green(),
            dest.display()
        );
        Ok(Some(bin_dir))
    } else {
        Err("Could not locate noseyparker binary in extracted archive.".into())
    }
}

impl Platform {
    fn has_pm(&self, pm: PkgManager) -> bool {
        self.pkg_managers.contains(&pm)
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Shared Helpers
// ═════════════════════════════════════════════════════════════════════════════

fn which_exists(binary: &str) -> bool {
    Command::new("which")
        .arg(binary)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn get_version(binary: &str, args: &[&str]) -> Option<String> {
    Command::new(binary)
        .args(args)
        .output()
        .ok()
        .and_then(|o| {
            let out = String::from_utf8_lossy(&o.stdout).to_string();
            let err = String::from_utf8_lossy(&o.stderr).to_string();
            let combined = if out.trim().is_empty() { err } else { out };
            combined.lines().next().map(|l| l.trim().to_string())
        })
        .filter(|s| !s.is_empty())
}

/// Run a command with sudo.
fn run_sudo_cmd(bin: &str, args: &[&str]) -> Result<Option<PathBuf>, String> {
    println!("  Running: sudo {} {}", bin, args.join(" "));
    let status = Command::new("sudo")
        .arg(bin)
        .args(args)
        .status()
        .map_err(|e| format!("Failed to run sudo {}: {}", bin, e))?;

    if status.success() {
        Ok(None)
    } else {
        Err(format!(
            "sudo {} {} exited with code {:?}",
            bin,
            args.join(" "),
            status.code()
        ))
    }
}

/// Run a command without sudo.
fn run_cmd(bin: &str, args: &[&str]) -> Result<Option<PathBuf>, String> {
    println!("  Running: {} {}", bin, args.join(" "));
    let status = Command::new(bin)
        .args(args)
        .status()
        .map_err(|e| format!("Failed to run {}: {}", bin, e))?;

    if status.success() {
        Ok(None)
    } else {
        Err(format!(
            "{} {} exited with code {:?}",
            bin,
            args.join(" "),
            status.code()
        ))
    }
}

/// Fetch the latest release tag from a GitHub repo via the API.
fn fetch_github_latest_tag(owner: &str, repo: &str) -> Result<String, String> {
    let url = format!(
        "https://api.github.com/repos/{}/{}/releases/latest",
        owner, repo
    );
    let client = reqwest::blocking::Client::builder()
        .user_agent("flintbase-setup/0.1")
        .timeout(std::time::Duration::from_secs(15))
        .build()
        .map_err(|e| e.to_string())?;

    let resp = client.get(&url).send().map_err(|e| e.to_string())?;
    if !resp.status().is_success() {
        return Err(format!("GitHub API returned {}", resp.status()));
    }

    let data: serde_json::Value = resp.json().map_err(|e| e.to_string())?;
    data.get("tag_name")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .ok_or_else(|| "No tag_name in GitHub release response".into())
}

/// Download a file from a URL to a local path using curl or reqwest.
fn download_file(url: &str, dest: &Path) -> Result<(), String> {
    // Prefer curl for large files (streams to disk, shows progress)
    if which_exists("curl") {
        let status = Command::new("curl")
            .arg("-L") // follow redirects
            .arg("-f") // fail on HTTP errors
            .arg("-#") // progress bar
            .arg("-o")
            .arg(dest)
            .arg(url)
            .status()
            .map_err(|e| format!("Failed to run curl: {}", e))?;

        if status.success() {
            return Ok(());
        }
        // Fall through to reqwest
    }

    // Fallback: use reqwest (in-memory)
    let client = reqwest::blocking::Client::builder()
        .user_agent("flintbase-setup/0.1")
        .timeout(std::time::Duration::from_secs(120))
        .build()
        .map_err(|e| e.to_string())?;

    let resp = client
        .get(url)
        .send()
        .map_err(|e| format!("Download failed: {}", e))?;

    if !resp.status().is_success() {
        return Err(format!("Download returned HTTP {}", resp.status()));
    }

    let bytes = resp.bytes().map_err(|e| e.to_string())?;
    fs::write(dest, &bytes).map_err(|e| format!("Failed to write {}: {}", dest.display(), e))?;
    Ok(())
}

/// Set a file as executable (chmod +x).
#[cfg(unix)]
fn set_executable(path: &Path) -> Result<(), String> {
    use std::os::unix::fs::PermissionsExt;
    let meta = fs::metadata(path).map_err(|e| e.to_string())?;
    let mut perms = meta.permissions();
    perms.set_mode(perms.mode() | 0o755);
    fs::set_permissions(path, perms).map_err(|e| e.to_string())
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) -> Result<(), String> {
    Ok(()) // no-op on non-Unix
}

/// Recursively find a binary by name inside a directory.
fn find_binary_in_dir(dir: &Path, name: &str) -> Option<PathBuf> {
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if let Some(found) = find_binary_in_dir(&path, name) {
                    return Some(found);
                }
            } else if let Some(fname) = path.file_name().and_then(|n| n.to_str()) {
                if fname == name {
                    return Some(path);
                }
            }
        }
    }
    None
}