-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1158 lines (979 loc) · 38.2 KB
/
main.cpp
File metadata and controls
1158 lines (979 loc) · 38.2 KB
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
#include "config/conf.hpp"
#include "store/store.hpp"
#include "store/entry.hpp"
#include "lock/lockfile.hpp"
#include "env/shell.hpp"
#include "gc/gc.hpp"
#include "system/differ.hpp"
#include "system/applier.hpp"
#include "system/system_conf.hpp"
#include "snap/snap.hpp"
#include "util/process.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <optional>
#include <cstring>
#include <fstream>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
// Extern declaration for the daemon main function
extern "C" void run_daemon();
namespace {
void print_version() {
std::cout << "astral-env " << config::version() << "\n";
}
void print_help(const char* prog) {
std::cout << "Usage: " << prog << " <command> [options]\n"
<< "\n"
<< "Environment Commands:\n"
<< " init Scaffold astral-env.stars in current directory\n"
<< " lock [--update [pkg]] Generate/update lockfile from .stars\n"
<< " build [--force] Build environment from lockfile\n"
<< " shell [--dir <d>] Enter interactive environment shell\n"
<< " run <cmd...> Run command inside the environment\n"
<< " status Show what's installed vs missing\n"
<< "\n"
<< "System Commands:\n"
<< " system init Create /etc/astral/env/env.stars\n"
<< " system init-user <u> Create per-user config + dotfiles directory\n"
<< " system diff Show pending changes\n"
<< " system apply Apply changes (--dry-run, --yes, --user, --global-only)\n"
<< " system rollback Roll back (--list, --to <id>)\n"
<< " system check Validate all .stars files\n"
<< "\n"
<< "Snapshot Commands:\n"
<< " snap <path> Snapshot a file or directory\n"
<< " snap list [path] List snapshots (optionally filtered by path)\n"
<< " snap restore <id> Restore a snapshot (--dest <path> for alternate location)\n"
<< " snap prune Prune old snapshots (--keep-last N, --older-than Nd)\n"
<< "\n"
<< "Store Commands:\n"
<< " store list List all store entries\n"
<< " store size Show total store disk usage\n"
<< " gc [--dry-run] Garbage collect unused entries (--max-age <days>)\n"
<< "\n"
<< "Daemon Commands:\n"
<< " snapd start Start snapshot daemon (enables at boot)\n"
<< " snapd stop Stop snapshot daemon\n"
<< " snapd restart Restart snapshot daemon\n"
<< " snapd status Show daemon status\n"
<< "\n"
<< "Global Options:\n"
<< " -v, --verbose Verbose output\n"
<< " -q, --quiet Quiet output\n"
<< " -V, --version Show version\n"
<< " -h, --help Show this help\n";
}
int cmd_init(const std::vector<std::string>&) {
auto stars_path = std::filesystem::path("astral-env.stars");
if (std::filesystem::exists(stars_path)) {
std::cout << "astral-env.stars already exists, not overwriting.\n";
return 0;
}
std::string content = R"($ENV.Version = "3"
$ENV.Metadata: {
Name = "my-project"
Description = "Dev environment"
};
$ENV.Packages: {
# Add packages here, e.g.:
# python >= 3.11
# nodejs >= 20.0
};
$ENV.Vars: {
# DEBUG = "true"
};
$ENV.Shell: {
# echo "entering environment"
};
)";
std::ofstream f(stars_path);
f << content;
std::cout << "Created astral-env.stars\n";
return 0;
}
int cmd_lock(const std::vector<std::string>& args) {
bool update_all = false;
std::vector<std::string> update_packages;
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--update") {
if (i + 1 < args.size() && args[i+1] != "--update") {
update_packages.push_back(args[++i]);
} else {
update_all = true;
}
}
}
auto stars_path = std::filesystem::path("astral-env.stars");
auto lock_path = std::filesystem::path("astral-env.lock");
auto repo_bin = std::filesystem::path("/usr/share/astral/bin");
try {
auto lock = lock::generate(stars_path, repo_bin, update_all, update_packages);
lock::write(lock, lock_path);
std::cout << "Wrote " << lock_path << "\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_build(const std::vector<std::string>& args) {
bool force = false;
for (const auto& arg : args) {
if (arg == "--force") force = true;
}
auto lock_path = std::filesystem::path("astral-env.lock");
auto store_root = std::filesystem::path("/astral-env/store");
if (!std::filesystem::exists(lock_path)) {
std::cerr << "Error: no astral-env.lock found.\n";
std::cerr << " Run 'astral-env lock' first to generate it.\n";
return 1;
}
try {
auto lock = lock::read(lock_path);
for (const auto& entry : lock.entries) {
// Now we can use lock::LockEntry directly since it's the same as store::LockEntry
auto result = store::install(entry, store_root, 4, force);
if (!result) {
std::cerr << "Failed to install " << entry.name << "\n";
return 1;
}
}
std::cout << "Build complete.\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_shell(const std::vector<std::string>& args) {
std::filesystem::path dir = std::filesystem::current_path();
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--dir" && i + 1 < args.size()) {
dir = args[++i];
}
}
auto lock_path = dir / "astral-env.lock";
auto stars_path = dir / "astral-env.stars";
if (!std::filesystem::exists(lock_path)) {
std::cerr << "Error: no astral-env.lock found in " << dir << "\n";
return 1;
}
try {
env::enter_shell(lock_path, stars_path);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_run(const std::vector<std::string>& args) {
if (args.empty()) {
std::cerr << "Error: no command specified\n";
return 1;
}
auto lock_path = std::filesystem::path("astral-env.lock");
auto stars_path = std::filesystem::path("astral-env.stars");
if (!std::filesystem::exists(lock_path)) {
std::cerr << "Error: no astral-env.lock found.\n";
return 1;
}
try {
return env::run_command(lock_path, stars_path, args);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
int cmd_status(const std::vector<std::string>&) {
auto lock_path = std::filesystem::path("astral-env.lock");
auto store_root = std::filesystem::path("/astral-env/store");
if (!std::filesystem::exists(lock_path)) {
std::cout << "No lockfile found.\n";
return 0;
}
auto lock = lock::read(lock_path);
std::cout << "astral-env status\n";
std::cout << "Lock file: " << lock_path << "\n";
std::cout << "Packages:\n";
for (const auto& entry : lock.entries) {
std::cout << " [";
// FIX: Check build_kind first - system installs don't go to store
if (entry.build_kind == lock::BuildKind::System) {
// System packages are installed via astral -S, not the store
std::cout << "✓] " << entry.name;
if (!entry.version.empty()) {
std::cout << " " << entry.version;
}
std::cout << " (system install via astral)\n";
} else {
bool present = store::entry_exists(entry.store_path);
std::cout << (present ? "✓" : "✗") << "] " << entry.name << " " << entry.version;
if (!present) {
std::cout << " (store: MISSING — run astral-env build)";
} else {
std::cout << " (store: present)";
}
std::cout << "\n";
}
}
return 0;
}
int cmd_gc(const std::vector<std::string>& args) {
bool dry_run = false; // Default: actually collect (opposite of before)
int gc_keep_days = 30;
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--dry-run") {
dry_run = true;
} else if (args[i] == "--max-age" && i + 1 < args.size()) {
gc_keep_days = std::stoi(args[++i]);
}
}
auto store_root = std::filesystem::path("/astral-env/store");
// Search multiple roots for lockfiles - not just /home
std::vector<std::filesystem::path> search_roots;
const char* home = std::getenv("HOME");
if (home) search_roots.emplace_back(home);
search_roots.emplace_back("/home");
search_roots.emplace_back("/root");
// Future: read from /astral-env/registry
// Collect lockfiles from all search roots
std::vector<std::filesystem::path> all_lockfiles;
for (const auto& root : search_roots) {
auto lockfiles = gc::find_lockfiles(root);
all_lockfiles.insert(all_lockfiles.end(), lockfiles.begin(), lockfiles.end());
}
try {
// FIX: Use multiple search roots, not just one
auto candidates = gc::find_candidates_multi(store_root, all_lockfiles, gc_keep_days);
if (candidates.empty()) {
std::cout << "No GC candidates found.\n";
return 0;
}
uint64_t total_size = 0;
for (const auto& c : candidates) {
total_size += c.size;
}
std::cout << "Candidates for collection:\n";
for (const auto& c : candidates) {
std::cout << " " << c.path.filename().string() << " - "
<< (c.size / 1024 / 1024) << " MB\n";
}
std::cout << "Total: " << (total_size / 1024 / 1024) << " MB\n";
if (dry_run) {
std::cout << "Run without --dry-run to collect these entries.\n";
} else {
auto freed = gc::collect(store_root, candidates);
std::cout << "Freed " << (freed / 1024 / 1024) << " MB\n";
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_snap(const std::vector<std::string>& args) {
if (args.empty()) {
std::cerr << "Usage: astral-env snap <path>\n";
return 1;
}
std::filesystem::path path = args[0];
if (!std::filesystem::exists(path)) {
std::cerr << "Error: Path does not exist: " << path << "\n";
return 1;
}
try {
auto result = snap::create(path, snap::SNAP_STORE, snap::SNAP_INDEX, "manual");
std::cout << "Created snapshot: " << result.snapshot_id << "\n";
std::cout << " Original: " << (result.original_bytes / 1024) << " KB\n";
std::cout << " Compressed: " << (result.compressed_bytes / 1024) << " KB\n";
if (result.deduped) {
std::cout << " (deduplicated - content unchanged)\n";
}
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
int cmd_snap_list(const std::vector<std::string>& args) {
std::optional<std::filesystem::path> filter_path;
if (!args.empty()) {
filter_path = args[0];
}
try {
auto snapshots = snap::list(snap::SNAP_INDEX, filter_path);
if (snapshots.empty()) {
std::cout << "No snapshots found.\n";
return 0;
}
if (filter_path) {
std::cout << "Snapshots for: " << *filter_path << "\n";
} else {
std::cout << "All snapshots:\n";
}
for (const auto& s : snapshots) {
std::cout << " " << s.id << " " << s.path.string() << " (" << s.reason << ")\n";
}
std::cout << "Total: " << snapshots.size() << " snapshots\n";
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
int cmd_snap_restore(const std::vector<std::string>& args) {
if (args.empty()) {
std::cerr << "Usage: astral-env snap restore <id> [--dest <path>]\n";
return 1;
}
std::string snap_id = args[0];
std::optional<std::filesystem::path> dest;
// Check for --dest
for (size_t i = 1; i < args.size(); i++) {
if (args[i] == "--dest" && i + 1 < args.size()) {
dest = args[i + 1];
break;
}
}
try {
snap::restore(snap_id, snap::SNAP_INDEX, snap::SNAP_STORE, dest);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
int cmd_snap_prune(const std::vector<std::string>&) {
try {
int pruned = snap::prune(snap::SNAP_INDEX, snap::SNAP_STORE, 30, 5);
std::cout << "Pruned " << pruned << " snapshots\n";
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
int cmd_store_list(const std::vector<std::string>&) {
auto store_root = std::filesystem::path("/astral-env/store");
try {
auto entries = store::list_store_entries(store_root);
std::cout << "Store entries:\n";
for (const auto& entry : entries) {
std::cout << " " << entry.filename().string() << "\n";
}
std::cout << "Total: " << entries.size() << " entries\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_store_size(const std::vector<std::string>&) {
auto store_root = std::filesystem::path("/astral-env/store");
try {
auto entries = store::list_store_entries(store_root);
auto size = store::store_size(store_root);
std::cout << "Store: " << entries.size() << " entries, "
<< (size / 1024 / 1024) << " MB total\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_system_diff(const std::vector<std::string>& args) {
bool global_only = false;
std::string target_user;
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--global-only") global_only = true;
else if (args[i] == "--user" && i + 1 < args.size()) target_user = args[++i];
}
auto env_path = std::filesystem::path("/etc/astral/env/env.stars");
auto env_dir = std::filesystem::path("/etc/astral/env");
if (!std::filesystem::exists(env_path)) {
std::cerr << "Error: " << env_path << " not found.\n";
return 1;
}
try {
auto config = astral_sys::parse_system_config(env_path);
// FIX: Load user configs
std::vector<std::pair<std::string, astral_sys::UserConfig>> user_configs;
if (!global_only) {
user_configs = astral_sys::load_all_user_configs(env_dir);
// Filter to target user if specified
if (!target_user.empty()) {
std::vector<std::pair<std::string, astral_sys::UserConfig>> filtered;
for (auto& uc : user_configs) {
if (uc.first == target_user) {
filtered.push_back(uc);
break;
}
}
user_configs = filtered;
}
}
auto diffs = astral_sys::diff_system(config, user_configs);
astral_sys::print_diff(diffs);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_system_apply(const std::vector<std::string>& args) {
bool dry_run = false;
bool prune = false;
bool yes = false;
bool global_only = false;
std::string target_user;
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--dry-run") dry_run = true;
else if (args[i] == "--prune") prune = true;
else if (args[i] == "--yes") yes = true;
else if (args[i] == "--user" && i + 1 < args.size()) target_user = args[++i];
else if (args[i] == "--global-only") global_only = true;
}
auto env_path = std::filesystem::path("/etc/astral/env/env.stars");
auto env_dir = std::filesystem::path("/etc/astral/env");
if (!std::filesystem::exists(env_path)) {
std::cerr << "Error: " << env_path << " not found.\n";
std::cerr << "Run 'astral-env system init' first.\n";
return 1;
}
try {
// Parse global config
auto config = astral_sys::parse_system_config(env_path);
// Load user configs
std::vector<std::pair<std::string, astral_sys::UserConfig>> user_configs;
if (!global_only) {
user_configs = astral_sys::load_all_user_configs(env_dir);
// Filter to target user if specified
if (!target_user.empty()) {
std::vector<std::pair<std::string, astral_sys::UserConfig>> filtered;
for (auto& uc : user_configs) {
if (uc.first == target_user) {
filtered.push_back(uc);
break;
}
}
user_configs = filtered;
}
}
// Compute diff
auto diffs = astral_sys::diff_system(config, user_configs);
// Show diff
std::cout << "astral-env system apply\n";
std::cout << "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
if (diffs.empty()) {
std::cout << "No changes needed.\n";
return 0;
}
for (const auto& d : diffs) {
// Convert action enum to string
std::string action_str;
switch (d.action) {
case astral_sys::DiffAction::Install: action_str = "+"; break;
case astral_sys::DiffAction::Remove: action_str = "-"; break;
case astral_sys::DiffAction::Enable: action_str = "~"; break;
case astral_sys::DiffAction::Disable: action_str = "~"; break;
case astral_sys::DiffAction::Change: action_str = "~"; break;
case astral_sys::DiffAction::Symlink: action_str = "+"; break;
case astral_sys::DiffAction::Unlink: action_str = "-"; break;
case astral_sys::DiffAction::Conflict: action_str = "!"; break;
default: action_str = "?"; break;
}
std::cout << " [" << action_str << "] " << d.name << "\n";
if (!d.target.empty()) {
std::cout << " -> " << d.target << "\n";
}
}
std::cout << "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
// Ask for confirmation unless --yes
if (!yes) {
std::cout << "Apply these changes? [y/N] ";
std::string response;
std::getline(std::cin, response);
if (response != "y" && response != "Y") {
std::cout << "Aborted.\n";
return 0;
}
}
if (dry_run) {
std::cout << "Dry run — no changes made.\n";
return 0;
}
int applied = astral_sys::apply_diff(diffs, false, prune, yes);
std::cout << "Applied " << applied << " change(s).\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_system_rollback(const std::vector<std::string>& args) {
std::string snapshot_id;
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "--list") {
auto snapshots = astral_sys::list_snapshots();
std::cout << "Available snapshots:\n";
for (const auto& s : snapshots) {
std::cout << " " << s << "\n";
}
return 0;
} else if (args[i] == "--to" && i + 1 < args.size()) {
snapshot_id = args[++i];
}
}
try {
// Check if rollback is actually implemented
if (!astral_sys::rollback_implemented()) {
std::cerr << "WARNING: rollback is not yet fully implemented.\n";
std::cerr << "Only partial restoration is supported.\n";
return 1;
}
if (astral_sys::rollback(snapshot_id)) {
std::cout << "Rollback complete.\n";
} else {
std::cerr << "Rollback failed.\n";
return 1;
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}
int cmd_system_init(const std::vector<std::string>&) {
auto env_dir = std::filesystem::path("/etc/astral/env");
auto env_path = env_dir / "env.stars";
// Create directory if it doesn't exist with permissions writable by group (2775)
if (!std::filesystem::exists(env_dir)) {
std::filesystem::create_directories(env_dir);
// Set permissions: rwxrwsr-x (2775) - owner and group can read/write/execute, others can read/execute
// Also setgid bit so new files inherit group ownership
std::filesystem::permissions(env_dir,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_all |
std::filesystem::perms::others_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::set_gid,
std::filesystem::perm_options::replace);
std::cout << "Created " << env_dir << "\n";
}
if (std::filesystem::exists(env_path)) {
std::cout << env_path << " already exists, not overwriting.\n";
return 0;
}
// Create default env.stars
std::string content = R"($ENV.Version = "3"
# $ENV.System - optional, uncomment if you want to manage hostname/timezone
# $ENV.System: {
# hostname = "my-machine"
# timezone = "UTC"
# };
$ENV.Packages: {
# Add system packages here, e.g.:
# neovim
# git
# htop
};
# $ENV.Services - optional, format: service = "enabled" | "disabled" | "masked"
# $ENV.Services: {
# sshd = "enabled"
# };
)";
std::ofstream f(env_path);
f << content;
// Set file permissions: rw-rw-r-- (664) - owner and group can read/write
std::filesystem::permissions(env_path,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_write |
std::filesystem::perms::others_read);
std::cout << "Created " << env_path << "\n";
// Also create the dotfiles subdirectory with group write permissions
auto dotfiles_dir = env_dir / "dotfiles";
if (!std::filesystem::exists(dotfiles_dir)) {
std::filesystem::create_directories(dotfiles_dir);
std::filesystem::permissions(dotfiles_dir,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_all |
std::filesystem::perms::others_exec |
std::filesystem::perms::others_read);
std::cout << "Created " << dotfiles_dir << "\n";
}
return 0;
}
int cmd_system_init_user(const std::vector<std::string>& args) {
// Get the username - either from argument or from environment
std::string username;
if (!args.empty()) {
username = args[0];
} else {
// Try to get username from environment
const char* user = std::getenv("USER");
if (!user) {
user = std::getenv("USERNAME");
}
if (!user) {
// Try to get from whoami
auto result = util::run("whoami", {});
username = result.stdout_output;
if (!username.empty() && username.back() == '\n') {
username.pop_back();
}
} else {
username = user;
}
}
if (username.empty()) {
std::cerr << "Error: Could not determine username. Please specify as argument.\n";
return 1;
}
auto env_dir = std::filesystem::path("/etc/astral/env");
auto user_path = env_dir / (username + ".stars");
// Ensure env directory exists
if (!std::filesystem::exists(env_dir)) {
std::filesystem::create_directories(env_dir);
std::filesystem::permissions(env_dir,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_all |
std::filesystem::perms::others_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::set_gid,
std::filesystem::perm_options::replace);
std::cout << "Created " << env_dir << "\n";
}
if (std::filesystem::exists(user_path)) {
std::cout << user_path << " already exists, not overwriting.\n";
return 0;
}
// Create user-specific config
std::string content = R"($ENV.Version = "3"
$ENV.User: {
name = ")" + username + R"(
shell = "/bin/bash"
# groups = "wheel audio video" # optional, space-separated
};
# $ENV.Packages - user-specific packages (installed via Astral)
# $ENV.Packages: {
# firefox
# thunderbird
# };
# $ENV.Dotfiles - symlink dotfiles from /etc/astral/env/dotfiles/<user>/
# Format: "/home/)" + username + R"(/.bashrc" = "bashrc"
# $ENV.Dotfiles: {
# "/home/)" + username + R"(/.bashrc" = "bashrc"
# "/home/)" + username + R"(/.gitconfig" = "gitconfig"
# };
# $ENV.Vars - environment variables for this user
# $ENV.Vars: {
# EDITOR = "vim"
# BROWSER = "firefox"
# };
)";
std::ofstream f(user_path);
f << content;
// Set ownership to the user and permissions 664
// Get uid/gid for the user
auto result = util::run("id", {username});
if (result.exit_code == 0) {
// Parse uid/gid from id command output
std::string output = result.stdout_output;
size_t uid_pos = output.find("uid=");
size_t gid_pos = output.find("gid=");
if (uid_pos != std::string::npos && gid_pos != std::string::npos) {
std::string uid_str = output.substr(uid_pos + 4);
std::string gid_str = output.substr(gid_pos + 4);
// Extract numbers
uid_str = uid_str.substr(0, uid_str.find('('));
gid_str = gid_str.substr(0, gid_str.find('('));
// Change ownership
auto chown_result = util::run("chown", {username + ":" + username, user_path.string()});
(void)chown_result; // Ignore errors - might not have permission
}
}
// Set permissions: rw-rw-r-- (664)
std::filesystem::permissions(user_path,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_write |
std::filesystem::perms::others_read);
std::cout << "Created " << user_path << "\n";
// Also create user's dotfiles directory
auto dotfiles_user_dir = env_dir / "dotfiles" / username;
if (!std::filesystem::exists(dotfiles_user_dir)) {
std::filesystem::create_directories(dotfiles_user_dir);
// Try to set ownership
auto chown_result = util::run("chown", {username + ":" + username, dotfiles_user_dir.string()});
(void)chown_result;
std::filesystem::permissions(dotfiles_user_dir,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_all |
std::filesystem::perms::others_exec |
std::filesystem::perms::others_read);
std::cout << "Created " << dotfiles_user_dir << "\n";
}
std::cout << "\nUser configuration created for '" << username << "'.\n";
std::cout << "Edit " << user_path << " to add packages, dotfiles, and variables.\n";
return 0;
}
int cmd_system_check(const std::vector<std::string>&) {
auto env_dir = std::filesystem::path("/etc/astral/env");
if (!std::filesystem::exists(env_dir)) {
std::cout << "No env directory found.\n";
return 0;
}
int errors = 0;
for (const auto& entry : std::filesystem::directory_iterator(env_dir)) {
if (!entry.is_regular_file() || entry.path().extension() != ".stars") {
continue;
}
try {
// FIX: Actually parse the file to validate it, not just check if it opens
auto filename = entry.path().filename().string();
if (filename == "env.stars") {
// Try to parse as system config
auto config = astral_sys::parse_system_config(entry.path());
std::cout << "✓ " << filename << " — valid\n";
} else {
// Try to parse as user config
auto config = astral_sys::parse_user_config(entry.path());
std::cout << "✓ " << filename << " — valid\n";
}
} catch (const std::exception& e) {
std::cout << "✗ " << entry.path().filename().string()
<< " — ERROR: " << e.what() << "\n";
errors++;
}
}
if (errors > 0) {
std::cout << "\n" << errors << " error(s) found.\n";
return 1;
}
std::cout << "\nAll config files are valid.\n";
return 0;
}
int cmd_snapd_start(const std::vector<std::string>&) {
// Check if already running
auto result = util::run("pidof", {"astral-env-snapd"});
if (result.exit_code == 0 && !result.stdout_output.empty()) {
std::cerr << "Error: astral-env-snapd is already running (PID: " << result.stdout_output << ")\n";
return 1;
}
// Fork and run the daemon
pid_t pid = fork();
if (pid < 0) {
std::cerr << "Error: fork failed\n";
return 1;
}
if (pid == 0) {
// Child process: run the daemon
// Close standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Open /dev/null for stdin
open("/dev/null", O_RDONLY);
// Redirect stdout and stderr to a log file
int log_fd = open("/var/log/astral-env-snapd.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
if (log_fd >= 0) {
dup2(log_fd, STDOUT_FILENO);
dup2(log_fd, STDERR_FILENO);
close(log_fd);
}
execlp("astral-env-snapd", "astral-env-snapd", nullptr);
_exit(1);
}
// Parent process
std::cout << "Started astral-env-snapd (PID: " << pid << ")\n";
return 0;
}
int cmd_snapd_stop(const std::vector<std::string>&) {
auto result = util::run("pidof", {"astral-env-snapd"});
if (result.exit_code != 0 || result.stdout_output.empty()) {
std::cerr << "Error: astral-env-snapd is not running\n";
return 1;
}
// Extract PID
std::string pid_str = result.stdout_output;
// Take first PID if multiple
size_t space = pid_str.find(' ');
if (space != std::string::npos) {
pid_str = pid_str.substr(0, space);
}
// Send SIGTERM
int pid = std::stoi(pid_str);
if (kill(pid, SIGTERM) != 0) {
std::cerr << "Error: failed to stop daemon\n";
return 1;
}
std::cout << "Stopped astral-env-snapd (PID: " << pid << ")\n";
return 0;
}
int cmd_snapd_restart(const std::vector<std::string>&) {
cmd_snapd_stop({});
return cmd_snapd_start({});
}
int cmd_snapd_status(const std::vector<std::string>&) {
auto result = util::run("pidof", {"astral-env-snapd"});
if (result.exit_code == 0 && !result.stdout_output.empty()) {
std::cout << "astral-env-snapd is running (PID: " << result.stdout_output << ")\n";
} else {
std::cout << "astral-env-snapd is not running\n";
}
return 0;
}
} // anonymous namespace
int main(int argc, char* argv[]) {
// Check if we are the snapd binary
std::string prog_name = argv[0];
size_t pos = prog_name.rfind('/');