zoi-rs 1.13.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
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
use crate::{
    pkg::{config, db, pgp, types},
    utils,
};
use anyhow::{Result, anyhow};
use colored::*;
use git2::{
    FetchOptions, RemoteCallbacks, Repository, ResetType,
    build::{CheckoutBuilder, RepoBuilder},
};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use rayon::prelude::*;
use serde_yaml;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tempfile::Builder;
use walkdir::WalkDir;

fn refresh_registry_db(
    registry_handle: &str,
    registry_path: &Path,
    sync_files: bool,
    m: Option<&MultiProgress>,
    verbose: bool,
    pb: Option<&ProgressBar>,
) -> Result<()> {
    if verbose {
        let msg = format!(
            "Refreshing metadata database for {}...",
            registry_handle.cyan()
        );
        if let Some(m_ref) = m {
            let _ = m_ref.println(&msg);
        } else {
            println!("{}", msg);
        }
    }

    let mut conn = db::open_connection(registry_handle)?;
    db::clear_registry(&conn)?;

    let mut pkg_files = Vec::new();
    let mut sec_files = Vec::new();
    for entry in WalkDir::new(registry_path)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        if entry.file_type().is_file() {
            let name = entry.file_name().to_string_lossy();
            if name.ends_with(".pkg.lua") {
                pkg_files.push(entry.path().to_path_buf());
            } else if name.ends_with(".sec.yaml") {
                sec_files.push(entry.path().to_path_buf());
            }
        }
    }

    let repo_config = config::read_repo_config(registry_path).ok();
    let _advisory_prefix = repo_config
        .as_ref()
        .and_then(|rc| rc.advisory_prefix.clone());
    let platform = utils::get_platform().unwrap_or_default();

    let client = if sync_files {
        crate::utils::get_http_client().ok()
    } else {
        None
    };

    if let Some(p) = pb {
        p.set_length(pkg_files.len() as u64);
        p.set_position(0);
        p.set_message(format!("Indexing {}", registry_handle.cyan()));
    }

    let parsed_results: Vec<(types::Package, PathBuf, Option<Vec<String>>)> = pkg_files
        .par_iter()
        .filter_map(|path| {
            if let Some(p) = pb {
                p.inc(1);
            }
            let path_str = path.to_string_lossy();
            if let Ok(mut pkg) = crate::pkg::lua::parser::parse_lua_package(&path_str, None, true) {
                if pkg.repo.is_empty()
                    && let Ok(rel_path) = path.strip_prefix(registry_path)
                    && let Some(parent) = rel_path.parent()
                {
                    let mut repo_path = parent.to_string_lossy().to_string().replace('\\', "/");
                    let pkg_name_suffix = format!("/{}", pkg.name);
                    if repo_path.ends_with(&pkg_name_suffix) {
                        repo_path =
                            repo_path[..repo_path.len() - pkg_name_suffix.len()].to_string();
                    } else if repo_path == pkg.name {
                        repo_path = String::new();
                    }
                    pkg.repo = repo_path;
                }

                let mut file_list = None;
                if sync_files
                    && let Some(c) = &client
                    && let Some(rc) = &repo_config
                    && let Some(pkg_link) = rc.pkg.iter().find(|p| p.link_type == "main")
                    && let Some(files_url_template) = &pkg_link.files
                {
                    let version = pkg.version.clone().unwrap_or_else(|| "latest".to_string());
                    let files_url = crate::pkg::install::util::resolve_url_placeholders(
                        files_url_template,
                        &pkg.name,
                        &pkg.repo,
                        &version,
                        &platform,
                    );

                    if let Ok(response) = c.get(&files_url).send()
                        && response.status().is_success()
                        && let Ok(content) = response.text()
                    {
                        file_list = Some(
                            content
                                .lines()
                                .map(|l| l.trim().to_string())
                                .filter(|l| !l.is_empty())
                                .collect(),
                        );
                    }
                }

                Some((pkg, path.clone(), file_list))
            } else {
                None
            }
        })
        .collect();

    let parsed_advisories: Vec<(types::Advisory, String)> = sec_files
        .par_iter()
        .filter_map(|path| {
            if let Ok(content) = fs::read_to_string(path)
                && let Ok(advisory) = serde_yaml::from_str::<types::Advisory>(&content)
                && let Ok(rel_path) = path.strip_prefix(registry_path)
                && let Some(parent) = rel_path.parent()
            {
                let repo_path = parent.to_string_lossy().to_string().replace('\\', "/");
                return Some((advisory, repo_path));
            }
            None
        })
        .collect();

    let tx = conn.transaction()?;

    for (pkg, _path, file_list) in parsed_results {
        let pkg_id = db::update_package(&tx, &pkg, registry_handle, None, None, None)?;

        if let Some(subs) = &pkg.sub_packages {
            for sub in subs {
                let _ = db::update_package(&tx, &pkg, registry_handle, None, Some(sub), None);
            }
        }

        if let Some(list) = file_list {
            let _ = db::index_package_files(&tx, pkg_id, &list);
        }
    }

    for (advisory, repo) in parsed_advisories {
        let _ = db::update_advisory(&tx, &advisory, &repo, registry_handle);
    }

    tx.commit()?;

    if let Some(p) = pb {
        p.finish_and_clear();
    }

    Ok(())
}

fn verify_registry_signature(
    repo_path: &Path,
    authorities: &[String],
    verbose: bool,
) -> Result<()> {
    if authorities.is_empty() {
        return Ok(());
    }

    if verbose {
        println!("Verifying registry signature...");
    }

    let repo = Repository::open(repo_path)
        .map_err(|e| anyhow!("Failed to open registry repository: {}", e))?;
    let head = repo
        .head()
        .map_err(|e| anyhow!("Failed to get repository HEAD: {}", e))?;
    let target = head
        .target()
        .ok_or_else(|| anyhow!("HEAD is not a direct reference"))?;
    let commit = repo
        .find_commit(target)
        .map_err(|e| anyhow!("Failed to find HEAD commit: {}", e))?;

    let (sig, data) = repo
        .extract_signature(&commit.id(), None)
        .map_err(|_| anyhow!("Registry commit is not signed. Sync aborted for security."))?;

    let sig_bytes = &*sig;
    let data_bytes = &*data;

    let trusted_certs = pgp::get_certs_by_name_or_fingerprint(authorities)?;

    let mut verified = false;
    for cert in trusted_certs {
        if pgp::verify_detached_signature_raw(data_bytes, sig_bytes, &cert).is_ok() {
            verified = true;
            break;
        }
    }

    if verified {
        if verbose {
            println!("{}", "Registry signature verified successfully.".green());
        }
        Ok(())
    } else {
        Err(anyhow!(
            "Registry commit was signed but not by any authorized authority. Sync aborted."
        ))
    }
}

fn get_db_path() -> Result<PathBuf> {
    let home_dir = home::home_dir().ok_or_else(|| anyhow!("Could not find home directory."))?;
    Ok(crate::pkg::sysroot::apply_sysroot(
        home_dir.join(".zoi").join("pkgs").join("db"),
    ))
}

fn get_git_root() -> Result<PathBuf> {
    let home_dir = home::home_dir().ok_or_else(|| anyhow!("Could not find home directory."))?;
    Ok(crate::pkg::sysroot::apply_sysroot(
        home_dir.join(".zoi").join("pkgs").join("git"),
    ))
}

fn sync_git_repos(verbose: bool) -> Result<()> {
    if crate::pkg::offline::is_offline() {
        println!(
            "\n{}",
            "Zoi is offline. Skipping sync of external git repositories.".yellow()
        );
        return Ok(());
    }
    let git_root = get_git_root()?;
    if !git_root.exists() {
        return Ok(());
    }

    if verbose {
        println!("\n{}", "Syncing external git repositories...".green());
    }

    let config = config::read_config()?;
    let configured_git_repos_names: HashSet<String> = config
        .git_repos
        .iter()
        .map(|url| {
            url.trim_end_matches('/')
                .split('/')
                .next_back()
                .unwrap_or_default()
                .trim_end_matches(".git")
                .to_string()
        })
        .collect();

    for entry in fs::read_dir(git_root)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() && path.join(".git").exists() {
            let Some(repo_name_os) = path.file_name() else {
                continue;
            };
            let repo_name = repo_name_os.to_string_lossy();

            if !configured_git_repos_names.contains(repo_name.as_ref()) {
                println!(
                    "Removing untracked git repository '{}'...",
                    repo_name.yellow()
                );
                fs::remove_dir_all(&path)?;
                continue;
            }

            println!("Pulling changes for '{}'...", repo_name.cyan());

            let mut cmd = Command::new("git");
            cmd.arg("-C").arg(&path).arg("pull");

            if verbose {
                let status = cmd
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit())
                    .status()?;
                if !status.success() {
                    eprintln!(
                        "{}: Failed to pull changes for '{}'.",
                        "Warning".yellow(),
                        repo_name
                    );
                }
            } else {
                let output = cmd.output()?;
                if !output.status.success() {
                    eprintln!(
                        "{}: Failed to pull changes for '{}'.",
                        "Warning".yellow(),
                        repo_name
                    );
                    eprintln!("{}", String::from_utf8_lossy(&output.stderr));
                }
            }
        }
    }
    Ok(())
}

fn run_verbose_at_path(db_url: &str, db_path: &Path) -> Result<()> {
    if db_path.exists() {
        let status = Command::new("git")
            .arg("-C")
            .arg(db_path)
            .arg("pull")
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()?;
        if !status.success() {
            return Err(anyhow!(
                "Failed to pull changes from the remote repository."
            ));
        }
    } else {
        let status = Command::new("git")
            .arg("clone")
            .arg("--progress")
            .arg(db_url)
            .arg(db_path)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()?;
        if !status.success() {
            return Err(anyhow!("Failed to clone the package repository."));
        }
    }
    Ok(())
}

fn run_non_verbose_at_path(
    db_url: &str,
    db_path: &Path,
    m: Option<&MultiProgress>,
    pb: Option<&ProgressBar>,
) -> Result<()> {
    let internal_m;
    let m_ref = if let Some(m_ptr) = m {
        m_ptr
    } else {
        internal_m = MultiProgress::new();
        &internal_m
    };

    let fetch_style = ProgressStyle::default_bar()
        .template(
            "{spinner:.green} [{elapsed_precise}] {msg:30.cyan} [{bar:40.cyan/blue}] {pos}/{len} ({percent}%)",
        )?
        .progress_chars("#>-");

    let pb_internal;
    let pb_to_use = if let Some(p) = pb {
        p
    } else {
        pb_internal = m_ref.add(ProgressBar::new(0));
        pb_internal.set_style(fetch_style);
        &pb_internal
    };

    if db_path.exists() {
        let repo = Repository::open(db_path)?;
        let mut remote = repo.find_remote("origin")?;

        let mut cb = RemoteCallbacks::new();
        let pb_clone = pb_to_use.clone();
        cb.transfer_progress(move |stats| {
            if stats.total_deltas() > 0 {
                pb_clone.set_length(stats.total_deltas() as u64);
                pb_clone.set_position(stats.indexed_deltas() as u64);
            }
            true
        });

        let head_symref = repo.find_reference("refs/remotes/origin/HEAD")?;
        let remote_default_ref = head_symref
            .symbolic_target()
            .ok_or_else(|| anyhow!("Remote HEAD is not a symbolic ref"))?;
        let short_branch_name = remote_default_ref
            .strip_prefix("refs/remotes/origin/")
            .ok_or_else(|| anyhow!("Could not determine default branch name from remote HEAD"))?;

        let mut fo = FetchOptions::new();
        fo.remote_callbacks(cb);
        pb_to_use.set_message(format!("Fetching {}", db_url.cyan()));
        remote.fetch(&[short_branch_name], Some(&mut fo), None)?;

        let fetch_head = repo.find_reference("FETCH_HEAD")?;
        let fetch_commit = repo.reference_to_annotated_commit(&fetch_head)?;
        let analysis = repo.merge_analysis(&[&fetch_commit])?;

        if analysis.0.is_up_to_date() {
        } else if analysis.0.is_fast_forward() {
            let refname = format!("refs/heads/{}", short_branch_name);
            let mut reference = repo.find_reference(&refname)?;
            reference.set_target(fetch_commit.id(), "Fast-forwarding")?;
            repo.set_head(&refname)?;

            let mut checkout_builder = CheckoutBuilder::new();
            let pb_clone = pb_to_use.clone();
            checkout_builder.force().progress(move |_path, cur, total| {
                if total > 0 {
                    pb_clone.set_length(total as u64);
                    pb_clone.set_position(cur as u64);
                }
            });

            pb_to_use.set_message(format!("Checkout {}", db_url.cyan()));
            repo.checkout_head(Some(&mut checkout_builder))?;
        } else {
            println!(
                "{}",
                "Cannot fast-forward. Please run `git pull` manually.".yellow()
            );
        }
    } else {
        if let Some(parent) = db_path.parent() {
            fs::create_dir_all(parent)?;
        }

        let mut cb = RemoteCallbacks::new();
        let pb_clone = pb_to_use.clone();
        cb.transfer_progress(move |stats| {
            if stats.total_deltas() > 0 {
                pb_clone.set_length(stats.total_deltas() as u64);
            }
            pb_clone.set_position(stats.indexed_deltas() as u64);
            true
        });

        let mut fo = FetchOptions::new();
        fo.remote_callbacks(cb);

        let mut checkout_builder = CheckoutBuilder::new();
        let pb_clone = pb_to_use.clone();
        checkout_builder.progress(move |_path, cur, total| {
            if total > 0 {
                pb_clone.set_length(total as u64);
            }
            pb_clone.set_position(cur as u64);
        });

        pb_to_use.set_message(format!("Cloning {}", db_url.cyan()));
        RepoBuilder::new()
            .fetch_options(fo)
            .with_checkout(checkout_builder)
            .clone(db_url, db_path)?;
    }

    Ok(())
}

fn try_sync_at_path(
    db_url: &str,
    db_path: &Path,
    verbose: bool,
    m: Option<&MultiProgress>,
    pb: Option<&ProgressBar>,
) -> Result<()> {
    if crate::pkg::offline::is_offline() {
        if db_path.exists() {
            let msg = format!(
                "Zoi is offline. Skipping update for existing registry at {}",
                db_path.display()
            );
            if let Some(m_ref) = m {
                let _ = m_ref.println(&msg);
            } else {
                println!("{}", msg);
            }
            return Ok(());
        } else {
            return Err(anyhow!(
                "Cannot sync registry '{}': Zoi is offline and registry is not cloned.",
                db_url
            ));
        }
    }
    if db_path.exists()
        && let Ok(repo) = Repository::open(db_path)
        && let Ok(remote) = repo.find_remote("origin")
        && let Some(remote_url) = remote.url()
        && remote_url != db_url
    {
        let msg = format!(
            "Registry URL has changed from {}. Removing old database and re-cloning from {}.",
            remote_url.yellow(),
            db_url.cyan()
        );
        if let Some(m_ref) = m {
            m_ref.println(&msg)?;
        } else {
            println!("{}", msg);
        }
        fs::remove_dir_all(db_path)?;
    }

    if verbose {
        run_verbose_at_path(db_url, db_path)
    } else {
        run_non_verbose_at_path(db_url, db_path, m, pb)
    }
}

fn sync_pgp_keys_at_path(db_path: &Path, verbose: bool, pb: Option<&ProgressBar>) -> Result<()> {
    if verbose {
        println!("\n{}", "Syncing PGP keys from repository...".green());
    }
    if !db_path.join("repo.yaml").exists() {
        if verbose {
            println!("{}", "repo.yaml not found, skipping PGP key sync.".yellow());
        }
        return Ok(());
    }

    let repo_config = config::read_repo_config(db_path)?;

    if repo_config.pgp.is_empty() {
        if verbose {
            println!("No PGP keys defined in repo.yaml.");
        }
        return Ok(());
    }

    if let Some(p) = pb {
        p.set_length(repo_config.pgp.len() as u64);
        p.set_position(0);
        p.set_message(format!("PGP Keys {}", repo_config.name.cyan()));
    }

    for key_info in repo_config.pgp {
        let key_source = &key_info.key;
        let key_name = &key_info.name;

        if let Some(p) = pb {
            p.set_message(format!("PGP Key: {}", key_name));
        }

        let result = if key_source.starts_with("http") {
            crate::pkg::pgp::add_key_from_url(key_source, key_name, !verbose)
        } else if key_source.len() == 40 && key_source.chars().all(|c| c.is_ascii_hexdigit()) {
            crate::pkg::pgp::add_key_from_fingerprint(key_source, key_name, !verbose)
        } else {
            Err(anyhow!(
                "Invalid key source '{}': must be a URL or a 40-character fingerprint.",
                key_source
            ))
        };

        if let Err(e) = result {
            let err_msg = format!(
                "{} Failed to import key '{}': {}",
                "Warning:".yellow(),
                key_name,
                e
            );
            if let Some(p) = pb {
                p.println(err_msg);
            } else {
                eprintln!("{}", err_msg);
            }
        }
        if let Some(p) = pb {
            p.inc(1);
        }
    }

    Ok(())
}

fn fetch_handle_by_cloning(url: &str, verbose: bool) -> Result<String> {
    let temp_dir = Builder::new().prefix("zoi-handle-fetch").tempdir()?;
    if verbose {
        println!("Cloning '{}' to fetch handle...", url.cyan());
    }
    let status = std::process::Command::new("git")
        .arg("clone")
        .arg("--depth=1")
        .arg(url)
        .arg(temp_dir.path())
        .stdout(if verbose {
            Stdio::inherit()
        } else {
            Stdio::null()
        })
        .stderr(if verbose {
            Stdio::inherit()
        } else {
            Stdio::null()
        })
        .status()?;

    if !status.success() {
        return Err(anyhow!("git clone failed to fetch handle"));
    }

    let repo_config = config::read_repo_config(temp_dir.path())?;
    Ok(repo_config.name)
}

fn parse_full_repo_url(url: &str) -> Option<(String, String)> {
    let url = url.trim_end_matches(".git").trim_end_matches('/');
    if let Some(path) = url.strip_prefix("https://github.com/") {
        Some(("github".to_string(), path.to_string()))
    } else if let Some(path) = url.strip_prefix("https://gitlab.com/") {
        Some(("gitlab".to_string(), path.to_string()))
    } else {
        url.strip_prefix("https://codeberg.org/")
            .map(|path| ("codeberg".to_string(), path.to_string()))
    }
}

fn fetch_repo_yaml_content(url: &str) -> Result<String> {
    let (provider, repo_path) = parse_full_repo_url(url)
        .ok_or_else(|| anyhow!("Unsupported git provider or URL format for direct fetch."))?;

    let branches = ["main", "master"];
    for branch in &branches {
        let repo_yaml_url = match provider.as_str() {
            "github" => format!(
                "https://raw.githubusercontent.com/{}/{}/repo.yaml",
                repo_path, branch
            ),
            "gitlab" => format!(
                "https://gitlab.com/{}/-/raw/{}/repo.yaml",
                repo_path, branch
            ),
            "codeberg" => format!(
                "https://codeberg.org/{}/raw/branch/{}/repo.yaml",
                repo_path, branch
            ),
            _ => continue,
        };

        let client = crate::utils::get_http_client().ok();
        if let Some(c) = client
            && let Ok(response) = c.get(&repo_yaml_url).send()
            && response.status().is_success()
        {
            println!("Found repo.yaml at: {}", repo_yaml_url.cyan());
            return Ok(response.text()?);
        }
    }

    Err(anyhow!(
        "Could not find 'repo.yaml' in repo '{}' on branches main or master.",
        repo_path
    ))
}

fn fetch_handle_for_url(url: &str, verbose: bool) -> Result<String> {
    if verbose {
        println!(
            "Attempting to fetch handle for '{}' directly...",
            url.cyan()
        );
    }
    match fetch_repo_yaml_content(url) {
        Ok(content) => {
            let repo_config: crate::pkg::types::RepoConfig = serde_yaml::from_str(&content)?;
            if verbose {
                println!("Successfully fetched and parsed repo.yaml.");
            }
            Ok(repo_config.name)
        }
        Err(e) => {
            if verbose {
                println!(
                    "Direct fetch failed: {}. Falling back to cloning repository...",
                    e.to_string().yellow()
                );
            }
            fetch_handle_by_cloning(url, verbose)
        }
    }
}

fn sync_registry(
    mut reg: types::Registry,
    db_root: &Path,
    verbose: bool,
    sync_files: bool,
    m: Option<&MultiProgress>,
) -> Result<(types::Registry, bool)> {
    let mut reg_changed = false;

    let pb = if !verbose && let Some(m_ref) = m {
        let p = m_ref.add(ProgressBar::new(0));
        p.set_style(
            ProgressStyle::default_bar()
                .template(
                    "{spinner:.green} [{elapsed_precise}] {msg:30.cyan} [{bar:40.cyan/blue}] {percent}%",
                )?
                .progress_chars("#>-"),
        );
        p.enable_steady_tick(std::time::Duration::from_millis(120));
        Some(p)
    } else {
        None
    };

    if reg.handle.is_empty() {
        if let Some(p) = &pb {
            p.set_message(format!("Fetching handle for {}", reg.url.cyan()));
        }
        let handle = fetch_handle_for_url(&reg.url, verbose)?;
        reg.handle = handle;
        reg_changed = true;
    }

    let target_dir = db_root.join(&reg.handle);

    let pre_sync_head = match Repository::open(&target_dir) {
        Ok(repo) => match repo.head() {
            Ok(head) => head.target(),
            Err(_) => None,
        },
        Err(_) => None,
    };

    if let Err(e) = try_sync_at_path(&reg.url, &target_dir, verbose, m, pb.as_ref()) {
        let msg = format!("Sync with {} failed: {}", reg.url.yellow(), e);
        if let Some(p) = &pb {
            p.abandon_with_message(msg);
        } else if let Some(m_ref) = m {
            m_ref.println(msg)?;
        } else {
            eprintln!("{}", msg);
        }
    } else {
        if let Some(authorities) = &reg.authorities
            && let Err(e) = verify_registry_signature(&target_dir, authorities, verbose)
        {
            let rollback_msg = if let Some(oid) = pre_sync_head {
                if let Ok(repo) = Repository::open(&target_dir) {
                    if let Ok(object) = repo.find_object(oid, None) {
                        let mut checkout = CheckoutBuilder::new();
                        checkout.force();
                        if repo
                            .reset(&object, ResetType::Hard, Some(&mut checkout))
                            .is_ok()
                        {
                            "Rolled back to previous signed commit.".to_string()
                        } else {
                            "Failed to rollback. Repository may be in an inconsistent state."
                                .to_string()
                        }
                    } else {
                        "Could not find previous HEAD object.".to_string()
                    }
                } else {
                    "Could not open repository for rollback.".to_string()
                }
            } else {
                let _ = fs::remove_dir_all(&target_dir);
                "Removed unsigned clone.".to_string()
            };

            let msg = format!(
                "Security: Registry signature check failed for {}: {}. {}",
                reg.url.red(),
                e,
                rollback_msg.yellow(),
            );
            if let Some(m_ref) = m {
                m_ref.println(&msg)?;
            } else {
                eprintln!("{}", msg);
            }
            return Err(e);
        }

        sync_pgp_keys_at_path(&target_dir, verbose, pb.as_ref())?;

        let mut db_downloaded = false;
        if let Ok(repo_config) = config::read_repo_config(&target_dir)
            && let Some(db_url_template) = &repo_config.db
        {
            let platform = utils::get_platform().unwrap_or_default();
            let db_url = crate::pkg::install::util::resolve_url_placeholders(
                db_url_template,
                "",
                "",
                "",
                &platform,
            );

            if let Ok(db_path) = db::get_db_path(&reg.handle) {
                if let Some(p) = pb.as_ref() {
                    p.set_message("Downloading pre-indexed DB...");
                } else if verbose {
                    println!("Downloading pre-indexed DB from {}...", db_url);
                }
                if let Some(parent) = db_path.parent() {
                    let _ = fs::create_dir_all(parent);
                }

                let temp_db_path = db_path.with_extension("db.tmp");
                if crate::pkg::install::util::download_file_with_progress(
                    &db_url,
                    &temp_db_path,
                    pb.as_ref(),
                    None,
                )
                .is_ok()
                {
                    if fs::rename(&temp_db_path, &db_path).is_ok() {
                        db_downloaded = true;
                        if verbose {
                            println!("Successfully downloaded pre-indexed DB.");
                        }
                    }
                } else {
                    let _ = fs::remove_file(&temp_db_path);
                }
            }
        }

        if !db_downloaded {
            refresh_registry_db(
                &reg.handle,
                &target_dir,
                sync_files,
                m,
                verbose,
                pb.as_ref(),
            )?;
        }

        if let Ok(repo_config) = config::read_repo_config(&target_dir)
            && repo_config.advisory_prefix != reg.advisory_prefix
        {
            reg.advisory_prefix = repo_config.advisory_prefix;
            reg_changed = true;
        }

        if let Some(p) = pb {
            p.finish_with_message(format!("Synced {}", reg.handle.cyan()));
        }
    }

    Ok((reg, reg_changed))
}

pub fn run(verbose: bool, _fallback: bool, no_pm: bool, sync_files: bool) -> Result<()> {
    let merged_config = config::read_config()?;
    if merged_config.protect_db {
        let db_root = get_db_path()?;
        if db_root.exists() {
            if verbose {
                println!("Making package database writable...");
            }
            if let Err(e) = utils::set_path_writable(&db_root) {
                eprintln!("Warning: could not make db writable: {}", e);
            }
        }
    }

    let mut config = config::read_user_config()?;
    let mut needs_config_update = false;

    if config.default_registry.is_none() {
        let merged_config = config::read_config()?;
        if merged_config.default_registry.is_some() {
            config.default_registry = merged_config.default_registry;
        }
    }

    let db_root = get_db_path()?;
    let mut registries_to_sync = Vec::new();

    if let Some(default_reg) = &config.default_registry {
        registries_to_sync.push((default_reg.clone(), true));
    }

    for reg in &config.added_registries {
        registries_to_sync.push((reg.clone(), false));
    }

    if !registries_to_sync.is_empty() {
        println!("{} Syncing registries...", "::".bold().blue());
        let m = if verbose {
            None
        } else {
            Some(MultiProgress::new())
        };

        let results: Vec<Result<(types::Registry, bool, bool)>> = registries_to_sync
            .into_par_iter()
            .map(|(reg, is_default)| {
                let (synced_reg, changed) =
                    sync_registry(reg, &db_root, verbose, sync_files, m.as_ref())?;
                Ok((synced_reg, changed, is_default))
            })
            .collect();

        let mut updated_added_registries = Vec::new();
        for res in results {
            let (reg, changed, is_default) = res?;
            if changed {
                needs_config_update = true;
            }
            if is_default {
                config.default_registry = Some(reg);
            } else {
                updated_added_registries.push(reg);
            }
        }
        config.added_registries = updated_added_registries;
    }

    if !no_pm {
        if verbose {
            println!("\n{}", "Updating system configuration...".green());
        }
        config.native_package_manager = utils::get_native_package_manager();
        config.package_managers = Some(utils::get_all_available_package_managers());
        needs_config_update = true;
        if verbose {
            println!("System configuration updated.");
        }
    }

    if needs_config_update {
        config::write_user_config(&config)?;
    }

    sync_git_repos(verbose)?;

    if merged_config.protect_db {
        let db_root = get_db_path()?;
        if db_root.exists() {
            if verbose {
                println!("Making package database read-only...");
            }
            if let Err(e) = utils::set_path_read_only(&db_root) {
                eprintln!("Warning: could not make db read-only: {}", e);
            }
        }
    }

    Ok(())
}