-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.go
More file actions
1114 lines (935 loc) · 26.1 KB
/
install.go
File metadata and controls
1114 lines (935 loc) · 26.1 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
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"time"
)
var basePackages = []string{
// Base packages to make the system work
"base-devel",
"neovim",
"grub",
"os-prober",
"dhcpcd",
"networkmanager",
"reflector",
"fzf",
"whois",
// Packages for working graphical system with audio
"fish",
"pipewire",
"pipewire-pulse",
"pipewire-jack",
"pipewire-alsa",
"wireplumber",
"sddm",
"hyprland",
"waybar",
"polkit-gnome",
"man",
"mako",
"kitty",
"foot",
"noto-fonts",
"noto-fonts-emoji",
"noto-fonts-cjk",
"nerd-fonts",
"playerctl",
"qt5ct",
"gnome-keyring",
"grim",
"wl-clipboard",
"fcitx5",
"fcitx5-qt",
"fcitx5-gtk",
"fcitx5-mozc",
"fcitx5-configtool",
"qt5-wayland",
"qt6-wayland",
"bluez",
"bluez-utils",
"gifski",
"wf-recorder",
"swayidle",
"htop",
"btop",
"weston",
"xdg-desktop-portal-hyprland",
"qt5-graphicaleffects",
"qt5-quickcontrols2",
"cifs-utils",
"webkit2gtk",
"clang",
"man-pages-de",
"keychain",
"gvfs-mtp",
"gvfs-gphoto2",
"sassc",
"hyfetch",
"flatpak",
"eza",
"bat",
"starship",
"wofi",
"nm-connection-editor",
"blueman",
"ttf-fantasque-sans-mono",
"hyprpaper",
"swappy",
"wev",
}
var archChaoticPackages = []string{
// Packages for working graphical system with audio
"wlogout",
"swaylock-effects",
"dracula-icons-git",
}
var aurPackages = []string{
"samurai-select",
"aur/dracula-gtk-theme",
"aur/dracula-cursors-git",
"backlight_control",
"poweralertd",
}
// Applications can be installed optionally (makes testing faster)
var applicationPackages = []string{
"thunar",
"vscodium",
"xmake",
"biber",
"speech-dispatcher",
"thunar-archive-plugin",
"file-roller",
"openconnect",
"eruption",
"openrgb",
}
var flatpaks = []string{
"com.github.tchx84.Flatseal",
"com.heroicgameslauncher.hgl", // x86_64 only
"net.lutris.Lutris", // x86_64 only
"net.waterfox.waterfox", // x86_64 only
"org.gnome.Evince",
"org.kde.KStyle.Kvantum",
"org.godotengine.Godot",
"org.gnome.eog",
"org.libreoffice.LibreOffice",
"net.ankiweb.Anki",
"com.github.IsmaelMartinez.teams_for_linux",
"com.spotify.Client", // x86_64 only
"com.valvesoftware.Steam", // x86_64 only
"io.mpv.Mpv",
"org.pulseaudio.pavucontrol",
"org.inkscape.Inkscape",
}
var vscodeExtensions = []string{
"jeff-hykin.better-cpp-syntax",
"xaver.clang-format",
"dracula-theme.theme-dracula",
"MS-CEINTL.vscode-language-pack-de",
"MS-CEINTL.vscode-language-pack-ja",
"golang.go",
"vscode-icons-team.vscode-icons",
"streetsidesoftware.code-spell-checker",
"streetsidesoftware.code-spell-checker-german",
"ms-python.python",
"llvm-vs-code-extensions.vscode-clangd",
"vadimcn.vscode-lldb",
"ms-vscode.hexeditor",
"prince781.vala",
// "jeanp413.open-remote-ssh",
"wmaurer.change-case",
"danielgavin.ols",
"yzhang.markdown-all-in-one",
"asvetliakov.vscode-neovim",
"ngtystr.ppm-pgm-viewer-for-vscode",
}
var virtualizationPackages = []string{
"virt-install",
"libvirt",
"qemu-desktop",
"virt-manager",
"dnsmasq",
"distrobox",
"podman",
}
func main() {
// Parse Args
var stage int = 1
var allDefault, userDefault, addUserDirectly bool
userDefault = true
var argUserName, argPassword string
if len(os.Args) > 1 {
args := os.Args[1:]
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "-y" || arg == "--yes" {
allDefault = true
} else if arg == "-u" || arg == "--user" {
userDefault = false
} else if arg == "--name" {
i++
if i == len(args) {
logError("Invalid arguments: username required after \"--name\"")
os.Exit(1)
}
argUserName = args[i]
} else if arg == "--pass" {
i++
if i == len(args) {
logError("Invalid arguments: password required after \"--pass\"")
os.Exit(1)
}
argPassword = args[i]
} else if arg == "--add-user" {
addUserDirectly = true
} else {
stage = parseStage(os.Args[1])
}
}
}
if stage == 1 {
logInfo("Performing Stage 1 ...")
// Enable ParallelDownloads
exeArgs("go", "run", "scripts/replace.go", "/etc/pacman.conf", "#ParallelDownloads = 5", "ParallelDownloads = 5\nILoveCandy")
exe("pacman -Sy --noconfirm --needed " + strings.Join(basePackages, " "))
// set the time zone
if !fileExists("/etc/localtime") {
logInfo("Setting locale ...")
region := promptWithDefault("Europe", allDefault, "Region")
city := promptWithDefault("Vienna", allDefault, "City")
exe(fmt.Sprint("ln -sf /usr/share/zoneinfo/", region, "/", city, " /etc/localtime"))
}
exe("hwclock --systohc")
// Set locale
localesStr := promptWithDefault("de_AT.UTF-8, en_GB.UTF-8", allDefault, "Locale (comma seperated)")
locales := strings.Split(localesStr, ",")
for i := 0; i < len(locales); i++ {
locales[i] = strings.TrimSpace(locales[i])
}
{
localeGen, err := os.Open("/etc/locale.gen")
if err != nil {
logError(err)
os.Exit(1)
}
var localeBuilder strings.Builder
localeScanner := bufio.NewScanner(localeGen)
for localeScanner.Scan() {
line := localeScanner.Text()
var isWanted bool
for _, l := range locales {
if strings.HasPrefix(line, "#"+l) {
isWanted = true
break
}
}
if isWanted {
localeBuilder.WriteString(strings.TrimPrefix(line, "#") + "\n")
} else {
localeBuilder.WriteString(line + "\n")
}
}
localeGen.Close()
localeGen, err = os.Create("/etc/locale.gen")
if err != nil {
logError(err)
os.Exit(1)
}
localeGen.WriteString(localeBuilder.String())
localeGen.Close()
}
exe("locale-gen")
exeAppendFile("echo export LANG=\""+locales[0]+"\"", "/etc/locale.conf")
keymap := promptWithDefault("de", allDefault, "Keymap")
exeAppendFile("echo KEYMAP="+keymap, "/etc/vconsole.conf")
// Boot Loader
if !fileExists("/boot/grub/grub.cfg") {
logInfo("Installing boot loader (grub) ...")
if isUEFI(allDefault) {
exe("grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=grub")
} else {
device := mountedDeviceName()
exe("grub-install --recheck " + device)
}
// Copy over the grub configuration
exe("mkdir -p /etc/default")
exe("cp etc/default/grub /etc/default/")
exe("cp -r etc/default/dracula-grub /etc/default/dracula-grub")
exe("grub-mkconfig -o /boot/grub/grub.cfg")
}
// Set root password to root
passwordPrompt("root", "root", false)
if addUserDirectly {
if !userExists(argUserName) {
addUser(argUserName, argPassword, allDefault, userDefault)
}
}
if !fileExists("/etc/hostname") {
hostName := promptWithDefault("samurai", allDefault, "Hostname")
{
hostNameFile, err := os.Create("/etc/hostname")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
hostNameFile.WriteString(hostName)
hostNameFile.Close()
}
}
if !fileExists("/etc/hosts") {
hostName := readFileTrim("/etc/hostname")
hosts, err := os.Create("/etc/hosts")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
hosts.WriteString("127.0.0.1\tlocalhost\n")
hosts.WriteString("::1\tlocalhost\n")
hosts.WriteString("127.0.1.1\t" + hostName + ".localdomain\t" + hostName + "\n")
}
// Enable every user in the wheel group to use sudo
exeArgs("go", "run", "scripts/replace.go", "/etc/sudoers", "# %wheel ALL=(ALL:ALL) ALL", "%wheel ALL=(ALL:ALL) ALL")
// Show asteriks when typing sudo password
exeArgs("go", "run", "scripts/replace.go", "/etc/sudoers", "# Defaults maxseq = 1000", "Defaults env_reset,pwfeedback")
if !userExists("installer") {
logInfo("Add user installer")
exe("useradd -M -G wheel installer")
pwCrypt, err := exeToStringSilent("mkpasswd installer")
if err == nil {
pwCrypt = strings.TrimSpace(pwCrypt)
exeArgs("usermod", "--password", pwCrypt, "installer")
}
}
curDir, _ := os.Getwd()
exeDontCare("systemctl enable NetworkManager.service")
exeDontCare("systemctl enable bluetooth.service")
// Install chaotic-aur
if !chaoticInstalled() {
logInfo("Installing chaotic-aur repository ...")
exeRetry("pacman-key --recv-key 3056513887B78AEB --keyserver keyserver.ubuntu.com")
exe("pacman-key --lsign-key 3056513887B78AEB")
exe("pacman --noconfirm --needed -U https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-keyring.pkg.tar.zst https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-mirrorlist.pkg.tar.zst")
// Uncomment chaotic-aur
exeArgs("go", "run", "scripts/append.go", "echo [chaotic-aur]", "/etc/pacman.conf")
exeArgs("go", "run", "scripts/append.go", "echo Include = /etc/pacman.d/chaotic-mirrorlist", "/etc/pacman.conf")
} else {
logInfo("Skipping installation of chaotic-aur since it is already installed")
}
// Install packages from chaotic repos and update repositories
logInfo("Installing chaotic packages ...")
exe("pacman -Sy --noconfirm --needed " + strings.Join(archChaoticPackages, " "))
// Installing yay
if !isInstalled("yay") {
installAURPackage("yay-bin")
} else {
logInfo("Skipping installation of yay since it is already installed")
}
// Copy configuration files
logInfo("Copying system configuration files ...")
// Copy non contents of repo
repoEntries, err := os.ReadDir(curDir)
if err != nil {
logError(err)
os.Exit(1)
}
var repoEntriesStr []string
for _, e := range repoEntries {
if e.IsDir() && !(e.Name() == "home" || e.Name() == "scripts" || strings.HasPrefix(e.Name(), ".")) {
repoEntriesStr = append(repoEntriesStr, e.Name())
}
}
exe("cp -r " + strings.Join(repoEntriesStr, " ") + " /")
// Do System Update for multilib
exe("pacman -Syu")
// Copy wireplumber alsa configuration (Fix for broken headset audio)
exe("mkdir -p /etc/wireplumber/main.lua.d")
exe("cp /usr/share/wireplumber/main.lua.d/50-alsa-config.lua /etc/wireplumber/main.lua.d")
exeArgs("go", "run", "scripts/replace.go", "/etc/wireplumber/main.lua.d/50-alsa-config.lua", "--[\"api.alsa.headroom\"] = 0", "[\"api.alsa.headroom\"] = 1024")
logInfo("Clearing pacman cache ...")
exe("pacman -Scc --noconfirm")
rmSamurai := promptWithDefaultYesNo(false, allDefault, "Remove /SamuraiOS")
if rmSamurai {
exe("rm -rf /SamuraiOS")
}
exe("userdel installer")
logInfo("Stage 1 Done")
logInfo("Now reboot into the system and do the following\n\t1. Login as root with pasword root\n\t2. Partion and mount the home partition\n\t3. Add users\n\t4. Execute `systemctl enable --now sddm.service`")
} else if stage == 2 {
// Application Stage
logInfo("Performing Stage 2 ...")
homeDir, _ := os.UserHomeDir()
// Install yay packages
if len(aurPackages) != 0 {
logInfo("Installing AUR packages ...")
exe("yay -S --noconfirm --needed " + strings.Join(aurPackages, " "))
}
logInfo("Done")
installOdinfmt()
installGoPrograms()
exe("sudo pacman -S --noconfirm --needed " + strings.Join(applicationPackages, " "))
exeDontCare("systemctl enable --user eruption-audio-proxy.service")
exeDontCare("systemctl enable --user eruption-fx-proxy.service")
exeDontCare("systemctl enable --user eruption-process-monitor.service")
exeDontCare("sudo systemctl enable --now eruption.service")
for _, ext := range vscodeExtensions {
exe("codium --install-extension " + ext)
}
// Install odin formatter for neoformat
logInfo("Installing neovim formatter for odin ...")
if ok := promptWithDefaultYesNo(true, allDefault, "You need to start neovim at least once before continuing. Did you do this?"); ok {
exe("cp home/ninja/.local/share/nvim/site/pack/pckr/opt/neoformat/autoload/neoformat/formatters/odin.vim " + filepath.Join(homeDir, ".local/share/nvim/site/pack/pckr/opt/neoformat/autoload/neoformat/formatters/"))
}
logInfo("Installing flatpaks ...")
exe("flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo")
exe("flatpak install --assumeyes " + strings.Join(flatpaks, " "))
logInfo("Stage 2 Done")
} else if stage == 4 {
// Virtualizazion Stage
logInfo("Performing Virtualization Stage ...")
exe("sudo pacman -S --noconfirm --needed " + strings.Join(virtualizationPackages, " "))
exe("sudo systemctl enable --now libvirtd.service")
exe("sudo systemctl enable --now docker.service")
exe("sudo virsh net-start default")
exe("sudo virsh net-autostart default")
curUser, err := user.Current()
if err != nil {
logError("Failed to get user: ", err)
os.Exit(1)
}
exe("sudo usermod -aG libvirt " + curUser.Username)
exe("sudo usermod -aG libvirt-qemu " + curUser.Username)
exe("sudo usermod -aG kvm " + curUser.Username)
exe("sudo usermod -aG input " + curUser.Username)
exe("sudo usermod -aG disk " + curUser.Username)
logInfo("Stage 7 Done")
logInfo("Now reboot and everything should be set up")
} else if stage == 5 {
logInfo("Performing User Stage ...")
// User Stage to add another user
addUser(argUserName, argPassword, allDefault, userDefault)
logInfo("User Stage Done")
} else if stage == 255 {
// Testing
logInfo("Performing Tests ...")
for _, ext := range vscodeExtensions {
exe("code --install-extension " + ext)
}
logInfo("Tests Done")
} else {
logError("Invalid Stage ", stage)
os.Exit(1)
}
}
func input() string {
reader := bufio.NewReader(os.Stdin)
text, err := reader.ReadString('\n')
if err != nil {
return ""
}
return strings.TrimSuffix(text, "\n")
}
func inputWithDefault(defaultValue string) string {
text := input()
if text == "" {
return defaultValue
}
return text
}
func exe(command string) {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
cmd := exec.Command(words[0], args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
logScript(command)
if err := cmd.Run(); err != nil {
logError("\"", command, "\" failed: ", err)
os.Exit(1)
}
}
func exeDontCare(command string) {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
cmd := exec.Command(words[0], args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
logScript(command)
cmd.Run()
}
func exeArgs(args ...string) {
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
logScript(strings.Join(args, " "))
if err := cmd.Run(); err != nil {
logError("\"", strings.Join(args, " "), "\" failed: ", err)
os.Exit(1)
}
}
func exeAppendFile(command, filename string) {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0744)
if err != nil {
logError("Failed to open \"", filename, "\" for \"", command, "\": ", err)
os.Exit(1)
}
defer file.Close()
cmd := exec.Command(words[0], args...)
cmd.Stdout = file
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
logScript(command, " >> ", filename)
if err := cmd.Run(); err != nil {
logError("\"", command, "\" failed: ", err)
os.Exit(1)
}
}
func exeToString(command string) string {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
var builder strings.Builder
cmd := exec.Command(words[0], args...)
cmd.Stdout = &builder
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
logScript(command)
if err := cmd.Run(); err != nil {
logError("\"", command, "\" failed: ", err)
os.Exit(1)
}
return builder.String()
}
func exeToStringSilent(command string) (string, error) {
words := strings.Split(command, " ")
if len(words) == 0 {
return "", errors.New("No Command")
}
var args []string
if len(words) > 1 {
args = words[1:]
}
var builder strings.Builder
var stderr strings.Builder
cmd := exec.Command(words[0], args...)
cmd.Stdout = &builder
cmd.Stderr = &stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("\"%s\" failed: %s", command, stderr.String())
}
return builder.String(), nil
}
func exeRetry(command string) {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
logScript(command)
var tries int
for {
tries++
cmd := exec.Command(words[0], args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
logError("failed: ", err, ". Trying again. ", 5-tries, " tries left ...")
if tries == 5 {
logError("failed 5 times quitting")
os.Exit(1)
}
time.Sleep(500 * time.Millisecond)
} else {
break
}
}
}
func exeEnv(command string, envNameValue ...string) {
words := strings.Split(command, " ")
if len(words) == 0 {
logError("No Command")
os.Exit(1)
}
var args []string
if len(words) > 1 {
args = words[1:]
}
cmd := exec.Command(words[0], args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Env = envNameValue
logScript(
fmt.Sprint(
strings.Join(envNameValue, " "),
" ",
command,
),
)
if err := cmd.Run(); err != nil {
logError("\"", command, "\" failed: ", err)
os.Exit(1)
}
}
func copyConfig(src string) {
var dst string
homeDir, _ := os.UserHomeDir()
if strings.HasPrefix(src, "home/ninja") {
dst = strings.Replace(src, "home/ninja", homeDir, 1)
} else {
dst = "/" + src
}
dirname := filepath.Dir(dst)
if strings.HasPrefix(dst, homeDir) {
exe("mkdir -p " + dirname)
exe("cp " + src + " " + dst)
} else {
exe("sudo mkdir -p " + dirname)
exe("sudo cp " + src + " " + dst)
}
}
func logInfo(msg ...any) {
msgStr := fmt.Sprint(msg...)
fmt.Printf("\n\n\033[30;46m[INFO]\033[0;33m %s\033[0m\n\n", msgStr)
}
func logError(msg ...any) {
msgStr := fmt.Sprint(msg...)
fmt.Fprintf(os.Stderr, "\n\n\033[30;41m[ERROR]\033[0;33m %s\033[0m\n\n", msgStr)
}
func logScript(msg ...any) {
msgStr := fmt.Sprint(msg...)
fmt.Printf("\033[30;47m[CALL]\033[0;33m %s\033[0m\n", msgStr)
}
func prompt(msg ...any) {
msgStr := fmt.Sprint(msg...)
fmt.Printf("\033[30;47m[PROMPT]\033[0;33m %s: \033[0m", msgStr)
}
func promptWithDefault(defaultValue string, allDefault bool, msg ...any) string {
msgStr := fmt.Sprint(msg...)
msgStr = fmt.Sprint(msgStr, " (", defaultValue, ")")
prompt(msgStr)
if allDefault {
fmt.Println(defaultValue)
return defaultValue
}
value := inputWithDefault(defaultValue)
return value
}
func promptWithDefaultYesNo(defaultValue, allDefault bool, msg ...any) bool {
msgStr := fmt.Sprint(msg...)
msgStr = fmt.Sprint(msgStr, " yes|no")
var defaultValueStr string
if defaultValue {
defaultValueStr = "yes"
} else {
defaultValueStr = "no"
}
value := promptWithDefault(defaultValueStr, allDefault, msgStr)
valueBool := strings.HasPrefix(strings.ToLower(value), "y")
return valueBool
}
func isInstalled(program string) bool {
_, err := exec.LookPath(program)
return err == nil
}
func dinitServiceExists(service string) bool {
cmd := exec.Command("sudo", "dinitctl", "status", service)
err := cmd.Run()
return err == nil
}
func parseStage(arg string) int {
switch strings.ToLower(arg) {
case "test":
return 255
case "applications", "apps", "application":
return 2
case "gaming":
return 3
case "virt", "virtualization":
return 4
case "user":
return 5
default:
v, err := strconv.ParseUint(arg, 10, 64)
if err != nil {
logError("Failed to parse stage argument: ", err)
os.Exit(1)
}
return int(v)
}
}
func isUEFI(allDefault bool) bool {
_, err := os.Stat("/sys/firmware/efi")
if err != nil && !os.IsNotExist(err) {
logInfo("Failed to check if the system is UEFI automatically: ", err, " Manual input required.")
return promptWithDefaultYesNo(false, allDefault, "Is UEFI")
}
return err == nil
}
func backupName(filename string) string {
for {
filename = filename + ".bak"
if _, err := os.Stat(filename); err != nil && os.IsNotExist(err) {
return filename
}
}
}
func sudoRankmirrors(mirrorlistPath string) {
// Create back up
mirrorlistBak := backupName(mirrorlistPath)
exeArgs("sudo", "mv", mirrorlistPath, mirrorlistBak)
// rank mirror list
exe("sudo reflector --latest 5 --sort rate --save " + mirrorlistPath + ".tmp")
// Overwrite old mirrorlist
exeArgs("sudo", "mv", mirrorlistPath+".tmp", mirrorlistPath)
}
func rankmirrors(mirrorlistPath string) {
// Create back up
mirrorlistBak := backupName(mirrorlistPath)
exeArgs("mv", mirrorlistPath, mirrorlistBak)
// rank mirror list
exe("reflector --latest 5 --sort rate --save " + mirrorlistPath + ".tmp")
// Overwrite old mirrorlist
exeArgs("mv", mirrorlistPath+".tmp", mirrorlistPath)
}
func mountedDeviceName() string {
dfOut, err := exeToStringSilent("df")
if err == nil {
lines := strings.Split(dfOut, "\n")
for _, line := range lines {
words := strings.Split(line, " ")
// Clear empty ones
for i := 0; i < len(words); i++ {
if words[i] == "" {
words = append(words[:i], words[i+1:]...)
i--
}
}
if len(words) < 6 {
continue
}
partition := words[0]
directory := words[5]
if directory == "/" {
return strings.Trim(partition, "0123456789")
}
}
}
logInfo("Failed to get mounted device name automatically. Manual input required.")
exe("lsblk")
for {
prompt("Which device is currently mounted at /mnt (e.g. /dev/sda)?")
if device := input(); device != "" {
return device
}
}
}
func passwordPrompt(username, argPassword string, allDefault bool) {
var pw string
if len(argPassword) != 0 {
pw = argPassword
} else {
for {
pw1 := promptWithDefault("s", allDefault, "Password")
pw2 := promptWithDefault("s", allDefault, "Reenter Password")
if pw1 != pw2 {
logError("Passwords do not match. Please enter again!")
} else {
pw = pw1
break
}
}
}
pwCrypt, err := exeToStringSilent("mkpasswd " + pw)
if err == nil {
pwCrypt = strings.TrimSpace(pwCrypt)
// Set the root password if this is the first user
entries, err := os.ReadDir("/home")
if username != "root" && err == nil && len(entries) == 0 {
exeArgs("usermod", "--password", pwCrypt, username)
}
exeArgs("usermod", "--password", pwCrypt, username)
} else {
logInfo("Failed to create password using mkpasswd. passwd is required.")
logInfo("Root password")
exe("passwd")
logInfo("Password for user " + username)
exe("passwd " + username)
}
}
func chaoticInstalled() bool {
cmd := exec.Command("pacman", "-Qk", "chaotic-mirrorlist")
if err := cmd.Run(); err != nil {
return false
}
return true
}
func installOdinfmt() {
if isInstalled("odinfmt") {
logInfo("Skipping installation of odinfmt since it is already installed")
return
}
logInfo("Installing odinfmt ...")
curDir, _ := os.Getwd()
tmpDir := os.TempDir()
olsDir := filepath.Join(tmpDir, "ols")
exeDontCare("rm -rf " + olsDir)
exe("git clone https://github.com/DanielGavin/ols.git -b master --depth 1 " + olsDir)
os.Chdir(olsDir)
exe("./odinfmt.sh")
exe("sudo cp odinfmt /usr/bin")
os.Chdir(curDir)
}
func addUser(username, password string, allDefault, userDefault bool) {
var userName string
if len(username) != 0 {
userName = username
} else {
userName = promptWithDefault("ninja", allDefault && userDefault, "Username")
}
exe("useradd -m " + userName)
passwordPrompt(userName, password, allDefault && userDefault)
exe("usermod -aG wheel " + userName)
homeDir := "/home/" + userName
// Copy contents of home directory