This repository has been archived by the owner on Dec 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.py
executable file
·3066 lines (2540 loc) · 115 KB
/
setup.py
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
#!/usr/bin/env python3
#
# Project : ArchInstaller.py (https://git.io/fjFL6)
# Author : JamiKettunen (https://git.io/fj0wc)
# License : MIT (https://git.io/fjdxG)
# Reference : The Wiki (https://wiki.archlinux.org/index.php/Installation_guide)
# Description : My personal Arch Linux installer script
#
# File IO, argv, run, sleep, ...
import os, sys, subprocess, time, re, random
# Import configured user variables
try:
from config import *
except ModuleNotFoundError: pass
###############################
# Custom setup
###############################
def custom_setup():
# ------------ Custom system & packages setup goes here...
# Install custom packages
write_msg("Installing custom packages & applications...", 1)
errors = Pkg.install('bash-completion lsof strace psutils gnu-netcat reflector vim htop neofetch lm_sensors rsync tree')
if enable_aur:
errors += Pkg.aur_install('c-lolcat downgrade')
if de != '':
# Xorg, MIME, cursors, fonts etc
errors += Pkg.install('xorg-xkill xorg-xprop xorg-xrandr xorg-xauth x11-ssh-askpass xorg-fonts-alias-misc perl-file-mimeinfo perl-net-dbus perl-x11-protocol lsd ctags trash-cli wget capitaine-cursors youtube-dl python-pycryptodome')
if install_de_apps and vm_env == '':
errors += Pkg.install('noto-fonts-emoji noto-fonts-cjk code discord')
hide_app('electron6')
# Steam
if enable_multilib and not bat_present:
errors += Pkg.install('steam wqy-zenhei lib32-libldap')
IO.replace_ln(f'{apps_path}/steam.desktop', 'Name=', 'Name=Steam')
# Powerline status for Vim
# TODO: Install powerline-status from AUR (python-powerline-git) instead to avoid pip package conflicts in the future?
Pkg.install('python-lazy-object-proxy python-wrapt python-typed-ast python-astroid python-mccabe python-isort python-pylint')
Cmd.log('python -m pip install -U powerline-status')
write_status(errors)
# ------------ Wi-Fi setup
if vm_env == '':
wifi_setup = Cmd.suppress('lspci | egrep -i "wireless|wlan|wifi"') == 0
if wifi_setup:
write_msg("Setting up Wi-Fi hardware...", 1)
errors = Pkg.install(f'crda {kernel}-headers')
errors += IO.uncomment_ln('/etc/conf.d/wireless-regdom', f'WIRELESS_REGDOM="{LC_ALL[3:5]}"') # e.g. "FI"
bcm_install = Cmd.suppress('lspci | egrep -i "bcm|broadcom"') == 0
if bcm_install:
errors += Pkg.install('broadcom-wl-dkms')
# BCM4352
if Cmd.suppress('lspci | grep -i bcm4352') == 0:
errors += Pkg.aur_install('bcm20702a1-firmware')
write_status(errors, 0, 4)
# ------------ GRUB theme setup (when multibooting)
if multibooting:
write_msg("Configuring custom 'Tela' GRUB theme...", 1)
errors = IO.replace_ln(grub_conf, '#GRUB_THEME=', 'GRUB_THEME="/usr/share/grub/themes/Tela/theme.txt"')
errors += Cmd.exec('cd /tmp; git clone --depth 1 https://github.com/vinceliuice/grub2-themes.git &>>/setup.log && sed "/GRUB_THEME/d" -i grub2-themes/install.sh && grub2-themes/install.sh -t &>>/setup.log')
write_status(errors)
# ------------ TLP tweaks (TODO Move changes to laptop repo)
if bat_present:
file = '/etc/default/tlp'
IO.replace_ln(file, 'TLP_DEFAULT_MODE=', 'TLP_DEFAULT_MODE=BAT')
IO.replace_ln(file, '#CPU_SCALING_GOVERNOR_ON_AC=', 'CPU_SCALING_GOVERNOR_ON_AC=performance')
IO.uncomment_ln(file, 'CPU_SCALING_GOVERNOR_ON_BAT=') # powersave
IO.replace_ln(file, 'RESTORE_DEVICE_STATE_ON_STARTUP=', 'RESTORE_DEVICE_STATE_ON_STARTUP=1')
###############################
# "Constant" values
###############################
status_colors = {
0: 1,
1: 4,
2: 3,
3: 2,
4: 4,
5: 7
}
status_mgs = {
0: ' ',
1: 'WAIT',
2: 'DONE',
3: 'FAIL',
4: 'WARN',
5: 'INFO'
}
# Runtime vars
script_path, script_fn = os.path.split(os.path.abspath(sys.argv[0])) # Script filename e.g. 'setup.py'
script_path += ('/' + script_fn) # Full script path e.g. '/root/setup.py'
script_root = script_path.rsplit('/', 1)[0] # Directory path of script e.g. '/root'
# Vars updated on script load
args = '' # All arguments in one string
boot_mode = 'BIOS/CSM' # 'BIOS/CSM' / 'UEFI'
mbr_grub_dev = '' # GRUB install device on MBR systems e.g. '/dev/sda'
kernel = 'linux' # Used by the script for kernel specific configuration like pkgs; e.g. 'linux-lts', 'linux-hardened'
use_dkms_pkgs = False # Disabled for vanilla 'linux' kernel
cpu_family = '' # CPU family number e.g. '6'
cpu_model = '' # CPU model number e.g. '60'
cpu_identifier = '' # CPU identifier e.g. 'intel_6-60-4'
in_chroot = False # Inside chroot?
vm_env = '' # Virtualized env: '','vbox','vmware','qemu','other'
bat_present = False # Any battery present?
disc_tray_present = False # Any disc tray present?
bt_present = False # Any BT device present?
camera_present = False # Any camera device present?
video_drv = '' # e.g. 'nvidia','nvidia-340','noveau+mesa','amdgpu+mesa','intel+mesa','bumblebee' etc
use_qt_apps = False # Get Qt versions of apps
unres_users = [] # List of users with admin rights
aur_cache = '' # Path of cached AUR packages e.g. '/pkgcache/pkgcache/aur/intel_6-60-4'
pkgcache_enabled = os.path.exists('/pkgcache')
# Other vars
lsblk_cmd = "lsblk | grep -v '^loop' | grep -v '^sr0'"
blkid_cmd = "blkid | grep -v '^/dev/loop' | grep -v '^/dev/sr0'"
apps_path = '/usr/share/applications'
cflags = '-march=native -O2 -pipe -fstack-protector-strong -fno-plt'
mounts = '' # Current mounts e.g. '/efi:/dev/sda1,root:/dev/sda2'
grub_conf = '/etc/default/grub'
outdated_pkgs = ''
menu_visit_counter = 0
###############################
# Helper functions
###############################
# Clear the entire screen buffer
def clear_screen():
Cmd.exec('clear', '', False)
# Printing text
# Returns a string with parsed terminal output forecolor; usage:
# e.g. color_str("§2red §0reset §5blue")
# Colors:
# 0 = Default (white fg, black bg)
# 1 = Black
# 2 = Red
# 3 = Green
# 4 = Yellow
# 5 = Blue
# 6 = Magenta
# 7 = Cyan
# 8 = White
def color_str(string, reset=True):
if '§' in string: # Possible color definition found
for f in range(0, 9): # Forecolor only: (0-8)
match = f'§{str(f)}' # e.g. '§2'
if match not in string: # match not found => check next color
continue
fg = '0' # default fg to white (37)
if f != 0: # update fg to use defined color
fg = str(29 + f)
string = string.replace(match, f'\033[0;{fg}m') # e.g. '\e[0;32m'
if reset:
string += '\033[0m'
return string
# Writes text to stdout with optional coloring; see color_str()
def write(text):
if '\\§' in text: text = text.replace('\\§', '§') # '\§' => '§'
elif '§' in text: text = color_str(text)
sys.stdout.write(text)
sys.stdout.flush()
# Writes a line of text to stdout with optional coloring; see color_str()
def write_ln(text='', new_line_count=1):
for _ in range(0, new_line_count):
text += '\n'
write(text)
# Clears the screen & prints a *nice* looking header
def print_header(header):
ul = ('=' * len(header)) # e.g. '============='
clear_screen()
write_ln(f'§7{header}') # e.g. 'A Nice Header'
write_ln(f'§7{ul}', 2)
# Writes a status message; see status_mgs & status_colors. Examples:
# >> Using log engine v2.0
# >> [ WAIT ] Fetching latest data...
# >> [ OK ] Started NetworkManager service
# >> [ FAIL ] ...
def write_msg(msg, status=0, override_newline=-1):
if status > 0:
color = status_colors.get(status)
status_msg = status_mgs.get(status, 0)
write(f'§{color}>> [ {status_msg} ] ') # e.g. '>> [ WAIT ] '
else:
write('§7>> ') # '>> '
new_ln = True if override_newline == -1 and status > 1 else False
new_ln = True if override_newline == 1 else new_ln
write(msg + ('\n' if new_ln else ''))
# Writes back to the current status message line to update the appearance depending on a command's return value
# write_status(0, 0)
# '>> [ DONE ]'
# write_status(1, 0, 4)
# '>> [ WARN ]'
def write_status(ret_val=0, expected_val=0, error_status=3):
if ret_val == expected_val:
status_msg = status_mgs.get(2)
write_ln(f'\r§3>> [ {status_msg} ]')
else:
color = status_colors.get(error_status)
status_msg = status_mgs.get(error_status)
write_ln(f'\r§{color}>> [ {status_msg} ]')
# Logging
# Log a new line to /(tmp/)setup.log
# Returns: 0 = Success, 1 = Error
def log(text):
path = '' if in_chroot else '/tmp'
return IO.write_ln(f'{path}/setup.log', text)
# File I/O class to read from & write to files
class IO:
# Reads the first line from a file
# Returns: String on success, None on error
@staticmethod
def read_ln(f_path):
try:
with open(f_path, 'r') as f:
tmp_ln = f.readline().rstrip('\n')
except:
tmp_ln = None
return tmp_ln
# Writes text to a file
# Returns: 0 = Success, 1 = Error
@staticmethod
def write(f_path, text, append=False):
try:
mode = 'a' if append else 'w'
with open(f_path, f'{mode}+') as f:
f.write(text)
return 0
except:
return 1
# Appends text to a file
# Returns: 0 = Success, 1 = Error
#@staticmethod
#def append(f_path, text):
# return IO.write(f_path, text, True)
# Writes a line to a file
# Returns: 0 = Success, 1 = Error
@staticmethod
def write_ln(f_path, text='', append=True):
return IO.write(f_path, text + '\n', append)
# Replace a line with another in a file
# Returns: 0 = Replaced, 1 = Line not found, 2 = Error
@staticmethod
def replace_ln(file_path, search_ln, replace_ln, only_first_match=True):
try:
found = False
file_lines = ''
with open(file_path) as lines:
for line in lines:
line = line.rstrip() # e.g. 'line\n' => 'line'
if not only_first_match or (only_first_match and not found):
if line.startswith(search_ln):
found = True
line = replace_ln
file_lines += f'{line}\n'
if found:
with open(file_path, 'w') as f:
f.write(file_lines.rstrip())
return 0
else:
return 1
except:
return 2
# Uncomments a line in a file
# Returns: 0 = Uncommented, 1 = Line not found, 2 = Error
# TODO Return uncommented line & use for future purposes
@staticmethod
def uncomment_ln(file_path, search_ln, comment_prefix='#'):
try:
found = False
file_lines = ''
with open(file_path) as lines:
for line in lines:
line = line.rstrip() # e.g. 'line\n' => 'line'
if not found and line.startswith(comment_prefix + search_ln):
found = True
line = line[len(comment_prefix):]
file_lines += f'{line}\n'
if found:
with open(file_path, 'w') as f:
f.write(file_lines.rstrip())
return 0
else:
return 1
except:
return 2
# Returns: line number of found line, -1 when not found
@staticmethod
def get_ln_number(file_path, search_ln):
try:
line_num = -1
with open(file_path) as lines:
ln = 1
for line in lines:
line = line.rstrip() # e.g. 'line\n' => 'line'
if line.startswith(search_ln):
line_num = ln
break
ln += 1
return line_num
except:
return -2
# Package management
class Pkg:
# Refresh local package database cache
# Quit script execution on error
@staticmethod
def refresh_dbs(force_refresh=False, quit_on_fail=True):
cmd = 'pacman -Sy'
cmd += 'y' if force_refresh else ''
ret_val = Cmd.log(cmd)
if ret_val != 0 and quit_on_fail:
log_path = 'mnt' if in_chroot else 'tmp'
write_ln(f'§2ERROR: §0Database refreshing failed. Check /{log_path}/setup.log for details')
exit_code = 8 if force_refresh else 7
exit(exit_code) # 7 = Couldn't synchronize databases, 8 = Force-refresh failed
return ret_val
# Install packages from the Arch repositories (core, extra, community)
# or optionally a local package with the absolute path defined
# Returns: pacman exit code
@staticmethod
def install(pkgs, only_needed=True):
pac_args = '--needed' if only_needed else ''
local = ('/' in pkgs)
if pkgcache_enabled and in_chroot and not local:
pac_args += ' --cachedir /pkgcache/pkgcache'
if len(pac_args) > 0: pac_args = ' ' + pac_args.strip()
action = 'U' if local else 'S'
ret_val = Cmd.log(f'pacman -{action} --noconfirm --noprogressbar{pac_args} {pkgs}')
return ret_val
# Install Arch package groups while optionally ignoring some of the members
# Both 'groups' and 'excluded_pkgs' are space (' ') seperated lists
# Returns: pacman exit code
@staticmethod
def install_group(groups, excluded_pkgs='', only_needed=True):
tmp_pkgs = ''
if len(excluded_pkgs) > 0:
for pkg in excluded_pkgs.split(' '):
tmp_pkgs += pkg + '|'
excluded_pkgs = tmp_pkgs[:-1] # Remove last '|'
pkgs = f'$(pacman -Sg {groups} | cut -d" " -f2'
pkgs += (f' | egrep -v "{excluded_pkgs}"' if len(excluded_pkgs) > 0 else '') + ')'
pac_args = '--needed' if only_needed else ''
if pkgcache_enabled and in_chroot:
pac_args += ' --cachedir /pkgcache/pkgcache'
if len(pac_args) > 0: pac_args = ' ' + pac_args.strip()
ret_val = Cmd.log(f'pacman -S {pkgs} --noconfirm --noprogressbar{pac_args}')
return ret_val
# Remove installed packages on a system
# Returns: pacman exit code
@staticmethod
def remove(pkgs, also_deps=False, log_cmd=True):
pac_args = '-Rn' + ('sc' if also_deps else '') + ' --noconfirm --noprogressbar'
ret_val = Cmd.log(f'pacman {pac_args} {pkgs}', '', log_cmd)
return ret_val
# Install packages from the Arch User Repository (AUR)
# Returns: pacman exit code
@staticmethod
def aur_install(pkgs, only_needed=True):
if in_chroot:
if enable_aur:
yay_args = '--needed' if only_needed else ''
if len(yay_args) > 0: yay_args = ' ' + yay_args.strip()
errors = 0
ccache_args = 'export PATH=/usr/lib/ccache/bin:$PATH USE_CCACHE=1; ' if use_ccache else '' # TODO Optimize, use 'env' instead?
pkgs = pkgs.strip() # To mitigate user error
if pkgcache_enabled:
for pkg in pkgs.split(' '):
pkg = pkg.strip() # To mitigate user error
# TODO Check version differently for '-git' packages e.g. 'pulseaudio-modules-bt-git' report old pkg versions on yay query
ver = Cmd.output(f'$ yay -Si {pkg} | grep Version', 'aurhelper').split(':', 1)[1].strip() # e.g. '3.3.0-1'
latest_pkg = ''
try: latest_pkg = str(Cmd.output(f'ls {aur_cache}/ | grep {pkg} | grep {ver}')).split('\n')[0].strip() # e.g. 'polybar-3.3.0-1-x86_64.pkg.tar.xz'
except: pass
if len(latest_pkg) > 0: # Up-to-date cached version found => install it instead
errors += Pkg.install(f'{aur_cache}/{latest_pkg}', only_needed)
else: # Cached version not found => fetch from the AUR
ret_val = Cmd.log(f'$ {ccache_args}yay -Sq --noconfirm{yay_args} {pkg}', 'aurhelper')
if ret_val == 0: # Installed => try caching package
Cmd.log(f'cp /home/aurhelper/.cache/yay/{pkg}/*.pkg.tar.xz {aur_cache}/')
errors += ret_val
else:
errors = Cmd.log(f'$ {ccache_args}yay -Sq --noconfirm{yay_args} {pkgs}', 'aurhelper')
return errors
else:
log(f"[setup.py:Pkg.aur_install('{pkgs}')] WARN: Ignoring installation since AUR support is not present.")
else:
log(f"[setup.py:Pkg.aur_install('{pkgs}')] WARN: Ignoring installation since not in chroot.")
return 1
# Command execution
class Cmd:
# Run a command on the shell with an optional io stream
# io_stream_type: 0 = none, 1 = stdout, 2 = logged, 3 = all_supressed
# Returns: command exit code / output when io_stream_type=2
@staticmethod
def exec(cmd, exec_user='', log_cmd=True, io_stream_type=0):
user_exec = cmd.startswith('$ ')
exec_cmd = cmd
if user_exec:
if exec_user == '':
exec_user = users.split(',')[0]
cmd = cmd[2:] # Remove '$ ' from user_exec commands
if len(exec_user) > 0:
exec_cmd = f"sudo -i -u {exec_user} -H bash -c '{cmd}'"
else:
log(f"[setup.py:Cmd.exec({str(io_stream_type)})] WARN: Ignoring '{cmd}' execution, since no user was defined.")
return 1
use_stdout = (io_stream_type == 1)
logged = (io_stream_type == 2)
suppress = (io_stream_type == 3)
# TODO Still log everything if launched with '-D' flag for debugging purposes
if log_cmd and io_stream_type % 2 == 0: # Log executed command line ()
start = '# ' + (f'({exec_user}) $ ' if user_exec else '')
log(f'\n{start}{cmd}') # e.g. '# pacman -Syu'
end = ''
if suppress or logged:
path = '' if in_chroot else '/tmp'
log_path = f'{path}/setup.log' # e.g. '/tmp/setup.log' or '/setup.log' in chroot
#end = ' &>>' + (log_path if (logged and log_cmd) else '/dev/null')
end = ' ' + f'&>>{log_path}' if logged and log_cmd else '&>/dev/null'
cmd = exec_cmd + end
# TODO Log cmd line when debugging
if use_stdout: res = subprocess.run(cmd, shell=True, encoding='utf-8', capture_output=use_stdout)
else: res = subprocess.run(cmd, shell=True)
if log_cmd and io_stream_type % 2 == 0 and res.returncode != 0:
log(f'\n# Command non-zero exit code: {res.returncode}')
returns = res.stdout if use_stdout else res.returncode
return returns
# Run a command on the shell while capturing all it's output
# New lines are seperated with a '\n'
# Returns: command exit code
@staticmethod
def output(cmd, exec_user='', log_cmd=True):
return Cmd.exec(cmd, exec_user, log_cmd, 1)
# Run a command on the shell while logging all it's output
# Returns: command exit code
@staticmethod
def log(cmd, exec_user='', log_cmd=True):
return Cmd.exec(cmd, exec_user, log_cmd, 2)
# Run a command on the shell while supressing all it's output
# Returns: command exit code
@staticmethod
def suppress(cmd, exec_user=''):
return Cmd.exec(cmd, exec_user, False, 3)
# Check whether a command e.g. 'nc' is available on a system
# Returns: boolean
@staticmethod
def exists(cmd):
ret_val = Cmd.suppress(f'type {cmd}') # command -v
return (ret_val == 0)
# Checking user details
class User:
# Returns: Boolean representing the user's restricted status
@staticmethod
def is_restricted(user=''):
if len(users) == 0: return False # No users => can't be restricted
# TODO Add proper checking (against users list)
return user in restricted_users.split(',')
# Returns: Restricted users in a list
@staticmethod
def get_restricted_users():
if len(users) == 0: return [] # No users => can't be restricted
# TODO Add proper checking (against users list)
return restricted_users.split(',')
# Returns: Boolean representing the user's passwordless status
@staticmethod
def is_passwdless(user=''):
if len(users) == 0: return False # No users => can't be passwdless
# TODO Add proper checking (against users list)
return user in passwdless_users.split(',')
# Returns: Passwordless users in a list
@staticmethod
def get_passwdless_users():
if len(users) == 0: return [] # No users => can't be unrestricted
# TODO Add proper checking (against users list)
return passwdless_users.split(',')
# Returns: Unrestricted users in a list
@staticmethod
def get_unrestricted_users():
if len(users) == 0: return [] # No users => can't be unrestricted
users_lst = users.split(',')
res_users_lst = User.get_restricted_users()
unres_users_lst = []
for user in users_lst:
if user not in res_users_lst:
unres_users_lst.append(user)
return unres_users_lst
###############################
# Pre-run checks
###############################
# Check if running in Arch Linux installer env & quit if not
# Additionally update details about the device
def check_env():
global de, users, boot_mode, in_chroot, kernel_type, kernel, use_dkms_pkgs, cpu_family, cpu_model, cpu_identifier, aur_cache, use_qt_apps, unres_users
os_compat_msg = 'Please only run this script on the Arch Linux installer environment.\n\nhttps://www.archlinux.org/download/'
file_msg = "It seems that you are missing a '§f' module.\n"
if os.name == 'posix':
ret_val = Cmd.suppress('cat /etc/hostname')
if ret_val == 0:
host = Cmd.output("grep -v '^#' /etc/hostname | tr -d '\n'")
if host != 'archiso':
print(os_compat_msg)
exit(3) # 3 = Not running in ArchISO environment
#elif host == hostname:
# TODO Add post-install script parts => verify here
else: # Read failed => Assume chroot environment
# TODO Use a better chroot detection mechanism
in_chroot = True
if not in_chroot: in_chroot = os.path.isfile('/chroot')
if in_chroot: Cmd.suppress('rm -f /chroot')
# config.py
try:
kernel_type = kernel_type.strip().lower()
if kernel_type == 'stable':
kernel_type = ''
else:
kernel = 'linux-' + kernel_type # e.g. 'linux-lts', 'linux-hardened'
use_dkms_pkgs = True
except: # NameError
print(file_msg.replace('§f', 'config.py'))
write_msg(f'Would you like to try & §7fetch §0the file from GitHub? (§3Y§0/§2n§0)? §7>> ')
ans = input().upper().replace('YES', 'Y')
if len(ans) == 0 or ans == 'Y':
write_ln()
write_msg('Downloading latest revision of config.py from https://git.io/fjFmg...', 1)
ret_val = Cmd.suppress(f'curl https://git.io/fjFmg -Lso {script_root}/config.py')
write_status(ret_val)
print()
exit(4) # 4 = config.py not loaded
# CPU type needed for ucode
cpu_type = 'intel' if Cmd.suppress('cat /proc/cpuinfo | grep -i intel') == 0 else 'amd'
cpu_family = Cmd.output("cat /proc/cpuinfo | grep -i family | uniq").split(':', 1)[1].strip() # e.g. '6'
cpu_model = Cmd.output("cat /proc/cpuinfo | grep -i model | grep -vi '^model name' | uniq").split(':', 1)[1].strip() # e.g. '60'
cpu_cores = Cmd.output("cat /proc/cpuinfo | grep -i processor | wc -l").strip() # e.g. '4'
cpu_identifier = f'{cpu_type}_{cpu_family}-{cpu_model}-{cpu_cores}' # e.g. 'intel_6-60-4'
aur_cache = f'/pkgcache/pkgcache/aur' + (f'/{cpu_identifier}' if optimize_compilation and optimize_cached_pkgs else '')
de = de.lower().replace('deepin', 'dde').replace('none', '')
use_qt_apps = (de == 'kde' or de == 'lxqt')
users = users.replace(' ', '').lower().strip()
unres_users = User.get_unrestricted_users()
# Update bootmode to EFI if required
ret_val = Cmd.suppress('ls /sys/firmware/efi/efivars')
if ret_val == 0: boot_mode = 'UEFI' # efivars dir exits => booted in UEFI
else:
print(os_compat_msg)
input()
exit(2) # 2 = Non-POSIX systems are incompatible
# TODO Load phrases.txt for preferred language & transform all phrases in
def load_localization():
pass
# Check if running as root
def check_privs():
user = Cmd.output('whoami').rstrip('\n')
if user != 'root':
write_ln('§2ERROR: §0Please run this script as root to continue.')
exit(5) # 5 = Privilege requirements unmet
###############################
# Functions
###############################
# Use custom installer color definitions
def load_colors():
Cmd.exec("echo -en '\\033]P0101010'", '', False) # Black
Cmd.exec("echo -en '\\033]P1AF1923'", '', False) # Dark Red
Cmd.exec("echo -en '\\033]P269A62A'", '', False) # Dark Green
Cmd.exec("echo -en '\\033]P3E68523'", '', False) # Dark Yellow
Cmd.exec("echo -en '\\033]P42935B1'", '', False) # Dark Blue
Cmd.exec("echo -en '\\033]P57C1FA1'", '', False) # Dark Magenta
Cmd.exec("echo -en '\\033]P62397F5'", '', False) # Dark Cyan
Cmd.exec("echo -en '\\033]P7A4A4A4'", '', False) # Light Gray
Cmd.exec("echo -en '\\033]P8303030'", '', False) # Dark Gray
Cmd.exec("echo -en '\\033]P9FF0000'", '', False) # Red
Cmd.exec("echo -en '\\033]PA4CFF00'", '', False) # Green
Cmd.exec("echo -en '\\033]PBFFD800'", '', False) # Yellow
Cmd.exec("echo -en '\\033]PC0026FF'", '', False) # Blue
Cmd.exec("echo -en '\\033]PDFF00FF'", '', False) # Magenta
Cmd.exec("echo -en '\\033]PE00FFFF'", '', False) # Cyan
Cmd.exec("echo -en '\\033]PFF5F5F5'", '', False) # White
clear_screen() # For avoiding coloring artifacts
# Check network connectivity with ping
def check_connectivity():
write_msg('Checking network connectivity...', 1)
ret_val = Cmd.log('curl -s 1.1.1.1')
if ret_val != 0:
write_status(1)
write_ln("\n§2ERROR: §0No network connectivity. Check your connection and try again.", 2)
exit(6) # 6 = Network connectivity issue
elif enable_aur: # Test connection to AUR
ret_val += Cmd.log('ping -c 1 aur.archlinux.org')
write_status(ret_val, 0, 4)
if ret_val != 0:
write_ln("\n§4WARN: §0Possibly unreliable network connection detected: AUR support could fail to be enabled.")
write_msg(f'Would you like to continue §2without §0making any changes? (§3y§0/§2N§0)? §7>> ')
ans = input().upper().replace('YES', 'Y')
write_ln()
if ans != 'Y':
exit(6) # 6 = Network connectivity issue
else: write_status()
# Load console font using 'setfont'
def load_font():
global font
if font == '' or font == 'def' or font == 'default':
font = 'default8x16'
if font.startswith('ter-'):
write_msg('Installing the terminus-font package, please wait...', 1)
ret_val = Pkg.install('terminus-font')
write_status(ret_val)
write_msg(f"Loading system font '{font}'...", 1)
ret_val = Cmd.log('setfont ' + font)
write_status(ret_val)
if ret_val != 0:
write_ln("§2ERROR: §0Font loading failed. Most likely cause: the specified font was not found.")
exit(9) # 9 = Font couldn't be loaded!
# Load kb map using 'loadkeys'
def load_kbmap():
write_msg(f"Loading system keymap '{keymap}'...", 1)
ret_val = Cmd.log('loadkeys ' + keymap)
write_status(ret_val)
if ret_val != 0:
write_ln("§2ERROR: §0Keymap loading failed. Most likely cause: the specified keymap was not found.")
exit(10) # 10 = Keymap couldn't be loaded!
# NTP time synchronization
def ntp_setup():
write_msg('Enabling NTP time synchronization...', 1)
ret_val = Cmd.log('timedatectl set-ntp true')
write_status(ret_val, 0, 4)
# Disk partitioning
def partition(tool_to_use=''):
Cmd.exec(f"echo && {lsblk_cmd} && echo", '', False)
tool_defined = len(tool_to_use) > 0
if tool_defined:
write_msg('Device to partition (e.g. ')
else:
write_msg('Partitioning command line (e.g. §4fdisk §7/dev/')
write("§7sda§0) §7>> ")
in_cmd = ''
in_cmd = input().strip().lower()
if len(in_cmd) > 0:
if tool_defined: Cmd.exec(f'{tool_to_use} /dev/{in_cmd}')
else: Cmd.exec(in_cmd)
def sel_par_tool(hide_guide=False):
if not hide_guide:
write_ln(" Enter '§3F§0' to partition using §3cfdisk §0(UEFI & BIOS/CSM)")
write_ln(" Enter '§4G§0' to partition using §4cgdisk §0(UEFI only)")
write_ln(" Enter '§7O§0' to partition using §7something else", 2)
write_ln(" Enter '§3L§0' to view partitions using §3lsblk")
write_ln(" Enter '§2I§0' to view partitions using §2blkid", 2)
# TODO: Add note to "cfdisk" about choosing UEFI/GPT vs BIOS/DOS!
# '>> Selection (F/G/O/L/I) >> '
write_msg('Selection (')
write('§3F§0/§4G/§7O§0/§3L§0/§2I§0) §7>> ')
sel = ''
sel = input().strip().upper()
if len(sel) > 0:
if sel == 'F':
partition('cfdisk')
elif sel == 'G':
partition('cgdisk')
elif sel == 'O':
partition()
elif sel == 'L' or sel == 'I':
cmd = lsblk_cmd if sel == 'L' else blkid_cmd
write_ln()
Cmd.exec(cmd, '', False)
write('\nPress ENTER to continue...')
input()
else:
sel_par_tool(True)
partitioning_menu()
def partitioning_menu():
global menu_visit_counter
print_header('Disk Partitioning')
middle = ' anymore' if menu_visit_counter > 0 else ''
# TODO Make user type 'done' instead to continue?
write_ln(f" §3Tip: §0If you don't need to partition{middle}, just press ENTER", 2)
menu_visit_counter += 1
sel_par_tool()
# Partition mounting & formatting
# Mount a partition
# e.g. 'mount_par('/dev/sda1', '/')'
def mount_par(blk_dev, mount_point='/', opts=''):
mount_point = f'/mnt{mount_point}' # e.g. '/' -> '/mnt/'
Cmd.suppress(f'umount -R {mount_point}') # try unmounting existing par
Cmd.log(f'mkdir -p {mount_point}')
opts = ' -o ' + opts if len(opts) > 0 else ''
return Cmd.log(f'mount{opts} {blk_dev} {mount_point}')
def par_opt_handler(opt):
global mbr_grub_dev, pkgcache_enabled
# Option validity checks
# TODO Fully disallow mounted selections to be chosen in mounting menu! (e.g. /,/efi,swap etc)
if len(opt) != 1:
list_used_pars(True)
if opt == 'E' and boot_mode != 'UEFI':
list_used_pars(True)
if opt != 'B' and opt != 'R' and opt != 'E' and opt != 'H' and opt != 'S' and opt != 'C' and opt != 'O':
list_used_pars(True)
lsblk = Cmd.output(f"{lsblk_cmd} | grep -v '/mnt' | grep -vi 'swap'")
if lsblk.count('\n') <= 2:
write_ln()
# TODO Show question to re-enter partitioning menu!
write_msg('Mounting cancelled since there are no devices to mount.', 4)
write('\nPress ENTER to continue...')
input()
mounting_menu()
write_ln(f"\n{lsblk}")
purpose = opt.replace('B', '/boot').replace('R', '/').replace('E', '/efi').replace('H', '/home').replace('S', 'swap').replace('O', 'other purpose').replace('C', 'package cache')
write_msg(f'Which partition would you like to use for §3{purpose} §0(e.g. ')
if opt == 'O':
write('§7/dev/')
write('§7sda1§0)? §7>> ')
par = ''
par = input().strip().lower() # e.g. 'sda1'
if len(par) < 4: mounting_menu()
if '/' not in par: par = '/dev/' + par # Make proper form, e.g. '/dev/sda1'
ret_val = Cmd.suppress('find ' + par)
if ret_val != 0: mounting_menu() # TODO msg user ...
# e.g. 'Would you like to format /dev/sda1 for / using ext4 (y/N)? >> '
# 'Would you like to format /dev/sda2 for swap usage (y/N)? >> '
# 'Would you like to use /dev/sda3 for other purpose (y/N)? >> '
write_ln()
write_msg(f'Would you like to §2format §7{par} §0(§2y§0/§3N§0)? §7>> ')
ans = ''
ans = input().upper().replace('YES', 'Y')
# TODO Add RAID support etc.
pause = False # Pause at end of formatting & mounting?
fs_type = 'swap' if opt == 'S' else ''
# Format...
if ans == 'Y':
# TODO Add other as fs type & custom format commands etc
format_args = {
'f2fs': '-f', # -l label
'reiserfs': '-f', # -u -l label
'xfs': '-f', # -L label
'fat': '-F32 -s2', # -n label
'ntfs': '-F -Q', # -U -L label
#'exfat': '', # -n label
#'btrfs': '-f',
}
if opt == 'E': # efi
fs_type = 'fat'
elif opt == 'S': # swap
fs_type = 'swap'
else: # other
write_ln('\n§7>> §0All available supported §3filesystem types§0:', 2)
# TODO Add other as fs types (Btrfs) & custom format commands etc
supported_fs_types = [ 'ext4', 'XFS', 'F2FS', 'ReiserFS' ]
if opt != 'R':
supported_fs_types.extend([ 'FAT32', 'exFAT', 'NTFS', 'swap' ])
for fs_type in supported_fs_types:
write_ln(f' §3{fs_type}')
write_ln()
write(f'§7>> §0Which §3filesystem type §0would you like to format §7{par} §0with (e.g. §3ext4§0)? §7>> ')
fs_type = input().strip().lower() # e.g. 'ext4'
if len(fs_type) < 3 or fs_type not in [x.lower() for x in supported_fs_types]:
mounting_menu()
fs_type = fs_type.replace('fat32', 'fat')
format_cmd = (f'mkfs.{fs_type}') if fs_type != 'swap' else 'mkswap' # e.g. 'mkfs.ext4', 'mkswap'
if fs_type in format_args:
format_cmd += ' ' + format_args.get(fs_type)
write_ln()
# TODO umount -R before formatting?
# TODO Use proper stylized version of 'fs_type' e.g. get index & use from supported_fs_types[]
write_msg(f'Formatting {par} using {fs_type.replace("fat", "fat32")}...', 1)
#format_cmd += ' -n ESP' if opt == 'E' else ''
ret_val = Cmd.log(f'{format_cmd} {par}') # e.g. 'mkfs.ext4 /dev/sda1'
write_status(ret_val)
if ret_val != 0:
pause = True
# TODO Btrfs: create subvolume, __snapshot etc.
# TODO Add LUKS disk encryption support
# Mounting
if not pause:
if fs_type != 'swap':
#if ans != 'Y': write_ln()
if opt == 'O':
write_ln()
write_msg(f'Where would you like to mount §7{par} §0in the new system (e.g. §3/var§0)? §7>> ')
mp = ''
mp = input().strip().lower() # e.g. '/var'
write_ln()
elif opt == 'R': mp = '/'
elif opt == 'B': mp = '/boot'
elif opt == 'H': mp = '/home'
elif opt == 'C': mp = '/pkgcache'
elif opt == 'E': mp = '/efi'
# TODO Prevent mounting to / when using NTFS etc.
if len(mp) > 0 and mp.startswith('/'): # Assume proper path
# TODO Don't add new line if not formatted
write_ln()
write_msg('Other §4optional §0mount options (e.g. §7noatime,nofail§0) >> ')
opts = ''
opts = input().strip().replace(' ', '') # e.g. 'noatime,nofail'
#opts = 'defaults' if len(opts) == 0 else f'defaults,{opts}'
write_ln()
write_msg(f'Mounting {par} to {mp}...', 1)
ret_val = mount_par(par, mp, opts) # e.g. 'mount /dev/sda1 /mnt/'
write_status(ret_val)
if ret_val != 0: pause = True
elif boot_mode == 'BIOS/CSM' and ((opt == 'R' and mbr_grub_dev == '') or opt == 'B'): # Update MBR GRUB device
# TODO: Fix NVMe / EMMC MBR installs (don't assume :-1 in par; nvme,emmc,...)
if par[-1:].isdigit(): par = par[:-1] # e.g. '/dev/sda1' => '/dev/sda'
mbr_grub_dev = par # e.g. '/dev/sda'
elif mp == '/pkgcache':
# TODO Update to support Btrfs
#write_ln()
write_msg('Checking partition filesystem compatibility for caching...', 1)
errors = Cmd.log(f'mkdir -p /mnt/pkgcache/pkgcache/aur/' + (cpu_identifier if optimize_cached_pkgs else ''))
errors += Cmd.log('touch /mnt/pkgcache/pkgcache/test-1:1.2.3.4-x86-64.pkg.tar.xz.part')
write_status(errors)
pkgcache_enabled = (errors == 0)
if pkgcache_enabled:
Cmd.log('rm -f /mnt/pkgcache/pkgcache/test-1:1.2.3.4-x86-64.pkg.tar.xz.part')
Cmd.log('cp /etc/pacman.conf /etc/pacman.conf.bak')
IO.replace_ln('/etc/pacman.conf', '#CacheDir', 'CacheDir = /mnt/pkgcache/pkgcache') # pkgcache on live env
write_msg('Enabling package cache on the partition...', 2)
else:
pause = True
Cmd.log('mv /etc/pacman.conf.bak /etc/pacman.conf')
IO.replace_ln('/etc/pacman.conf', 'CacheDir', '#CacheDir')
Cmd.log('cd && umount /mnt/pkgcache && rm -rf /mnt/pkgcache')
else:
write_ln()
write_msg('Mounting cancelled due to an invalid mountpoint.', 4)
pause = True
else:
write_ln()
write_msg(f'Enabling swap on {par}...', 1)
Cmd.suppress('swapoff ' + par) # try disabling existing swap
ret_val = Cmd.log('swapon ' + par) # e.g. 'swapon /dev/sda1'
write_status(ret_val)
if ret_val != 0:
pause = True
if pause:
write('\nPress ENTER to continue...')
input()
else:
time.sleep(0.15)
def write_par_mount(key='E', mount='/efi', device='/dev/sda1', condition=False, max_len=9, start_space_count=6):
if key == '':
key = ' '
write(' ' * start_space_count)
write(f'{key} {mount}')
if condition:
mount_len = len(mount)
if mount_len < max_len:
write(' ' * (max_len - mount_len))
if device == '' and len(mounts) > 0:
split_mounts = mounts.split(',')
for entry in split_mounts: # e.g. '/efi:/dev/sda1'
split_entry = entry.split(':') # e.g. '/efi', '/dev/sda1'
mount_compare = split_entry[0] # eg. '/efi'
if mount_compare == 'root':
mount_compare = '/'
if mount == mount_compare:
device = split_entry[1]
break
if device == '':
device = '/dev/null'
log(f"[setup.py:write_par_mount()] WARN: Mountpoint not found for mount '{mount}' on device '{device}', showing /dev/null instead...")
log(f"Mounts: '{mounts}'")
action = 'mounted as' if key != 'S' else 'enabled on'
write(f' §3({action} §7{device}§3)')
write_ln()
def list_used_pars(hide_guide=False):
global mounts, menu_visit_counter
mounts = ''