forked from RedBearAK/toshy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup_toshy.py
executable file
·2825 lines (2372 loc) · 125 KB
/
setup_toshy.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
import os
os.environ['PYTHONDONTWRITEBYTECODE'] = '1' # prevent this script from creating cache files
import re
import sys
import pwd
import grp
import random
import string
import signal
import shutil
import sqlite3
import zipfile
import argparse
import builtins
import datetime
import platform
import textwrap
import subprocess
from subprocess import DEVNULL, PIPE
from typing import Dict, Tuple, Optional
# local import
import lib.env as env
from lib.logger import debug, error, warn, info
from lib import logger
logger.FLUSH = True
# Save the original print function
original_print = builtins.print
# Override the print function
def print(*args, **kwargs):
kwargs['flush'] = True # Set flush to True
# original_print("Using custom print:", *args, **kwargs) # Call the original print
original_print(*args, **kwargs) # Call the original print
# Replace the built-in print with our custom print
builtins.print = print
if os.name == 'posix' and os.geteuid() == 0:
error("This app should not be run as root/superuser. Exiting.")
sys.exit(1)
def signal_handler(sig, frame):
"""Handle signals like Ctrl+C"""
if sig in (signal.SIGINT, signal.SIGQUIT):
# Perform any cleanup code here before exiting
# traceback.print_stack(frame)
print('\n')
debug(f'SIGINT or SIGQUIT received. Exiting.\n')
sys.exit(1)
if platform.system() != 'Windows':
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
signal.signal(signal.SIGUSR1, signal_handler)
signal.signal(signal.SIGUSR2, signal_handler)
else:
signal.signal(signal.SIGINT, signal_handler)
error(f'This is only meant to run on Linux. Exiting.')
sys.exit(1)
original_PATH_str = os.getenv('PATH')
if original_PATH_str is None:
print()
error(f"ERROR: PATH variable is not set. This is abnormal. Exiting.")
print()
sys.exit(1)
home_dir = os.path.expanduser('~')
trash_dir = os.path.join(home_dir, '.local', 'share', 'Trash')
this_file_path = os.path.realpath(__file__)
this_file_dir = os.path.dirname(this_file_path)
this_file_name = os.path.basename(__file__)
if trash_dir in this_file_path or '/trash/' in this_file_path.lower():
print()
error(f"Path to this file:\n\t{this_file_path}")
error(f"You probably did not intend to run this from the TRASH. See path. Exiting.")
print()
sys.exit(1)
home_local_bin = os.path.join(home_dir, '.local', 'bin')
run_tmp_dir = os.environ.get('XDG_RUNTIME_DIR') or '/tmp'
good_path_tmp_file = 'toshy_installer_says_path_is_good'
good_path_tmp_path = os.path.join(run_tmp_dir, good_path_tmp_file)
fix_path_tmp_file = 'toshy_installer_says_fix_path'
fix_path_tmp_path = os.path.join(run_tmp_dir, fix_path_tmp_file)
# set a standard path for duration of script run, to avoid issues with user customized paths
os.environ['PATH'] = '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin'
# deactivate Python virtual environment, if one is active, to avoid issues with sys.executable
if sys.prefix != sys.base_prefix:
os.environ["VIRTUAL_ENV"] = ""
sys.path = [p for p in sys.path if not p.startswith(sys.prefix)]
sys.prefix = sys.base_prefix
# Check if 'sudo' command is available to user
if not shutil.which('sudo'):
print("Error: 'sudo' not found. Installer will fail without it. Exiting.")
sys.exit(1)
do_not_ask_about_path = None
if home_local_bin in original_PATH_str:
with open(good_path_tmp_path, 'a') as file:
file.write('Nothing to see here.')
# subprocess.run(['touch', path_good_tmp_path])
do_not_ask_about_path = True
else:
debug("Home user local bin not part of PATH string.")
# do the 'else' of creating 'path_fix_tmp_path' later in function that prompts user
# system Python version
py_ver_mjr, py_ver_mnr = sys.version_info[:2]
py_interp_ver_tup = (py_ver_mjr, py_ver_mnr)
py_pkg_ver_str = f'{py_ver_mjr}{py_ver_mnr}'
class InstallerSettings:
"""Set up variables for necessary information to be used by all functions"""
def __init__(self) -> None:
sep_reps = 80
self.sep_char = '='
self.separator = self.sep_char * sep_reps
self.override_distro = None
self.DISTRO_NAME = None
self.DISTRO_VER: str = ""
self.VARIANT_ID = None
self.SESSION_TYPE = None
self.DESKTOP_ENV = None
self.DE_MAJ_VER: str = ""
self.distro_mjr_ver: str = ""
self.distro_mnr_ver: str = ""
self.systemctl_present = shutil.which('systemctl') is not None
self.init_system = None
self.pkgs_for_distro = None
self.qdbus = 'qdbus-qt5' if shutil.which('qdbus-qt5') else 'qdbus'
# current stable Python release version (TODO: update when needed):
# 3.11 Release Date: Oct. 24, 2022
self.curr_py_rel_ver_mjr = 3
self.curr_py_rel_ver_mnr = 11
self.curr_py_rel_ver_tup = (self.curr_py_rel_ver_mjr, self.curr_py_rel_ver_mnr)
self.curr_py_rel_ver_str = f'{self.curr_py_rel_ver_mjr}.{self.curr_py_rel_ver_mnr}'
self.py_interp_ver = f'{py_ver_mjr}.{py_ver_mnr}'
self.py_interp_path = shutil.which('python3')
self.toshy_dir_path = os.path.join(home_dir, '.config', 'toshy')
self.db_file_name = 'toshy_user_preferences.sqlite'
self.db_file_path = os.path.join(self.toshy_dir_path, self.db_file_name)
self.backup_succeeded = None
self.existing_cfg_data = None
self.existing_cfg_slices = None
self.venv_path = os.path.join(self.toshy_dir_path, '.venv')
self.keyszer_tmp_path = os.path.join(this_file_dir, 'keyszer-temp')
self.keyszer_branch = 'device_grab_fix'
# self.keyszer_branch = 'environ_api_hyprland'
self.keyszer_url = 'https://github.com/RedBearAK/keyszer.git'
self.keyszer_clone_cmd = f'git clone -b {self.keyszer_branch} {self.keyszer_url}'
self.input_group = 'input'
self.user_name = pwd.getpwuid(os.getuid()).pw_name
self.barebones_config = None
self.autostart_tray_icon = True
self.skip_native = None
self.fancy_pants = None
self.tweak_applied = None
self.remind_extensions = None
self.should_reboot = None
self.run_tmp_dir = run_tmp_dir
self.reboot_tmp_file = f"{self.run_tmp_dir}/toshy_installer_says_reboot"
self.reboot_ascii_art = textwrap.dedent("""
██████ ███████ ██████ ██████ ██████ ████████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██████ █████ ██████ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ███████ ██████ ██████ ██████ ██ ██
""")
def safe_shutdown(exit_code: int):
"""do some stuff on the way out"""
# good place to do some file cleanup?
#
# invalidate the sudo ticket, don't leave system in "superuser" state
subprocess.run(['sudo', '-k'])
print() # avoid crowding the prompt on exit
sys.exit(exit_code)
def show_reboot_prompt():
"""show the big ASCII reboot prompt"""
print()
print()
print()
print(cnfg.separator)
print(cnfg.separator)
print(cnfg.reboot_ascii_art)
print(cnfg.separator)
print(cnfg.separator)
def get_environment_info():
"""Get back the distro name (ID), distro version, session type and desktop
environment from `env.py` module"""
print(f'\n§ Getting environment information...\n{cnfg.separator}')
known_init_systems = {
'systemd': 'Systemd',
'init': 'SysVinit',
'upstart': 'Upstart',
'openrc': 'OpenRC',
'runit': 'Runit',
'initng': 'Initng'
}
try:
with open('/proc/1/comm', 'r') as f:
cnfg.init_system = f.read().strip()
except (PermissionError, FileNotFoundError, OSError) as init_check_err:
error(f'ERROR: Problem when checking init system:\n\t{init_check_err}')
if cnfg.init_system:
if cnfg.init_system in known_init_systems:
init_sys_full_name = known_init_systems[cnfg.init_system]
print(f"The active init system is: '{cnfg.init_system}' ({init_sys_full_name})")
else:
print(f"Init system process unknown: '{cnfg.init_system}'")
else:
error("ERROR: Init system (process 1) could not be determined. (See above error.)")
print() # blank line after init system message
env_info_dct = env.get_env_info()
# Avoid casefold() errors by converting all to strings
if cnfg.override_distro:
cnfg.DISTRO_NAME = str(cnfg.override_distro).casefold()
else:
cnfg.DISTRO_NAME = str(env_info_dct.get('DISTRO_NAME', 'keymissing')).casefold()
cnfg.DISTRO_VER = str(env_info_dct.get('DISTRO_VER', 'keymissing')).casefold()
cnfg.VARIANT_ID = str(env_info_dct.get('VARIANT_ID', 'keymissing')).casefold()
cnfg.SESSION_TYPE = str(env_info_dct.get('SESSION_TYPE', 'keymissing')).casefold()
cnfg.DESKTOP_ENV = str(env_info_dct.get('DESKTOP_ENV', 'keymissing')).casefold()
cnfg.DE_MAJ_VER = str(env_info_dct.get('DE_MAJ_VER', 'keymissing')).casefold()
# split out the major version from the minor version, if there is one
distro_ver_parts = cnfg.DISTRO_VER.split('.') if cnfg.DISTRO_VER else []
cnfg.distro_mjr_ver = distro_ver_parts[0] if distro_ver_parts else 'NO_VER'
cnfg.distro_mnr_ver = distro_ver_parts[1] if len(distro_ver_parts) > 1 else 'no_mnr_ver'
debug('Toshy installer sees this environment:'
f"\n\t DISTRO_NAME = '{cnfg.DISTRO_NAME}'"
f"\n\t DISTRO_VER = '{cnfg.DISTRO_VER}'"
f"\n\t VARIANT_ID = '{cnfg.VARIANT_ID}'"
f"\n\t SESSION_TYPE = '{cnfg.SESSION_TYPE}'"
f"\n\t DESKTOP_ENV = '{cnfg.DESKTOP_ENV}'"
f"\n\t DE_MAJ_VER = '{cnfg.DE_MAJ_VER}'"
# '\n', ctx='EV')
'', ctx='EV')
def fancy_str(text, color_name, *, bold=False):
"""
Return text wrapped in the specified color code.
:param text: Text to be colorized.
:param color_name: Natural name of the color.
:param bold: Boolean to indicate if text should be bold.
:return: Colorized string if terminal likely supports it, otherwise the original string.
"""
color_codes = { 'red': '31', 'green': '32', 'yellow': '33', 'blue': '34',
'magenta': '35', 'cyan': '36', 'white': '37', 'default': '0'}
if os.getenv('COLORTERM') and color_name in color_codes:
bold_code = '1;' if bold else ''
return f"\033[{bold_code}{color_codes[color_name]}m{text}\033[0m"
else:
return text
def call_attn_to_pwd_prompt_if_sudo_tkt_exp():
"""Utility function to emphasize the sudo password prompt"""
try:
subprocess.run( ['sudo', '-n', 'true'], stdout=DEVNULL, stderr=DEVNULL, check=True)
except subprocess.CalledProcessError:
# sudo ticket not valid, requires a password, so get user attention
print()
print(fancy_str(' ---------------------------------------- ', 'blue', bold=True))
print(fancy_str(' -- SUDO PASSWORD REQUIRED TO CONTINUE -- ', 'blue', bold=True))
print(fancy_str(' ---------------------------------------- ', 'blue', bold=True))
print()
def enable_prompt_for_reboot():
"""Utility function to make sure user is reminded to reboot if necessary"""
cnfg.should_reboot = True
if not os.path.exists(cnfg.reboot_tmp_file):
os.mknod(cnfg.reboot_tmp_file)
def show_task_completed_msg():
"""Utility function to show a standard message after each major section completes"""
print(fancy_str(' >> Task completed successfully << ', 'green', bold=True))
def dot_Xmodmap_warning():
"""Check for '.Xmodmap' file in user's home folder, show warning about mod key remaps"""
xmodmap_file_path = os.path.join(home_dir, '.Xmodmap')
if os.path.isfile(xmodmap_file_path):
print()
print(f'{cnfg.separator}')
print(f'{cnfg.separator}')
warn_str = "\t WARNING: You have an '.Xmodmap' file in your home folder!!!"
print(fancy_str(warn_str, "red"))
print(f' This can cause confusing PROBLEMS if you are remapping any modifier keys!')
print(f'{cnfg.separator}')
print(f'{cnfg.separator}')
print()
secret_code = ''.join(random.choice(string.ascii_letters) for _ in range(4))
response = input(
f"You must take responsibility for the issues an '.Xmodmap' file may cause."
f"\n\n\t If you understand, enter the secret code '{secret_code}': "
)
if response == secret_code:
print()
info("Good code. User has taken responsibility for '.Xmodmap' file. Proceeding...\n")
else:
print()
error("Code does not match! Try the installer again after dealing with '.Xmodmap'.")
safe_shutdown(1)
def ask_is_distro_updated():
"""Ask user if the distro has recently been updated"""
print()
debug('NOTICE: It is ESSENTIAL to have your system completely updated.', ctx="!!")
print()
response = input('Have you updated your system recently? [y/N]: ')
if response not in ['y', 'Y']:
print()
error("Try the installer again after you've done a full system update. Exiting.")
safe_shutdown(1)
def ask_add_home_local_bin():
"""
Check if `~/.local/bin` is in original PATH. Done earlier in script.
Ask user if it is OK to add the `~/.local/bin` folder to the PATH permanently.
Create temp file to allow bincommands script to bypass question.
"""
if do_not_ask_about_path:
pass
else:
print()
response = input('The "~/.local/bin" folder is not in PATH. OK to add it? [Y/n]: ') or 'y'
if response in ['y', 'Y']:
# create temp file that will get script to add local bin to path without asking
with open(fix_path_tmp_path, 'a') as file:
file.write('Nothing to see here.')
def elevate_privileges():
"""Elevate privileges early in the installer process"""
call_attn_to_pwd_prompt_if_sudo_tkt_exp()
subprocess.run(['sudo', 'bash', '-c', 'echo -e "\nUsing elevated privileges..."'], check=True)
#####################################################################################################
### START OF NATIVE PACKAGE INSTALLER SECTION
#####################################################################################################
distro_groups_map = {
# separate references for RHEL types versus Fedora types
'fedora-based': ["fedora", "fedoralinux", "ultramarine", "nobara"],
'rhel-based': ["rhel", "almalinux", "rocky", "eurolinux", "centos"],
# separate references for Fedora immutables using rpm-ostree
'fedora-immutables': ["silverblue-experimental", "kinoite-experimental"],
# separate references for Tumbleweed types versus Leap types
'tumbleweed-based': ["opensuse-tumbleweed"],
'leap-based': ["opensuse-leap"],
'microos-based': ["opensuse-microos", "opensuse-aeon", "opensuse-kalpa"],
'mandriva-based': ["openmandriva"],
'ubuntu-based': ["ubuntu", "mint", "pop", "elementary", "neon", "tuxedo", "zorin"],
'debian-based': ["deepin", "lmde", "peppermint", "debian", "kali", "q4os"],
'arch-based': ["arch", "arcolinux", "endeavouros", "garuda", "manjaro"],
'solus-based': ["solus"],
'void-based': ["void"],
# 'kaos-based': ["kaos"],
# Add more as needed...
}
pkg_groups_map = {
# NOTE: Do not add 'gnome-shell-extension-appindicator' to Fedora/RHELs.
# This will install extension but requires logging out of GNOME to activate.
'fedora-based': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"evtest",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
"wayland-devel",
"xset",
"zenity"],
'rhel-based': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
"xset",
"zenity"],
'fedora-immutables': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"evtest",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
"xset",
"zenity"],
# NOTE: for openSUSE (Tumbleweed, not applicable to Leap):
# How to get rid of the need to use specific version numbers in packages:
# pkgconfig(packagename)>=N.nn (version symbols optional)
# How to query a package to see what the equivalent pkgconfig(packagename) syntax would be:
# rpm -q --provides packagename | grep -i pkgconfig
'tumbleweed-based': ["cairo-devel",
"dbus-1-daemon", "dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools",
# f"python{py_pkg_ver_str}-dbus-python-devel",
"python3-dbus-python-devel",
# f"python{py_pkg_ver_str}-devel",
"python3-devel",
# f"python{py_pkg_ver_str}-tk",
"python3-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],
# TODO: update Leap Python package versions as it makes newer Python available
'leap-based': ["cairo-devel",
"dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools",
"python3-dbus-python-devel",
"python311",
"python311-devel",
"python311-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],
# NOTE: This is a copy of Tumbleweed-based package list! For use with 'transactional-update'.
# But this needs to use the versioned package names because we are checking with 'rpm -q'.
'microos-based': ["cairo-devel",
"dbus-1-daemon", "dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools",
f"python{py_pkg_ver_str}-dbus-python-devel",
# "python3-dbus-python-devel",
f"python{py_pkg_ver_str}-devel",
# "python3-devel",
f"python{py_pkg_ver_str}-tk",
# "python3-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],
'mandriva-based': ["cairo-devel",
"dbus-daemon", "dbus-devel",
"git", "gobject-introspection-devel",
"lib64ayatana-appindicator3_1", "lib64ayatana-appindicator3-gir0.1",
"lib64cairo-gobject2", "lib64python-devel", "lib64systemd-devel",
"libnotify",
"python-dbus", "python-dbus-devel", "python-ensurepip", "python3-pip",
"task-devel", "tkinter",
"xset",
"zenity"],
# TODO: see if this needs "dbus-daemon" added as dependency (for containers)
'ubuntu-based': ["curl",
"git", "gir1.2-ayatanaappindicator3-0.1",
"input-utils",
"libcairo2-dev", "libdbus-1-dev", "libgirepository1.0-dev",
"libjpeg-dev", "libnotify-bin", "libsystemd-dev", "libwayland-dev",
"python3-dbus", "python3-dev", "python3-pip", "python3-tk",
"python3-venv",
"zenity"],
# TODO: see if this needs "dbus-daemon" added as dependency (for containers)
'debian-based': ["curl",
"git", "gir1.2-ayatanaappindicator3-0.1",
"input-utils",
"libcairo2-dev", "libdbus-1-dev", "libgirepository1.0-dev",
"libjpeg-dev", "libnotify-bin", "libsystemd-dev", "libwayland-dev",
"python3-dbus", "python3-dev", "python3-pip", "python3-tk",
"python3-venv",
"zenity"],
# TODO: see if this needs "dbus-daemon" added as dependency (for containers)
'arch-based': ["cairo",
"dbus",
"evtest",
"gcc", "git", "gobject-introspection",
"libappindicator-gtk3", "libnotify",
"pkg-config", "python", "python-dbus", "python-pip",
"systemd",
"tk",
"zenity"],
# TODO: see if this needs "dbus-daemon" added as dependency (for containers)
'solus-based': ["gcc", "git",
"libayatana-appindicator", "libcairo-devel", "libnotify",
"pip", "python3-dbus", "python3-devel", "python3-tkinter",
"python-dbus-devel", "python-gobject-devel",
"systemd-devel",
"zenity"],
'void-based': ["cairo-devel", "curl",
"dbus-devel",
"evtest",
"gcc", "git",
"libayatana-appindicator-devel", "libgirepository-devel", "libnotify",
"pkg-config", "python3-dbus", "python3-devel", "python3-pip",
"python3-pkgconfig", "python3-tkinter",
"wayland-devel", "wget",
"xset",
"zenity"],
'kaos-based': ["cairo",
"dbus",
"evtest",
"gcc", "git", "gobject-introspection",
"libappindicator-gtk3", "libnotify",
"pkg-config", "python", "python-dbus", "python-pip",
"systemd",
"tk",
"zenity"],
}
extra_pkgs_map = {
# Add a tuple with distro name (ID), major version (or None) and packages to be added...
# ('distro_name', '22'): ["pkg1", "pkg2", ...],
# ('distro_name', None): ["pkg1", "pkg2", ...],
}
remove_pkgs_map = {
# Add a tuple with distro name (ID), major version (or None) and packages to be removed...
# ('distro_name', '22'): ["pkg1", "pkg2", ...],
# ('distro_name', None): ["pkg1", "pkg2", ...],
('centos', '7'): ['dbus-daemon', 'gnome-shell-extension-appindicator'],
('deepin', None): ['input-utils'],
}
pip_pkgs = [
# pinning pygobject to 3.44.1 (or earlier) to get through install on RHEL 8.x and clones
"lockfile", "dbus-python", "systemd-python", "pygobject<=3.44.1", "tk",
"sv_ttk", "watchdog", "psutil", "hyprpy", "i3ipc", "pywayland", # "pywlroots",
# installing 'pywlroots' will require native pkg 'libxkbcommon-devel' (Fedora)
# TODO: Check on 'python-xlib' project by early-mid 2024 to see if this bug is fixed:
# [AttributeError: 'BadRRModeError' object has no attribute 'sequence_number']
# If the bug is fixed, remove pinning to v0.31 here:
# everything from 'inotify-simple' to 'six' is just to make `keyszer` install smoother
"inotify-simple", "evdev", "appdirs", "ordered-set", "python-xlib==0.31", "six"
]
def get_distro_names():
"""Utility function to return list of available distro names (IDs)"""
distro_list = []
for group in distro_groups_map.values():
distro_list.extend(group)
sorted_distro_list = sorted(distro_list)
prev_char: str = sorted_distro_list[0][0]
# start index with the initial letter
distro_index = prev_char.upper() + ": "
for distro in sorted_distro_list:
if distro[0] != prev_char:
# type hint to help out VSCode syntax highlighter
distro: str
# remove last comma and space from previous line
distro_index = distro_index[:-2]
# start a new line with new initial letter
distro_index += "\n\t" + distro[0].upper() + ": " + distro + ", "
prev_char = distro[0]
else:
distro_index += distro + ", "
# remove last comma and space from the final line
distro_index = distro_index[:-2]
return distro_index
def exit_with_invalid_distro_error(pkg_mgr_err=None):
"""Utility function to show error message and exit when distro is not valid"""
print()
error(f'ERROR: Installer does not know how to handle distro: "{cnfg.DISTRO_NAME}"')
if pkg_mgr_err:
error('ERROR: No valid package manager logic was encountered for this distro.')
print()
print(f'Try some options in "./{this_file_name} --help".')
print()
print(f'Maybe try one of these with "--override-distro" option:\n\n\t{get_distro_names()}')
safe_shutdown(1)
class DistroQuirksHandler:
"""Object to contain methods for prepping specific distro variants that
need some extra prep work before installing the native package list"""
def __init__(self) -> None:
pass
def handle_quirks_CentOS_7(self):
print('Doing prep/checks for CentOS 7...')
# pin 'evdev' pip package to version 1.6.1 for CentOS 7 to
# deal with ImportError and undefined symbol UI_GET_SYSNAME
global pip_pkgs
pip_pkgs = [pkg if pkg != "evdev" else "evdev==1.6.1" for pkg in pip_pkgs]
native_pkg_installer.check_for_pkg_mgr_cmd('yum')
yum_cmd_lst = ['sudo', 'yum', 'install', '-y']
if py_interp_ver_tup >= (3, 8):
print(f"Good, Python version is 3.8 or later: "
f"'{cnfg.py_interp_ver}'")
else:
try:
scl_repo = ['centos-release-scl']
subprocess.run(yum_cmd_lst + scl_repo, check=True)
py38_pkgs = [ 'rh-python38',
'rh-python38-python-devel',
'rh-python38-python-tkinter',
'rh-python38-python-wheel-wheel' ]
subprocess.run(yum_cmd_lst + py38_pkgs, check=True)
#
# set new Python interpreter version and path to reflect what was installed
cnfg.py_interp_path = '/opt/rh/rh-python38/root/usr/bin/python3.8'
cnfg.py_interp_ver = '3.8'
# avoid using systemd packages/services for CentOS
cnfg.systemctl_present = False
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: (CentOS 7-specific) Problem installing/enabling Python 3.8:'
f'\n\t{proc_err}')
safe_shutdown(1)
# use yum to install dnf package manager
try:
subprocess.run(yum_cmd_lst + ['dnf'], check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Failed to install DNF package manager.\n\t{proc_err}')
safe_shutdown(1)
def handle_quirks_CentOS_Stream_8(self):
print('Doing prep/checks for CentOS Stream 8...')
min_mnr_ver = cnfg.curr_py_rel_ver_mnr - 3 # check up to 2 vers before current
max_mnr_ver = cnfg.curr_py_rel_ver_mnr + 3 # check up to 3 vers after current
py_minor_ver_rng = range(max_mnr_ver, min_mnr_ver, -1)
if py_interp_ver_tup < cnfg.curr_py_rel_ver_tup:
print(f"Checking for appropriate Python version on system...")
for check_py_minor_ver in py_minor_ver_rng:
if shutil.which(f'python3.{check_py_minor_ver}'):
cnfg.py_interp_path = shutil.which(f'python3.{check_py_minor_ver}')
cnfg.py_interp_ver = f'3.{check_py_minor_ver}'
print(f'Found Python version {cnfg.py_interp_ver} available.')
break
else:
error( f'ERROR: Did not find any appropriate Python interpreter version.')
safe_shutdown(1)
try:
# for dbus-python
subprocess.run(['sudo', 'dnf', 'install', '-y',
f'python{cnfg.py_interp_ver}-devel'], check=True)
# for Toshy Preferences GUI app
subprocess.run(['sudo', 'dnf', 'install', '-y',
f'python{cnfg.py_interp_ver}-tkinter'], check=True)
except subprocess.CalledProcessError as proc_err:
error(f'ERROR: Problem installing necessary packages on CentOS Stream 8:'
f'\n\t{proc_err}')
safe_shutdown(1)
def handle_quirks_RHEL(self):
print('Doing prep/checks for RHEL-type distro...')
# for libappindicator-gtk3: sudo dnf install -y epel-release
try:
native_pkg_installer.check_for_pkg_mgr_cmd('dnf')
subprocess.run(['sudo', 'dnf', 'install', '-y', 'epel-release'], check=True)
subprocess.run(['sudo', 'dnf', 'makecache'], check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem while adding "epel-release" repo.\n\t{proc_err}')
safe_shutdown(1)
# Need to do this AFTER the 'epel-release' install
if cnfg.DISTRO_NAME != 'centos' and cnfg.distro_mjr_ver in ['8']:
# enable CRB repo on RHEL 8.x distros, but not CentOS Stream 8:
cmd_lst = ['sudo', '/usr/bin/crb', 'enable']
try:
subprocess.run(cmd_lst, check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem while enabling CRB repo.\n\t{proc_err}')
safe_shutdown(1)
#
# TODO: Add higher version if ever necessary (keep minimum 3.8)
potential_versions = ['3.14', '3.13', '3.12', '3.11', '3.10', '3.9', '3.8']
#
for version in potential_versions:
# check if the version is already installed
if shutil.which(f'python{version}'):
cnfg.py_interp_path = f'/usr/bin/python{version}'
cnfg.py_interp_ver = version
break
# try to install the corresponding packages
cmd_lst = ['sudo', 'dnf', 'install', '-y']
pkg_lst = [f'python{version}', f'python{version}-devel', f'python{version}-tkinter']
try:
subprocess.run(cmd_lst + pkg_lst, check=True)
# if the installation succeeds, set the interpreter path and version
cnfg.py_interp_path = f'/usr/bin/python{version}'
cnfg.py_interp_ver = version
break
# if the installation fails, continue with the next version
except subprocess.CalledProcessError:
print(f'No match for potential Python version {version}.')
continue
# this 'else' is part of the 'for' loop above, not an 'if' condition
else:
# if no suitable version was found, print an error message and exit
error('ERROR: Did not find any appropriate Python interpreter version.')
safe_shutdown(1)
if cnfg.distro_mjr_ver in ['9']:
#
# enable "CodeReady Builder" repo for 'gobject-introspection-devel' only on
# RHEL 9.x and CentOS Stream 9 (TODO: Add v10 if it uses the same command):
# sudo dnf config-manager --set-enabled crb
cmd_lst = ['sudo', 'dnf', 'config-manager', '--set-enabled', 'crb']
try:
subprocess.run(cmd_lst, check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem while enabling CRB repo:\n\t{proc_err}')
safe_shutdown(1)
class NativePackageInstaller:
"""Object to handle tasks related to installing native packages"""
def __init__(self) -> None:
pass
def check_for_pkg_mgr_cmd(self, pkg_mgr_cmd):
"""Make sure native package installer command exists before using it, or exit"""
call_attn_to_pwd_prompt_if_sudo_tkt_exp()
if not shutil.which(pkg_mgr_cmd):
print()
error(f'Package manager command ({pkg_mgr_cmd}) not available. Unable to continue.')
safe_shutdown(1)
def exit_with_pkg_install_error(self, proc_err):
"""shutdown with error message if there is a problem with installing package list"""
print()
error(f'ERROR: Problem installing package list for distro type:\n\t{proc_err}')
safe_shutdown(1)
def show_pkg_install_success_msg(self):
# Have something come out even if package list is empty (like Arch after initial run)
print('All necessary native distro packages are installed.')
def install_pkg_list(self, cmd_lst, pkg_lst):
"""Install packages using the given package manager command list and package list."""
# Extract the package manager command to check
pkg_mgr_cmd = next((cmd for cmd in cmd_lst if cmd != 'sudo'), None)
# If we couldn't extract the command, exit with an error
if not pkg_mgr_cmd:
error(f'No valid package manager command in provided command list:\n\t{cmd_lst}')
safe_shutdown(1)
call_attn_to_pwd_prompt_if_sudo_tkt_exp()
self.check_for_pkg_mgr_cmd(pkg_mgr_cmd)
# Execute the package installation command
try:
subprocess.run(cmd_lst + pkg_lst, check=True)
# self.show_pkg_install_success_msg()
except subprocess.CalledProcessError as proc_err:
self.exit_with_pkg_install_error(proc_err)
def install_distro_pkgs():
"""Install needed packages from list for distro type"""
print(f'\n\n§ Installing native packages for this distro type...\n{cnfg.separator}')
pkg_group = None
for group, distros in distro_groups_map.items():
if cnfg.DISTRO_NAME in distros:
pkg_group = group
break
if pkg_group is None:
print()
print(f"ERROR: No list of packages found for this distro: '{cnfg.DISTRO_NAME}'")
print(f'Installation cannot proceed without a list of packages. Sorry.')
print(f'Try some options in "./{this_file_name} --help"')
safe_shutdown(1)
cnfg.pkgs_for_distro = pkg_groups_map[pkg_group]
# Add extra packages for specific distros and versions
for version in [cnfg.distro_mjr_ver, None]:
distro_key = (cnfg.DISTRO_NAME, version)
if distro_key in extra_pkgs_map:
cnfg.pkgs_for_distro.extend(extra_pkgs_map[distro_key])
# Remove packages for specific distros and versions
for version in [cnfg.distro_mjr_ver, None]:
distro_key = (cnfg.DISTRO_NAME, version)
if distro_key in remove_pkgs_map:
for pkg in remove_pkgs_map[distro_key]:
if pkg in cnfg.pkgs_for_distro:
cnfg.pkgs_for_distro.remove(pkg)
# Filter out systemd packages if if systemctl is not present
cnfg.pkgs_for_distro = [
pkg for pkg in cnfg.pkgs_for_distro
if cnfg.systemctl_present or 'systemd' not in pkg
]
transupd_distros = [] # 'transactional-update': openSUSE MicroOS/Aeon/Kalpa
rpmostree_distros = [] # 'rpm-ostree': Fedora atomic/immutables
dnf_distros = [] # 'dnf': Fedora/RHEL/OpenMandriva
zypper_distros = [] # 'zypper': openSUSE Tumbleweed/Leap
apt_distros = [] # 'apt': Debian/Ubuntu
pacman_distros = [] # 'pacman': Arch, BTW
eopkg_distros = [] # 'eopkg': Solus
xbps_distros = [] # 'xbps-install': Void
# assemble specific pkg mgr distro lists
try:
transupd_distros += distro_groups_map['microos-based']
rpmostree_distros += distro_groups_map['fedora-immutables']
dnf_distros += distro_groups_map['fedora-based']
dnf_distros += distro_groups_map['rhel-based']
dnf_distros += distro_groups_map['mandriva-based']
zypper_distros += distro_groups_map['tumbleweed-based']
zypper_distros += distro_groups_map['leap-based']
apt_distros += distro_groups_map['ubuntu-based']
apt_distros += distro_groups_map['debian-based']
pacman_distros += distro_groups_map['arch-based']
eopkg_distros += distro_groups_map['solus-based']
xbps_distros += distro_groups_map['void-based']
except (KeyError, TypeError) as key_err:
print()
error(f'Problem setting up package manager distro lists:\n\t{key_err}')
safe_shutdown(1)
# create the quirks handler object
quirks_handler = DistroQuirksHandler()
###########################################################################
### TRANSACTIONAL-UPDATE DISTROS ########################################
###########################################################################
def install_on_transupd_distro():
"""utility function that gets dispatched for distros that use Transactional-Update"""
if cnfg.DISTRO_NAME in distro_groups_map['microos-based']:
print('Distro is openSUSE MicroOS/Aeon/Kalpa immutable. Using "transactional-update".')
# Filter out packages that are already installed
filtered_pkg_lst = []
for pkg in cnfg.pkgs_for_distro:
result = subprocess.run(["rpm", "-q", pkg], stdout=PIPE, stderr=PIPE)
if result.returncode != 0:
filtered_pkg_lst.append(pkg)
else:
print(fancy_str(f"Package '{pkg}' is already installed. Skipping.", "green"))
if filtered_pkg_lst:
print(f'Packages left to install:\n{filtered_pkg_lst}')
cmd_lst = ['sudo', 'transactional-update', '--non-interactive', 'pkg', 'in']
native_pkg_installer.install_pkg_list(cmd_lst, filtered_pkg_lst)
# might as well take care of user group and udev here, if rebooting is necessary.
verify_user_groups()
install_udev_rules()
show_reboot_prompt()
print()
print('###############################################################################')
print('############ WARNING: Toshy setup is NOT yet complete! ############')
print('########### This distro type uses "transactional-update". ###########')
print('########## You MUST reboot now to make native packages available. ##########')
print('######### After REBOOTING, run the Toshy setup script a second time. #########')
print('###############################################################################')
safe_shutdown(0)
else:
print('All needed packages are already available. Continuing setup...')
###########################################################################
### RPM-OSTREE DISTROS ##################################################
###########################################################################
def install_on_rpmostree_distro():
"""utility function that gets dispatched for distros that use RPM-OSTree"""
if cnfg.DISTRO_NAME in distro_groups_map['fedora-immutables']:
print('Distro is Fedora-type immutable. Using "rpm-ostree" instead of DNF.')
# Filter out packages that are already installed
filtered_pkg_lst = []
for pkg in cnfg.pkgs_for_distro:
result = subprocess.run(["rpm", "-q", pkg], stdout=PIPE, stderr=PIPE)
if result.returncode != 0:
filtered_pkg_lst.append(pkg)
else:
print(fancy_str(f"Package '{pkg}' is already installed. Skipping.", "green"))
if filtered_pkg_lst:
cmd_lst = ['sudo', 'rpm-ostree', 'install', '--idempotent',
'--allow-inactive', '--apply-live', '-y']
native_pkg_installer.install_pkg_list(cmd_lst, filtered_pkg_lst)
###########################################################################
### DNF DISTROS #########################################################
###########################################################################
def install_on_dnf_distro():
"""Utility function that gets dispatched for distros that use DNF package manager."""
call_attn_to_pwd_prompt_if_sudo_tkt_exp()
# Define helper functions for specific distro installations
def install_on_mandriva_based():
cmd_lst = ['sudo', 'dnf', 'install', '-y']
native_pkg_installer.install_pkg_list(cmd_lst, cnfg.pkgs_for_distro)
def install_on_rhel_based():
if cnfg.DISTRO_NAME == 'centos' and cnfg.distro_mjr_ver == '7':
quirks_handler.handle_quirks_CentOS_7()
if cnfg.DISTRO_NAME == 'centos' and cnfg.distro_mjr_ver == '8':
quirks_handler.handle_quirks_CentOS_Stream_8()
quirks_handler.handle_quirks_RHEL()
cmd_lst = ['sudo', 'dnf', 'install', '-y']
native_pkg_installer.install_pkg_list(cmd_lst, cnfg.pkgs_for_distro)
def install_on_fedora_based():
# TODO: insert check to see if Fedora distro is actually immutable/atomic (rpm-ostree)
cmd_lst = ['sudo', 'dnf', 'install', '-y']
native_pkg_installer.install_pkg_list(cmd_lst, cnfg.pkgs_for_distro)
# Dispatch installation sub-function based on DNF distro type
if cnfg.DISTRO_NAME in distro_groups_map['mandriva-based']:
install_on_mandriva_based()
elif cnfg.DISTRO_NAME in distro_groups_map['rhel-based']:
install_on_rhel_based()
elif cnfg.DISTRO_NAME in distro_groups_map['fedora-based']:
install_on_fedora_based()