zoi-rs 1.7.0

Universal Package Manager & Environment Setup Tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use crate::pkg::resolve::SourceType;
use anyhow::anyhow;
use colored::*;
use std::fmt::Display;
use std::fs;
use std::io::{Write, stdin, stdout};
use std::process::Command;
use std::time::Duration;
use walkdir::WalkDir;

#[cfg(windows)]
use junction;

pub fn format_bytes(bytes: u64) -> String {
    const KIB: u64 = 1024;
    const MIB: u64 = 1024 * KIB;
    const GIB: u64 = 1024 * MIB;

    if bytes >= GIB {
        format!("{:.2} GiB", bytes as f64 / GIB as f64)
    } else if bytes >= MIB {
        format!("{:.2} MiB", bytes as f64 / MIB as f64)
    } else if bytes >= KIB {
        format!("{:.2} KiB", bytes as f64 / KIB as f64)
    } else {
        format!("{} B", bytes)
    }
}

pub fn format_size_diff(diff: i64) -> String {
    if diff == 0 {
        return "0 B".to_string();
    }

    let sign = if diff > 0 { "+" } else { "-" };
    let bytes = diff.unsigned_abs();

    format!("{} {}", sign, format_bytes(bytes))
}

use crate::pkg::types::Scope;
use clap_complete::Shell;
use std::path::{Path, PathBuf};

pub fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        if ty.is_dir() {
            copy_dir_all(&entry.path(), &dst.join(entry.file_name()))?;
        } else {
            fs::copy(entry.path(), dst.join(entry.file_name()))?;
        }
    }
    Ok(())
}

pub fn symlink_file(target: &Path, link: &Path) -> std::io::Result<()> {
    if link.exists() || link.is_symlink() {
        fs::remove_file(link)?;
    }

    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, link)
    }
    #[cfg(windows)]
    {
        if std::os::windows::fs::symlink_file(target, link).is_err() {
            if fs::hard_link(target, link).is_err() {
                fs::copy(target, link)?;
            }
        }
        Ok(())
    }
}

pub fn symlink_dir(target: &Path, link: &Path) -> std::io::Result<()> {
    if link.exists() || link.is_symlink() {
        if link.is_dir() && !link.is_symlink() {
            fs::remove_dir_all(link)?;
        } else {
            fs::remove_file(link)?;
        }
    }

    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, link)
    }
    #[cfg(windows)]
    {
        junction::create(target, link)
    }
}

pub fn is_admin() -> bool {
    #[cfg(windows)]
    {
        use std::mem;
        use std::ptr;
        use winapi::um::handleapi::CloseHandle;
        use winapi::um::processthreadsapi::GetCurrentProcess;
        use winapi::um::processthreadsapi::OpenProcessToken;
        use winapi::um::securitybaseapi::CheckTokenMembership;
        use winapi::um::winnt::{PSID, TOKEN_QUERY};

        let mut token = ptr::null_mut();
        let process = unsafe { GetCurrentProcess() };
        if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 {
            return false;
        }

        let mut sid: [u8; 8] = [0; 8];
        let mut sid_size = mem::size_of_val(&sid) as u32;
        if unsafe {
            winapi::um::securitybaseapi::CreateWellKnownSid(
                winapi::um::winnt::WinBuiltinAdministratorsSid,
                ptr::null_mut(),
                sid.as_mut_ptr() as PSID,
                &mut sid_size,
            )
        } == 0
        {
            unsafe { CloseHandle(token) };
            return false;
        }

        let mut is_member = 0;
        let result =
            unsafe { CheckTokenMembership(token, sid.as_mut_ptr() as PSID, &mut is_member) };
        unsafe { CloseHandle(token) };

        result != 0 && is_member != 0
    }
    #[cfg(unix)]
    {
        nix::unistd::getuid().is_root()
    }
}

pub fn print_info<T: Display>(key: &str, value: T) {
    println!("{}: {}", key, value);
}

pub fn format_version_summary(branch: &str, status: &str, number: &str) -> String {
    let branch_short = if branch == "Production" {
        "Prod."
    } else if branch == "Development" {
        "Dev."
    } else if branch == "Public" {
        "Pub."
    } else if branch == "Special" {
        "Spec."
    } else {
        branch
    };
    format!(
        "{} {} {}",
        branch_short.blue().bold().italic(),
        status,
        number,
    )
}

pub fn format_version_full(branch: &str, status: &str, number: &str, commit: &str) -> String {
    format!(
        "{} {}",
        format_version_summary(branch, status, number),
        commit.green()
    )
}

pub fn print_aligned_info(key: &str, value: &str) {
    let key_with_colon = format!("{}:", key);
    println!("{:<18}{}", key_with_colon.cyan(), value);
}

pub fn run_shell_command(command_str: &str) -> anyhow::Result<()> {
    let status = if cfg!(target_os = "windows") {
        Command::new("pwsh")
            .arg("-Command")
            .arg(command_str)
            .status()?
    } else {
        Command::new("bash").arg("-c").arg(command_str).status()?
    };

    if !status.success() {
        return Err(anyhow!("Command failed: {}", command_str));
    }
    Ok(())
}

pub fn command_exists(command: &str) -> bool {
    if cfg!(target_os = "windows") {
        Command::new("where")
            .arg(command)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    } else {
        Command::new("bash")
            .arg("-c")
            .arg(format!("command -v {}", command))
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    }
}

pub fn ask_for_confirmation(prompt: &str, yes: bool) -> bool {
    if yes {
        return true;
    }
    print!("{} [y/N]: ", prompt.yellow());
    let _ = stdout().flush();
    let mut input = String::new();
    if stdin().read_line(&mut input).is_err() {
        return false;
    }
    input.trim().eq_ignore_ascii_case("y")
}

pub fn set_path_read_only(path: &Path) -> anyhow::Result<()> {
    if !path.exists() {
        return Ok(());
    }
    for entry in WalkDir::new(path) {
        let entry = entry?;
        let mut perms = fs::metadata(entry.path())?.permissions();
        if !perms.readonly() {
            perms.set_readonly(true);
            fs::set_permissions(entry.path(), perms)?;
        }
    }
    Ok(())
}

pub fn set_path_writable(path: &Path) -> anyhow::Result<()> {
    if !path.exists() {
        return Ok(());
    }
    for entry in WalkDir::new(path) {
        let entry = entry?;
        let mut perms = fs::metadata(entry.path())?.permissions();
        if perms.readonly() {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = perms.mode();
                perms.set_mode(mode | 0o200);
            }
            #[cfg(not(unix))]
            {
                perms.set_readonly(false);
            }
            fs::set_permissions(entry.path(), perms)?;
        }
    }
    Ok(())
}

use std::collections::HashMap;

pub fn get_linux_distribution_info() -> Option<HashMap<String, String>> {
    if let Ok(contents) = fs::read_to_string("/etc/os-release") {
        let info: HashMap<String, String> = contents
            .lines()
            .filter_map(|line| {
                let mut parts = line.splitn(2, '=');
                let key = parts.next()?;
                let value = parts.next()?.trim_matches('"').to_string();
                if key.is_empty() {
                    None
                } else {
                    Some((key.to_string(), value))
                }
            })
            .collect();
        if info.is_empty() { None } else { Some(info) }
    } else {
        None
    }
}

pub fn get_linux_distro_family() -> Option<String> {
    if let Some(info) = get_linux_distribution_info() {
        if let Some(id_like) = info.get("ID_LIKE") {
            let families: Vec<&str> = id_like.split_whitespace().collect();
            if families.contains(&"debian") {
                return Some("debian".to_string());
            }
            if families.contains(&"arch") {
                return Some("arch".to_string());
            }
            if families.contains(&"fedora") {
                return Some("fedora".to_string());
            }
            if families.contains(&"rhel") {
                return Some("fedora".to_string());
            }
            if families.contains(&"suse") {
                return Some("suse".to_string());
            }
            if families.contains(&"gentoo") {
                return Some("gentoo".to_string());
            }
        }
        if let Some(id) = info.get("ID") {
            return match id.as_str() {
                "debian" | "ubuntu" | "linuxmint" | "pop" | "kali" | "kubuntu" | "lubuntu"
                | "xubuntu" | "zorin" | "elementary" => Some("debian".to_string()),
                "arch" | "manjaro" | "cachyos" | "endeavouros" | "garuda" => {
                    Some("arch".to_string())
                }
                "fedora" | "centos" | "rhel" | "rocky" | "almalinux" => Some("fedora".to_string()),
                "opensuse" | "opensuse-tumbleweed" | "opensuse-leap" => Some("suse".to_string()),
                "gentoo" => Some("gentoo".to_string()),
                "alpine" => Some("alpine".to_string()),
                "void" => Some("void".to_string()),
                "solus" => Some("solus".to_string()),
                "guix" => Some("guix".to_string()),
                _ => None,
            };
        }
    }
    None
}

pub fn get_linux_distribution() -> Option<String> {
    get_linux_distribution_info().and_then(|info| info.get("ID").cloned())
}

pub fn get_native_package_manager() -> Option<String> {
    let os = std::env::consts::OS;
    match os {
        "linux" => get_linux_distro_family()
            .map(|family| {
                match family.as_str() {
                    "debian" => "apt",
                    "arch" => "pacman",
                    "fedora" => "dnf",
                    "suse" => "zypper",
                    "gentoo" => "portage",
                    "alpine" => "apk",
                    "void" => "xbps-install",
                    "solus" => "eopkg",
                    "guix" => "guix",
                    _ => "unknown",
                }
                .to_string()
            })
            .filter(|s| s != "unknown"),
        "macos" => {
            if command_exists("brew") {
                Some("brew".to_string())
            } else if command_exists("port") {
                Some("macports".to_string())
            } else {
                None
            }
        }
        "windows" => {
            if command_exists("scoop") {
                Some("scoop".to_string())
            } else if command_exists("choco") {
                Some("choco".to_string())
            } else if command_exists("winget") {
                Some("winget".to_string())
            } else {
                None
            }
        }
        "freebsd" => Some("pkg".to_string()),
        "openbsd" => Some("pkg_add".to_string()),
        _ => None,
    }
}

pub fn print_repo_warning(repo_name: &str) {
    if let Ok(db_path) = crate::pkg::resolve::get_db_root()
        && let Ok(repo_config) = crate::pkg::config::read_repo_config(&db_path)
    {
        let major_repo = repo_name.split('/').next().unwrap_or_default();
        if let Some(repo_entry) = repo_config.repos.iter().find(|r| r.name == major_repo) {
            let warning_message = match repo_entry.repo_type.as_str() {
                "unofficial" => {
                    Some("This package is from an unofficial repository and is not trusted.")
                }
                "community" => {
                    Some("This package is from a community repository. Use with caution.")
                }
                "test" => Some(
                    "This package is from a testing repository and may not function correctly.",
                ),
                "archive" => {
                    Some("This package is from an archive repository and is no longer maintained.")
                }
                _ => None,
            };

            if let Some(message) = warning_message {
                println!("\n{}: {}", "NOTE".yellow().bold(), message.yellow());
            }
        }
    }
}

pub fn confirm_untrusted_source(source_type: &SourceType, yes: bool) -> anyhow::Result<()> {
    if source_type == &SourceType::OfficialRepo {
        return Ok(());
    }

    let warning_message = match source_type {
        SourceType::UntrustedRepo(repo) => {
            format!(
                "The package from repository '@{}' is not an official Zoi repository.",
                repo
            )
        }
        SourceType::LocalFile => "You are installing from a local file.".to_string(),
        SourceType::Url => "You are installing from a remote URL.".to_string(),
        _ => return Ok(()),
    };

    println!(
        "\n{}: {}",
        "SECURITY WARNING".yellow().bold(),
        warning_message
    );

    if ask_for_confirmation(
        "This source is not trusted. Are you sure you want to continue?",
        yes,
    ) {
        Ok(())
    } else {
        Err(anyhow!("Operation aborted by user."))
    }
}

pub fn is_platform_compatible(current_platform: &str, allowed_platforms: &[String]) -> bool {
    let os = match std::env::consts::OS {
        "darwin" => "macos",
        other => other,
    };
    allowed_platforms
        .iter()
        .any(|p| p == "all" || p == os || p == current_platform)
}

pub fn setup_path(scope: Scope) -> anyhow::Result<()> {
    if scope == Scope::Project {
        return Ok(());
    }

    let zoi_bin_dir = match scope {
        Scope::User => {
            let home = home::home_dir().ok_or_else(|| anyhow!("Could not find home directory."))?;
            crate::pkg::sysroot::apply_sysroot(home.join(".zoi").join("pkgs").join("bin"))
        }
        Scope::System => {
            if cfg!(target_os = "windows") {
                crate::pkg::sysroot::apply_sysroot(PathBuf::from("C:\\ProgramData\\zoi\\pkgs\\bin"))
            } else {
                crate::pkg::sysroot::apply_sysroot(PathBuf::from("/usr/local/bin"))
            }
        }
        Scope::Project => return Ok(()),
    };

    if !zoi_bin_dir.exists() {
        fs::create_dir_all(&zoi_bin_dir)?;
    }

    if scope == Scope::System && cfg!(unix) {
        println!(
            "{}",
            "System-wide installation complete. Binaries are in the system PATH.".green()
        );
        return Ok(());
    }

    println!("{}", "Ensuring Zoi bin directory is in your PATH...".bold());

    #[cfg(unix)]
    {
        use std::fs::{File, OpenOptions};
        let home = home::home_dir().ok_or_else(|| anyhow!("Could not find home directory."))?;
        let zoi_bin_str = "$HOME/.zoi/pkgs/bin";

        let shell_name = std::env::var("SHELL").unwrap_or_default();
        let (profile_file_path, cmd_to_write) = if shell_name.contains("bash") {
            let path = if cfg!(target_os = "macos") {
                home.join(".bash_profile")
            } else {
                home.join(".bashrc")
            };
            let cmd = format!(
                "\n# Added by Zoi\nexport PATH=\"{}:{}\"\n",
                zoi_bin_str, "$PATH"
            );
            (path, cmd)
        } else if shell_name.contains("zsh") {
            let path = home.join(".zshrc");
            let cmd = format!(
                "\n# Added by Zoi\nexport PATH=\"{}:{}\"\n",
                zoi_bin_str, "$PATH"
            );
            (path, cmd)
        } else if shell_name.contains("fish") {
            let path = home.join(".config/fish/config.fish");
            let cmd = format!("\n# Added by Zoi\nset -gx PATH \"{}\" $PATH\n", zoi_bin_str);

            (path, cmd)
        } else if shell_name.contains("elvish") {
            let path = home.join(".config/elvish/rc.elv");
            let cmd = "
# Added by Zoi
set paths = [ ~/.zoi/pkgs/bin $paths... ]
"
            .to_string();
            (path, cmd)
        } else if shell_name.contains("csh") || shell_name.contains("tcsh") {
            let path = home.join(".cshrc");
            let cmd = format!(
                "\n# Added by Zoi\nsetenv PATH=\"{}:{}\"\n",
                zoi_bin_str, "$PATH"
            );
            (path, cmd)
        } else {
            let path = home.join(".profile");
            let cmd = format!(
                "\n# Added by Zoi\nexport PATH=\"{}:{}\"\n",
                zoi_bin_str, "$PATH"
            );
            (path, cmd)
        };

        if !profile_file_path.exists() {
            if let Some(parent) = profile_file_path.parent() {
                fs::create_dir_all(parent)?;
            }
            File::create(&profile_file_path)?;
        }

        let content = fs::read_to_string(&profile_file_path)?;
        if content.contains(zoi_bin_str) {
            println!("Zoi bin directory is already in your shell's config.");
            return Ok(());
        }

        let mut file = OpenOptions::new().append(true).open(&profile_file_path)?;

        file.write_all(cmd_to_write.as_bytes())?;

        println!(
            "{} Zoi bin directory has been added to your PATH in '{}'.",
            "Success:".green(),
            profile_file_path.display()
        );
        println!(
            "Please restart your shell or run `source {}` for the changes to take effect.",
            profile_file_path.display()
        );
    }

    #[cfg(windows)]
    {
        use winreg::RegKey;
        use winreg::enums::*;

        let zoi_bin_path_str = zoi_bin_dir
            .to_str()
            .ok_or_else(|| anyhow!("Invalid path string"))?;

        let (root, subkey, scope_name) = if scope == Scope::System {
            if !is_admin() {
                return Err(anyhow!(
                    "Administrator privileges required to modify system PATH."
                ));
            }
            (
                HKEY_LOCAL_MACHINE,
                "System\\CurrentControlSet\\Control\\Session Manager\\Environment",
                "system",
            )
        } else {
            (HKEY_CURRENT_USER, "Environment", "user")
        };

        let key = RegKey::predef(root);
        let env = key.open_subkey_with_flags(subkey, KEY_READ | KEY_WRITE)?;
        let current_path: String = env.get_value("Path")?;

        if current_path
            .split(';')
            .any(|p| p.eq_ignore_ascii_case(zoi_bin_path_str))
        {
            println!("Zoi bin directory is already in your PATH.");
            return Ok(());
        }

        let new_path = if current_path.is_empty() {
            zoi_bin_path_str.to_string()
        } else {
            format!("{};{}", current_path, zoi_bin_path_str)
        };
        env.set_value("Path", &new_path)?;

        println!(
            "{} Zoi bin directory has been added to your {} PATH environment variable.",
            "Success:".green(),
            scope_name
        );
        println!(
            "Please restart your shell or log out and log back in for the changes to take effect."
        );
    }

    Ok(())
}

pub fn check_path() {
    if let Some(home) = home::home_dir() {
        let zoi_bin_dir = crate::pkg::sysroot::apply_sysroot(home.join(".zoi/pkgs/bin"));
        if !zoi_bin_dir.exists() {
            return;
        }
    } else {
        return;
    }

    let command_output = if cfg!(target_os = "windows") {
        Command::new("pwsh")
            .arg("-Command")
            .arg("echo $env:Path")
            .output()
    } else {
        Command::new("bash").arg("-c").arg("echo $PATH").output()
    };

    let is_in_path = match command_output {
        Ok(output) => {
            if output.status.success() {
                let path_var = String::from_utf8_lossy(&output.stdout);
                path_var.contains(".zoi/pkgs/bin")
            } else {
                false
            }
        }
        Err(_) => false,
    };

    if !is_in_path {
        eprintln!(
            "Please run 'zoi shell <shell>' or add it to your PATH manually for commands to be available."
        );
    }
}

pub fn get_platform() -> anyhow::Result<String> {
    let os = match std::env::consts::OS {
        "linux" => "linux",
        "macos" | "darwin" => "macos",
        "windows" => "windows",
        "freebsd" => "freebsd",
        "openbsd" => "openbsd",
        unsupported_os => return Err(anyhow!("Unsupported operating system: {}", unsupported_os)),
    };

    let arch = match std::env::consts::ARCH {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        unsupported_arch => return Err(anyhow!("Unsupported architecture: {}", unsupported_arch)),
    };

    Ok(format!("{}-{}", os, arch))
}

pub fn get_all_available_package_managers() -> Vec<String> {
    let mut managers = Vec::new();
    let all_possible_managers = [
        "apt",
        "pacman",
        "yay",
        "paru",
        "pikaur",
        "trizen",
        "dnf",
        "yum",
        "zypper",
        "portage",
        "apk",
        "snap",
        "flatpak",
        "nix",
        "brew",
        "port",
        "scoop",
        "choco",
        "winget",
        "pkg",
        "pkg_add",
        "xbps-install",
        "eopkg",
        "guix",
        "mas",
    ];

    for manager in &all_possible_managers {
        if command_exists(manager) {
            managers.push(manager.to_string());
        }
    }
    managers.sort();
    managers.dedup();
    managers
}

pub fn build_blocking_http_client(timeout_secs: u64) -> anyhow::Result<reqwest::blocking::Client> {
    if crate::pkg::offline::is_offline() {
        return Err(anyhow!(
            "Cannot create HTTP client: Zoi is in offline mode."
        ));
    }
    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(timeout_secs))
        .build()?;
    Ok(client)
}

pub fn retry_backoff_sleep(attempt: u32) {
    let base_ms = 500u64.saturating_mul(1u64 << (attempt.saturating_sub(1)));
    let jitter = (std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or(Duration::from_secs(0))
        .subsec_millis()
        % 200) as u64;
    let sleep_ms = (base_ms + jitter).min(8000);
    std::thread::sleep(Duration::from_millis(sleep_ms));
}

pub fn check_license(license: &str) {
    if license.is_empty() {
        println!(
            "{}",
            "Warning: Package does not have a license specified.".yellow()
        );
        return;
    }

    if license.eq_ignore_ascii_case("Proprietary") {
        println!(
            "{}",
            "Warning: Package is using a proprietary license.".red()
        );
        return;
    }

    if license.eq_ignore_ascii_case("Unkown") {
        println!("{}", "Warning: Package license is unkown.".red());
        return;
    }

    match spdx::Expression::parse(license) {
        Ok(expr) => {
            if !expr.evaluate(|req| match req.license {
                spdx::LicenseItem::Spdx { id, .. } => id.is_osi_approved(),
                spdx::LicenseItem::Other { .. } => false,
            }) {
                println!(
                    "{}{}{}",
                    "Warning: License '".yellow(),
                    license.yellow().bold(),
                    "' is not an OSI approved license.".yellow()
                );
            }
        }
        Err(_) => {
            println!(
                "{}{}{}",
                "Warning: Could not parse license expression '".yellow(),
                license.yellow().bold(),
                "' It may not be a valid SPDX identifier.".yellow()
            );
        }
    }
}

#[derive(serde::Deserialize)]
struct PackageForCompletion {
    description: Option<String>,
}

pub struct PackageCompletion {
    pub display: String,
    pub repo: String,
    pub description: String,
}

pub fn get_all_packages_for_completion() -> Vec<PackageCompletion> {
    let db_root = if let Ok(path) = crate::pkg::resolve::get_db_root() {
        path
    } else {
        return Vec::new();
    };

    let active_repos = if let Ok(config) = crate::pkg::config::read_config() {
        config.repos
    } else {
        return Vec::new();
    };

    if !db_root.exists() {
        return Vec::new();
    }

    let mut packages = Vec::new();
    for repo_name in &active_repos {
        let repo_path = db_root.join(repo_name);
        if !repo_path.is_dir() {
            continue;
        }
        for entry in WalkDir::new(&repo_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_dir())
        {
            let pkg_name = entry.file_name().to_string_lossy();
            let pkg_file_path = entry.path().join(format!("{}.pkg.lua", pkg_name));

            if pkg_file_path.is_file() {
                let pkg_info: anyhow::Result<PackageForCompletion> = (|| -> anyhow::Result<_> {
                    let pkg = crate::pkg::lua::parser::parse_lua_package(
                        pkg_file_path.to_str().unwrap(),
                        None,
                        true,
                    )?;
                    Ok(PackageForCompletion {
                        description: Some(pkg.description),
                    })
                })();

                let description = match pkg_info {
                    Ok(pi) => pi.description.unwrap_or_default(),
                    Err(_) => String::new(),
                };

                let relative_path = entry.path().strip_prefix(&db_root).unwrap();
                let full_pkg_id =
                    format!("@{}", relative_path.to_string_lossy().replace('\\', "/"));

                packages.push(PackageCompletion {
                    display: full_pkg_id,
                    repo: repo_name.clone(),
                    description,
                });
            }
        }
    }
    packages.sort_by(|a, b| a.display.cmp(&b.display));
    packages
}

pub fn get_current_shell() -> Option<Shell> {
    if cfg!(windows) {
        return Some(Shell::PowerShell);
    }

    if let Ok(shell_path) = std::env::var("SHELL") {
        let shell_name = Path::new(&shell_path).file_name()?.to_str()?;
        match shell_name {
            "bash" => Some(Shell::Bash),
            "zsh" => Some(Shell::Zsh),
            "fish" => Some(Shell::Fish),
            "elvish" => Some(Shell::Elvish),
            "pwsh" => Some(Shell::PowerShell),
            _ => None,
        }
    } else {
        None
    }
}