nex-pkg 0.11.0

Package manager UX for nix-darwin + homebrew
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
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use console::style;

use crate::discover::{self, Platform};
use crate::output;

/// Run `nex init` — bootstrap nix (+ homebrew on macOS) and a system config.
pub fn run(from: Option<String>, dry_run: bool) -> Result<()> {
    let platform = discover::detect_platform();

    println!();
    println!("  {} — first-time setup", style("nex init").bold());
    println!();

    let config_label = match platform {
        Platform::Darwin => "nix-darwin",
        Platform::Linux => "NixOS",
    };

    // 0. Check if a nix config already exists
    if let Ok(existing) = crate::discover::find_repo() {
        eprintln!(
            "  {} found existing {} config at {}",
            style("!").yellow().bold(),
            config_label,
            style(existing.display()).cyan()
        );
        eprintln!();

        let adopt = dialoguer::Confirm::new()
            .with_prompt(format!(
                "  Use {} instead of creating a new config?",
                existing.display()
            ))
            .default(true)
            .interact()?;

        if adopt {
            let hostname = crate::discover::hostname()?;
            let config_dir = crate::config::config_dir()?;

            if !dry_run {
                std::fs::create_dir_all(&config_dir)?;
                let config_content = format!(
                    "repo_path = \"{}\"\nhostname = \"{}\"\n",
                    existing.display(),
                    hostname
                );
                std::fs::write(config_dir.join("config.toml"), &config_content)?;
            }

            ok("config repo", &existing.display().to_string());
            ok(
                "config",
                &config_dir.join("config.toml").display().to_string(),
            );
            eprintln!();
            eprintln!(
                "  nex is now using {}. Run {} to activate.",
                style(existing.display()).cyan(),
                style("nex switch").bold()
            );
            eprintln!();
            return Ok(());
        }
        eprintln!();
    }

    // 1. Check / install Nix
    let has_nix = check_cmd("nix");
    if has_nix {
        ok("nix", &capture_version("nix", &["--version"]));
    } else if dry_run {
        output::dry_run("would install Determinate Nix");
    } else {
        install_nix()?;
    }

    // 2. Check / install Homebrew (macOS only)
    let _has_brew = if platform == Platform::Darwin {
        let has_brew = check_cmd("brew");
        if has_brew {
            ok("homebrew", &capture_version("brew", &["--version"]));
        } else if dry_run {
            output::dry_run("would install Homebrew");
        } else {
            install_homebrew()?;
        }
        has_brew || !dry_run
    } else {
        false
    };

    // 3. Verify git is available (required for nix flakes)
    //    On a fresh Mac, the Homebrew installer installs Xcode Command Line Tools
    //    which provides git. If something went wrong, catch it here before we try
    //    to scaffold a git repo.
    if !dry_run {
        let has_git = Command::new("git")
            .args(["--version"])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if has_git {
            ok("git", &capture_version("git", &["--version"]));
        } else {
            eprintln!();
            eprintln!(
                "  {} git is not available — nix flakes require a git repository",
                style("!").red().bold(),
            );
            eprintln!();
            if platform == Platform::Darwin {
                eprintln!("  Install Xcode Command Line Tools, then re-run nex init:");
                eprintln!("    {}", style("xcode-select --install").cyan());
            } else {
                eprintln!("  Install git, then re-run nex init:");
                eprintln!(
                    "    {}",
                    style("sudo apt install git  # or your distro's equivalent").cyan()
                );
            }
            eprintln!();
            bail!("git is required but not found");
        }
    }

    // 4. Detect hostname
    let hostname = crate::discover::hostname()?;
    ok("hostname", &hostname);

    // 5. Set up the nix-darwin config repo
    let repo_path = match from {
        Some(url) => clone_repo(&url, dry_run)?,
        None => scaffold_repo(&hostname, dry_run)?,
    };

    ok("config repo", &repo_path.display().to_string());

    // 6. Write nex config so future commands find the repo
    let config_dir = crate::config::config_dir()?;

    if !dry_run {
        std::fs::create_dir_all(&config_dir)?;
        let config_content = format!(
            "repo_path = \"{}\"\nhostname = \"{}\"\n",
            repo_path.display(),
            hostname
        );
        std::fs::write(config_dir.join("config.toml"), config_content)?;
    }
    ok(
        "config",
        &config_dir.join("config.toml").display().to_string(),
    );

    // 7. First build + switch
    if dry_run {
        let rebuild_cmd = match platform {
            Platform::Darwin => "darwin-rebuild switch",
            Platform::Linux => "nixos-rebuild switch",
        };
        output::dry_run(&format!("would run {rebuild_cmd}"));
        println!();
        return Ok(());
    }

    // Ensure git tree is clean so nix doesn't refuse to build.
    // scaffold_repo already does git init + add + commit + identity setup,
    // but clone_repo or an adopted repo may have dirty state.
    let _ = Command::new("git")
        .args(["add", "-A"])
        .current_dir(&repo_path)
        .output();
    let commit_status = Command::new("git")
        .args(["commit", "-m", "nex init"])
        .current_dir(&repo_path)
        .output();
    if let Err(e) = commit_status {
        output::error(&format!(
            "git commit failed: {e} — nix build may warn about dirty tree"
        ));
    }

    println!();
    output::status("building (this takes a few minutes on first run)...");

    // First build to verify it works
    let nix = crate::exec::find_nix();
    let build_attr = match platform {
        Platform::Darwin => format!(".#darwinConfigurations.{hostname}.system"),
        Platform::Linux => format!(".#nixosConfigurations.{hostname}.config.system.build.toplevel"),
    };
    let build_status = Command::new(&nix)
        .args(["build", &build_attr, "--show-trace"])
        .current_dir(&repo_path)
        .status()
        .context("failed to run nix build")?;

    if !build_status.success() {
        bail!(
            "nix build failed — check the config at {}\n\
             You can fix issues and re-run: nex init",
            repo_path.display()
        );
    }

    // Check for existing brew packages BEFORE activating, because
    // homebrew.onActivation.cleanup = "zap" will remove anything not in the
    // nix-managed brew lists. Run nex adopt to capture them first.
    if platform == Platform::Darwin {
        let has_brew_packages = crate::exec::brew_available()
            && (!crate::exec::brew_leaves().unwrap_or_default().is_empty()
                || !crate::exec::brew_list_casks()
                    .unwrap_or_default()
                    .is_empty());

        if has_brew_packages {
            println!();
            eprintln!(
                "  {} existing brew packages detected — adopting before activation",
                style("!").yellow().bold()
            );
            eprintln!(
                "  This prevents {} from removing your installed packages.",
                style("cleanup = \"zap\"").dim()
            );
            println!();
            // Run nex adopt to capture existing packages into the nix config
            let adopt_status =
                Command::new(std::env::current_exe().unwrap_or_else(|_| "nex".into()))
                    .args(["adopt"])
                    .current_dir(&repo_path)
                    .status();
            if let Ok(status) = adopt_status {
                if status.success() {
                    // Re-stage and commit the adopted packages
                    let _ = Command::new("git")
                        .args(["add", "-A"])
                        .current_dir(&repo_path)
                        .output();
                    let _ = Command::new("git")
                        .args(["commit", "-m", "nex adopt: capture existing brew packages"])
                        .current_dir(&repo_path)
                        .output();
                    // Rebuild with the adopted packages
                    output::status("rebuilding with adopted packages...");
                    let _ = Command::new(&nix)
                        .args(["build", &build_attr, "--show-trace"])
                        .current_dir(&repo_path)
                        .status();
                }
            }
        }
    }

    output::status("activating (sudo required)...");

    // nix-darwin refuses to overwrite files in /etc on first run.
    // Move them out of the way so activation can proceed. (macOS only)
    let etc_files = ["/etc/shells", "/etc/nix/nix.conf"];
    if platform == Platform::Darwin {
        for path in &etc_files {
            let p = Path::new(path);
            let backup = format!("{path}.before-nix-darwin");
            if p.exists() && !Path::new(&backup).exists() {
                info("backing up", &format!("{path}{backup}"));
                let _ = Command::new("sudo").args(["mv", path, &backup]).status();
            }
        }
    }

    // Ensure home-manager profile dirs exist before first switch
    crate::exec::ensure_profile_dirs();

    // Use the system rebuild from the build result, via sudo
    let switch_ok = match platform {
        Platform::Darwin => {
            let result_path = repo_path.join("result/sw/bin/darwin-rebuild");
            if result_path.exists() {
                Command::new("sudo")
                    .args([
                        result_path.to_string_lossy().as_ref(),
                        "switch",
                        "--flake",
                        &format!(".#{hostname}"),
                    ])
                    .current_dir(&repo_path)
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false)
            } else {
                Command::new("sudo")
                    .args([
                        "darwin-rebuild",
                        "switch",
                        "--flake",
                        &format!(".#{hostname}"),
                    ])
                    .current_dir(&repo_path)
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false)
            }
        }
        Platform::Linux => Command::new("sudo")
            .args([
                "nixos-rebuild",
                "switch",
                "--flake",
                &format!(".#{hostname}"),
            ])
            .current_dir(&repo_path)
            .status()
            .map(|s| s.success())
            .unwrap_or(false),
    };

    if !switch_ok {
        // Restore /etc files that were moved (macOS only)
        if platform == Platform::Darwin {
            for path in &etc_files {
                let backup = format!("{path}.before-nix-darwin");
                if Path::new(&backup).exists() {
                    let _ = Command::new("sudo").args(["mv", &backup, path]).status();
                    info("restored", path);
                }
            }
        }
        println!();
        output::error("automatic activation failed — run manually:");
        match platform {
            Platform::Darwin => println!(
                "  cd {} && sudo ./result/sw/bin/darwin-rebuild switch --flake .#{}",
                repo_path.display(),
                hostname
            ),
            Platform::Linux => println!(
                "  cd {} && sudo nixos-rebuild switch --flake .#{}",
                repo_path.display(),
                hostname
            ),
        }
        println!();
        println!("  After that, open a new terminal and nex is ready.");
        return Ok(());
    }

    println!();
    println!("  {} Setup complete.", style("").green().bold());
    println!();
    println!("  Next steps:");
    println!(
        "  {}  Install a package",
        style("  nex install htop").cyan()
    );
    println!("  {}  Show all packages", style("  nex list").cyan());
    println!();

    Ok(())
}

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

fn capture_version(cmd: &str, args: &[&str]) -> String {
    Command::new(cmd)
        .args(args)
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().lines().next().unwrap_or("").to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

fn ok(label: &str, detail: &str) {
    eprintln!(
        "  {} {}: {}",
        style("").green().bold(),
        label,
        style(detail).dim()
    );
}

fn info(label: &str, detail: &str) {
    eprintln!("  {} {}: {}", style("").cyan(), label, style(detail).dim());
}

fn install_nix() -> Result<()> {
    output::status("installing Determinate Nix...");
    let status = Command::new("sh")
        .args([
            "-c",
            "curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install",
        ])
        .status()
        .context("failed to run nix installer")?;

    if !status.success() {
        output::error("shell installer failed — trying macOS .pkg installer...");
        install_nix_pkg()?;
    }

    source_nix_env();
    Ok(())
}

fn install_nix_pkg() -> Result<()> {
    let tmp_dir = std::env::temp_dir();
    let pkg_path = tmp_dir.join("determinate-nix.pkg");

    output::status("downloading Determinate Nix .pkg...");
    let dl = Command::new("curl")
        .args([
            "-fsSL",
            "https://install.determinate.systems/determinate-pkg/stable/Universal",
            "-o",
            &pkg_path.display().to_string(),
        ])
        .status()
        .context("failed to download .pkg installer")?;

    if !dl.success() {
        bail!(
            "failed to download Determinate Nix .pkg\n\
             Install Nix manually: https://determinate.systems/nix-installer\n\
             Then re-run: nex init"
        );
    }

    output::status("installing .pkg (sudo required)...");
    let install = Command::new("sudo")
        .args([
            "installer",
            "-pkg",
            &pkg_path.display().to_string(),
            "-target",
            "/",
        ])
        .status()
        .context("failed to run .pkg installer")?;

    // Clean up
    let _ = std::fs::remove_file(&pkg_path);

    if !install.success() {
        bail!(
            "Determinate Nix .pkg installation failed\n\
             Install Nix manually: https://determinate.systems/nix-installer\n\
             Then re-run: nex init"
        );
    }

    Ok(())
}

fn source_nix_env() {
    // Add well-known nix paths so subsequent commands can find the nix binary.
    // We can't source nix-daemon.sh from Rust, but the known paths are stable.
    let current_path = std::env::var("PATH").unwrap_or_default();
    std::env::set_var(
        "PATH",
        format!("/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin:{current_path}"),
    );
}

fn install_homebrew() -> Result<()> {
    output::status("installing Homebrew...");
    let status = Command::new("sh")
        .args([
            "-c",
            "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"",
        ])
        .status()
        .context("failed to run Homebrew installer")?;

    if !status.success() {
        bail!("Homebrew installation failed");
    }

    // Add homebrew to PATH for this process
    let current_path = std::env::var("PATH").unwrap_or_default();
    std::env::set_var("PATH", format!("/opt/homebrew/bin:{current_path}"));

    Ok(())
}

fn clone_repo(url: &str, dry_run: bool) -> Result<PathBuf> {
    let home = dirs::home_dir().context("no home directory")?;
    let repo_path = home.join(discover::default_repo_name());

    if repo_path.exists() {
        return Ok(repo_path);
    }

    if dry_run {
        output::dry_run(&format!("would clone {url} to {}", repo_path.display()));
        return Ok(repo_path);
    }

    output::status(&format!("cloning {url}..."));
    let status = Command::new("git")
        .args(["clone", url, &repo_path.display().to_string()])
        .status()
        .context("failed to run git clone")?;

    if !status.success() {
        bail!("git clone failed");
    }

    Ok(repo_path)
}

fn scaffold_repo(hostname: &str, dry_run: bool) -> Result<PathBuf> {
    let platform = discover::detect_platform();
    let home = dirs::home_dir().context("no home directory")?;
    let repo_path = home.join(discover::default_repo_name());

    if repo_path.exists() {
        return Ok(repo_path);
    }

    if dry_run {
        output::dry_run(&format!(
            "would scaffold nix config at {}",
            repo_path.display()
        ));
        return Ok(repo_path);
    }

    let config_label = match platform {
        Platform::Darwin => "nix-darwin",
        Platform::Linux => "NixOS",
    };
    output::status(&format!("scaffolding {config_label} config..."));

    // Create directory structure
    let host_dir = repo_path.join(format!("nix/hosts/{hostname}"));
    let home_dir = repo_path.join("nix/modules/home");
    let lib_dir = repo_path.join("nix/lib");

    std::fs::create_dir_all(&host_dir)?;
    std::fs::create_dir_all(&home_dir)?;
    std::fs::create_dir_all(&lib_dir)?;

    let user = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
    let system = discover::detect_system();

    match platform {
        Platform::Darwin => {
            let darwin_dir = repo_path.join("nix/modules/darwin");
            std::fs::create_dir_all(&darwin_dir)?;
            scaffold_darwin(
                &repo_path,
                &host_dir,
                &darwin_dir,
                &lib_dir,
                hostname,
                system,
                &user,
            )?;
        }
        Platform::Linux => {
            let nixos_dir = repo_path.join("nix/modules/nixos");
            std::fs::create_dir_all(&nixos_dir)?;
            scaffold_nixos(
                &repo_path, &host_dir, &nixos_dir, &lib_dir, hostname, system, &user,
            )?;
        }
    }

    // home/base.nix — shared between platforms
    let home_directory = match platform {
        Platform::Darwin => "/Users/${username}",
        Platform::Linux => "/home/${username}",
    };
    std::fs::write(
        home_dir.join("base.nix"),
        format!(
            "{{ pkgs, username, ... }}:\n\
             \n\
             {{\n\
             \x20 home = {{\n\
             \x20   username = username;\n\
             \x20   homeDirectory = \"{home_directory}\";\n\
             \x20   stateVersion = \"25.05\";\n\
             \x20 }};\n\
             \n\
             \x20 home.sessionPath = [ \"$HOME/.local/bin\" ];\n\
             \n\
             \x20 home.packages = with pkgs; [\n\
             \x20   git\n\
             \x20   vim\n\
             \x20 ];\n\
             \n\
             \x20 # Enable bash so home-manager generates .bashrc and .bash_profile.\n\
             \x20 # Without this, the login shell works but has no managed config.\n\
             \x20 programs.bash.enable = true;\n\
             \x20 programs.home-manager.enable = true;\n\
             }}\n"
        ),
    )?;

    // Init git repo — nix flakes require files to be tracked by git
    let git_init = Command::new("git")
        .args(["init"])
        .current_dir(&repo_path)
        .output()
        .context("failed to run git init")?;

    if !git_init.status.success() {
        bail!(
            "git init failed in {} — nix flakes require a git repository.\n\
             Check that git is installed: git --version",
            repo_path.display()
        );
    }

    let _ = Command::new("git")
        .args(["branch", "-m", "main"])
        .current_dir(&repo_path)
        .output();

    let git_add = Command::new("git")
        .args(["add", "-A"])
        .current_dir(&repo_path)
        .output()
        .context("failed to run git add")?;

    if !git_add.status.success() {
        bail!(
            "git add failed in {} — nix flakes require files to be tracked.\n\
             Run manually: cd {} && git add -A && git commit -m 'init'",
            repo_path.display(),
            repo_path.display()
        );
    }

    // Set fallback git identity if not configured (fresh systems with no .gitconfig)
    let has_name = Command::new("git")
        .args(["config", "user.name"])
        .current_dir(&repo_path)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if !has_name {
        let user = std::env::var("USER").unwrap_or_else(|_| "nex".to_string());
        let _ = Command::new("git")
            .args(["config", "user.name", &user])
            .current_dir(&repo_path)
            .output();
        let _ = Command::new("git")
            .args(["config", "user.email", &format!("{user}@localhost")])
            .current_dir(&repo_path)
            .output();
    }

    let _ = Command::new("git")
        .args(["commit", "-m", "init: nex scaffold"])
        .current_dir(&repo_path)
        .output();

    Ok(repo_path)
}

// ── Darwin (macOS) scaffolding ───────────────────────────────────────────

fn scaffold_darwin(
    repo_path: &Path,
    host_dir: &Path,
    darwin_dir: &Path,
    lib_dir: &Path,
    hostname: &str,
    system: &str,
    user: &str,
) -> Result<()> {
    // flake.nix
    std::fs::write(
        repo_path.join("flake.nix"),
        format!(
            r#"{{
  description = "macOS workstation management — nix-darwin + home-manager";

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
    nix-darwin = {{
      url = "github:LnL7/nix-darwin";
      inputs.nixpkgs.follows = "nixpkgs";
    }};
    home-manager = {{
      url = "github:nix-community/home-manager";
      inputs.nixpkgs.follows = "nixpkgs";
    }};
    mac-app-util.url = "github:hraban/mac-app-util";
  }};

  outputs = {{ self, nixpkgs, nix-darwin, home-manager, mac-app-util }}:
    let
      mkHost = import ./nix/lib/mkHost.nix {{ inherit nixpkgs nix-darwin home-manager mac-app-util; }};
    in
    {{
      darwinConfigurations."{hostname}" = mkHost {{
        hostname = "{hostname}";
        system = "{system}";
        username = "{user}";
        hostModule = ./nix/hosts/{hostname};
      }};
    }};
}}
"#
        ),
    )?;

    // mkHost.nix
    std::fs::write(
        lib_dir.join("mkHost.nix"),
        r#"{ nixpkgs, nix-darwin, home-manager, mac-app-util }:

{ hostname, system, username, hostModule }:

nix-darwin.lib.darwinSystem {
  inherit system;
  specialArgs = { inherit hostname username; };
  modules = [
    hostModule
    mac-app-util.darwinModules.default
    home-manager.darwinModules.home-manager
    {
      home-manager = {
        useGlobalPkgs = true;
        useUserPackages = true;
        backupFileExtension = "backup";
        extraSpecialArgs = { inherit hostname username; };
        sharedModules = [
          mac-app-util.homeManagerModules.default
        ];
      };
    }
  ];
}
"#,
    )?;

    // Host default.nix
    std::fs::write(
        host_dir.join("default.nix"),
        r#"{ pkgs, hostname, username, ... }:

{
  imports = [
    ../../modules/darwin/base.nix
    ../../modules/darwin/homebrew.nix
  ];

  networking.hostName = hostname;
  networking.localHostName = hostname;

  home-manager.users.${username} = import ../../modules/home/base.nix;

  system.stateVersion = 6;
}
"#,
    )?;

    // darwin/base.nix
    let has_determinate =
        check_cmd("determinate-nixd") || Path::new("/nix/var/determinate").exists();

    let nix_block = if has_determinate {
        "  # Determinate Nix manages the daemon — disable nix-darwin's nix management\n  \
         nix.enable = false;\n"
    } else {
        "  nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];\n  \
         nix.package = pkgs.nix;\n"
    };

    std::fs::write(
        darwin_dir.join("base.nix"),
        format!(
            r#"{{ pkgs, username, ... }}:

{{
{nix_block}
  nixpkgs.config.allowUnfree = true;

  system.primaryUser = username;

  environment.shells = [ pkgs.bash ];
  users.users.${{username}} = {{
    shell = pkgs.bash;
    home = "/Users/${{username}}";
  }};

  security.pam.services.sudo_local.touchIdAuth = true;
}}
"#
        ),
    )?;

    // darwin/homebrew.nix
    std::fs::write(
        darwin_dir.join("homebrew.nix"),
        r#"{ ... }:

{
  homebrew = {
    enable = true;
    onActivation = {
      autoUpdate = true;
      upgrade = true;
      cleanup = "zap";
    };
    brews = [
    ];
    casks = [
    ];
  };
}
"#,
    )?;

    Ok(())
}

// ── NixOS (Linux) scaffolding ────────────────────────────────────────────

fn scaffold_nixos(
    repo_path: &Path,
    host_dir: &Path,
    nixos_dir: &Path,
    lib_dir: &Path,
    hostname: &str,
    system: &str,
    user: &str,
) -> Result<()> {
    // flake.nix
    std::fs::write(
        repo_path.join("flake.nix"),
        format!(
            r#"{{
  description = "NixOS workstation management — NixOS + home-manager";

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    home-manager = {{
      url = "github:nix-community/home-manager";
      inputs.nixpkgs.follows = "nixpkgs";
    }};
  }};

  outputs = {{ self, nixpkgs, home-manager }}:
    let
      mkHost = import ./nix/lib/mkHost.nix {{ inherit nixpkgs home-manager; }};
    in
    {{
      nixosConfigurations."{hostname}" = mkHost {{
        hostname = "{hostname}";
        system = "{system}";
        username = "{user}";
        hostModule = ./nix/hosts/{hostname};
      }};
    }};
}}
"#
        ),
    )?;

    // mkHost.nix
    std::fs::write(
        lib_dir.join("mkHost.nix"),
        r#"{ nixpkgs, home-manager }:

{ hostname, system, username, hostModule }:

nixpkgs.lib.nixosSystem {
  inherit system;
  specialArgs = { inherit hostname username; };
  modules = [
    hostModule
    home-manager.nixosModules.home-manager
    {
      home-manager = {
        useGlobalPkgs = true;
        useUserPackages = true;
        backupFileExtension = "backup";
        extraSpecialArgs = { inherit hostname username; };
      };
    }
  ];
}
"#,
    )?;

    // Host default.nix
    std::fs::write(
        host_dir.join("default.nix"),
        format!(
            r#"{{ pkgs, hostname, username, ... }}:

{{
  imports = [
    ../../modules/nixos/base.nix
    ./hardware-configuration.nix
  ];

  networking.hostName = hostname;

  home-manager.users.${{username}} = import ../../modules/home/base.nix;

  system.stateVersion = "25.05";
}}
"#
        ),
    )?;

    // Generate hardware-configuration.nix if nixos-generate-config is available
    if check_cmd("nixos-generate-config") {
        let _ = Command::new("nixos-generate-config")
            .args(["--show-hardware-config"])
            .output()
            .map(|output| {
                if output.status.success() {
                    let _ =
                        std::fs::write(host_dir.join("hardware-configuration.nix"), &output.stdout);
                }
            });
    }
    // If hardware-configuration.nix doesn't exist, create a placeholder
    if !host_dir.join("hardware-configuration.nix").exists() {
        std::fs::write(
            host_dir.join("hardware-configuration.nix"),
            format!(
                r#"# Auto-generated hardware configuration.
# Replace with output of: nixos-generate-config --show-hardware-config
{{ config, lib, pkgs, modulesPath, ... }}:

{{
  imports = [
    (modulesPath + "/installer/scan/not-detected.nix")
  ];

  boot.loader.systemd-boot.enable = true;
  boot.loader.efi.canTouchEfiVariables = true;
}}
"#
            ),
        )?;
    }

    // nixos/base.nix
    let has_determinate =
        check_cmd("determinate-nixd") || Path::new("/nix/var/determinate").exists();

    let nix_block = if has_determinate {
        "  # Determinate Nix manages the daemon\n  \
         nix.enable = false;\n"
    } else {
        "  nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];\n"
    };

    std::fs::write(
        nixos_dir.join("base.nix"),
        format!(
            r#"{{ pkgs, username, ... }}:

{{
{nix_block}
  nixpkgs.config.allowUnfree = true;

  users.users.${{username}} = {{
    isNormalUser = true;
    extraGroups = [ "wheel" "networkmanager" "video" "audio" ];
    shell = pkgs.bash;
  }};

  environment.shells = [ pkgs.bash ];

  # Networking
  networking.networkmanager.enable = true;

  # Sound
  services.pipewire = {{
    enable = true;
    alsa.enable = true;
    pulse.enable = true;
  }};

  # Timezone — override in host config if needed
  time.timeZone = "America/New_York";

  # Locale
  i18n.defaultLocale = "en_US.UTF-8";
}}
"#
        ),
    )?;

    Ok(())
}