Repository navigation
Expand file tree
/
Copy pathopencore-bootlinuxer.sh
More file actions
2079 lines (1898 loc) · 88.6 KB
/
Copy pathopencore-bootlinuxer.sh
File metadata and controls
2079 lines (1898 loc) · 88.6 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
#!/usr/bin/env bash
# OpenCore Bootlinuxer by BecabDev
# Made with love in Cannes
set -uo pipefail
BRAND="OpenCore Bootlinuxer by BecabDev"
VERSION="1.1.0"
STATE_DIR=/var/lib/opencore-bootlinuxer
STATE_FILE=$STATE_DIR/state.env
BACKUP_DIR=$STATE_DIR/backup
HOOK=/etc/grub.d/99_opencore
SYNC_NAME=opencore-bootlinuxer-sync
SYNC_PATH=/etc/systemd/system/$SYNC_NAME.path
SYNC_SERVICE=/etc/systemd/system/$SYNC_NAME.service
SYNC_SCRIPT=$STATE_DIR/opencore-bootlinuxer.sh
LOCK_FILE=/run/opencore-bootlinuxer.lock
SELF=$(readlink -f "${BASH_SOURCE[0]}")
LANG_UI=""; ESP=""; BOOT_EXISTED=0; ORIG_BOOTORDER=""; OC_BOOTNUM=""; COMPAT=0; GRUBDIR=""
GRUB_CFG=""; NO_SAVE=0
UI_RESULT=""; NONINT=0; TOOLS_ROOT=""; APPLY_COUNT=0
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
TUI="$WORK/tui.py"
C_G=$'\e[32m'; C_Y=$'\e[33m'; C_B=$'\e[1m'; C_0=$'\e[0m'
#translations
declare -A FR EN
def() { FR[$1]=$2; EN[$1]=$3; }
t() {
local k=$1 fmt; shift
if [ "$LANG_UI" = en ]; then fmt=${EN[$k]-$k}; else fmt=${FR[$k]-$k}; fi
# shellcheck disable=SC2059
printf -- "$fmt" "$@"
}
def yes "Oui" "Yes"
def no "Non" "No"
def btn_ok "Ok" "Ok"
def btn_cancel "Annuler" "Cancel"
def hint_menu "Haut/bas : naviguer Entrée/clic : valider Echap : quitter" \
"Up/Down: move Enter/click: select Escape: quit"
def hint_check "Haut/Bas : naviguer Espace/clic : cocher a : tout Entrée : valider Échap : annuler" \
"Up/Down: move Space/click: toggle a: all Enter: confirm Escape: cancel"
def hint_input "Entrée : valider Échap : annuler" "Enter: confirm Escape: cancel"
def hint_msg "Entrée/clic : continuer Haut/Bas : défiler" "Enter/click: continue Up/Down: scroll"
def done_title "Terminé" "Done"
def err_title "Erreur" "Error"
def warn_title "Attention" "Warning"
def lang_sub "Sélectionnez la langue de l'interface.\nChoose the interface language." \
"Choose the interface language.\nSélectionnez la langue de l'interface."
def lang_title "Langue/language" "Language/Langue"
def menu_title "Menu principal" "Main menu"
def menu_sub "Partition efi (ESP) : %s" "Efi partition (ESP): %s"
def m1 "Installer/mettre à jour OpenCore" "Install / update OpenCore"
def m2 "Customiser le bootloader" "Customize the bootloader"
def m3 "Mode compatibilité : GRUB dans EFI/BOOT" "Compatibility mode: GRUB in EFI/BOOT"
def m4 "Paramètres OpenCore" "OpenCore settings"
def m5 "Afficher l'état du bootloader" "Show bootloader status"
def m6 "Désinstaller" "Uninstall"
def m7 "Langue / Language" "Language / Langue"
def m0 "Quitter" "Quit"
def need_root "Ce script doit être lancé avec les droits root (sudo).\n\nRelancez-le avec :\n\n sudo ./%s" \
"This script must be run with superuser rights.\n\nRun it again with:\n\n sudo ./%s"
def need_tty "Ce script nécessite un terminal interactif" "This script needs an interactive terminal"
def need_curses "Le module python curses est requis (paquet python3)" "The Python curses module is required (python3 package)"
def not_uefi "Système non démarré en UEFI : OpenCore ne fonctionne pas sur les systèmes legacy" "System not booted in UEFI mode: OpenCore does not work on legacy systems"
def esp_title "Partition EFI introuvable" "EFI partition not found"
def esp_prompt "Point de montage de la partition EFI :" "Mount point of the EFI partition :"
def esp_nomount "%s n'est pas un point de montage" "%s is not a mount point"
def sb_warn "Secure Boot est activé : OpenCore ne démarrera pas tant qu'il n'est pas désactivé dans le firmware.\n\nContinuer quand même ?" \
"Secure Boot is enabled: OpenCore will not start until it is disabled in the firmware.\n\nContinue anyway?"
def deps_inst "Installation des dépendances curl unzip efibootmgr python3" "Installing dependencies curl unzip efibootmgr python3"
def deps_pm "Gestionnaire de paquets inconnu : installez curl, unzip, efibootmgr et python3" "Unknown package manager: install curl, unzip, efibootmgr and python3"
def old_title "Installation existante" "Existing installation"
def old_prompt "Une installation d'OpenCore existe déjà (effectuée hors de ce script).\nDossier contenant l'ancien EFI/BOOT à restaurer à la désinstallation (vide = aucun) :" \
"An OpenCore installation already exists (made outside this script).\nFolder containing the original EFI/BOOT to restore on uninstall (empty = none):"
def dir_nf "Dossier introuvable : %s" "Folder not found: %s"
def bk_fail "Sauvegarde impossible" "Backup failed"
def bk_done "Sauvegarde créée dans %s" "Backup created in %s"
def space_low "Moins de 30 Mo libres sur l'ESP" "Less than 30 MB free on the ESP"
def to_title "Délai de démarrage" "Boot timeout"
def to_prompt "Délai avant démarrage automatique, en secondes (0 = attendre indéfiniment) :" "Delay before automatic boot, in seconds (0 = wait forever):"
def gh_search "Recherche de la dernière version d'OpenCore, veuillez patienter." "Looking for the latest OpenCore release, please wait."
def gh_fail "GitHub injoignable" "GitHub unreachable"
def oc_ver "OpenCore %s trouvé" "OpenCore %s found"
def dl_oc_fail "Téléchargement OpenCore impossible." "OpenCore download failed."
def dl_res_fail "Téléchargement des ressources impossible" "Resources download failed"
def cp_fail "Copie impossible : %s" "Copy failed : %s"
def cfg_exists "Une config.plist existe déjà.\nLa régénérer avec les réglages sûrs pour Linux ?" "A config.plist already exists.\nRegenerate it with Linux safe settings?"
def fw_fail "Création de l'entrée firmware impossible, avez-vous les droits nécessaires ?" "Could not create the firmware boot entry, do you have the necessary rights ?"
def fw_renamed "Ancienne entrée firmware Boot%s supprimée (renommage)." "Old firmware entry Boot%s removed (renaming)."
def fw_first_t "Ordre de démarrage" "Boot order"
def fw_first_q "Placer %s en premier dans l'ordre de démarrage ?" "Put \"%s\" first in the boot order ?"
def install_ok "OpenCore est installé.\nEntrée firmware : %s" "OpenCore is installed.\nFW entry: %s"
def no_oc "Installez d'abord OpenCore (option 1)" "Install OpenCore first (option 1)"
def no_grub "Aucun GRUB (grubx64.efi) trouvé dans l'ESP : import impossible (systemd-boot ?)" "No GRUB (grubx64.efi) found in the ESP: cannot continue (systemd-boot?)"
def no_cfg "grub.cfg introuvable dans /boot/grub ou /boot/grub2" "grub.cfg not found in /boot/grub or /boot/grub2"
def multi_t "Plusieurs GRUB trouvés" "Many GRUB installs found"
def multi_s "Plusieurs installations de GRUB ont été trouvées dans l'ESP. Laquelle utiliser ?" "Several GRUB installations were found in the ESP. Which one to use?"
def no_stub "Pas de grub.cfg stub dans %s (GRUB à préfixe embarqué, type Arch).\nSeule l'entrée principale sera ajoutée" \
"No stub grub.cfg in %s (GRUB with an embedded prefix, Arch-like).\nOnly the main entry will be added"
def bls_warn "Cette distribution utilise les entrées BLS Fedora : la liste sera incomplète" "This distribution uses Fedora BLS entries: the list will be incomplete"
def no_entries "Aucune entrée trouvée dans la configuration GRUB" "No entry found in the GRUB configuration"
def tag_live "[sous-menu GRUB : toujours à jour]" "[GRUB submenu : always up to date]"
def tag_mem "[memtest]" "[memtest]"
def tag_kernel "[noyau précis, obsolète après une mise à jour]" "[specific kernel, outdated after an update]"
def pv_title "Aperçu" "Preview"
def pv_sub "Voici le bootloader tel qu'il s'affichera au démarrage. Choisissez une entrée puis masquez-la ou changez son logo. Les systèmes détectés automatiquement par OpenCore (type Windows) ne sont pas modifiables ici" \
"Here is the bootloader as it will appear at startup. Choose an entry then hide it or change its logo. Systems automatically detected by OpenCore like Windows are not editable here"
def hint_preview "Haut/Bas, Gauche/Droite ou Tab : choisir une entrée < / > : déplacer l'entrée|Espace : visible / masquée L : changer le logo D : ranger dans le sous-dossier « %s »|Entrée / clic : valider Échap : annuler" \
"Up/Down, Left/Right or Tab: select an entry < / >: move the entry|Space: show / hide L: change the logo D: put in the \"%s\" subfolder|Enter / click: confirm Esc: cancel"
def pv_on "visible" "visible"
def pv_off "masquée" "hidden"
def pv_empty "vide" "empty"
def pv_prev "Aperçu OpenCore :" "OpenCore shows:"
def pv_logo "Logo :" "Logo:"
def pv_auto "automatique" "automatic"
def pv_pos "Position :" "Position:"
def pv_has "Contient :" "Contains:"
def pv_pick "Logo de l'entrée" "Entry logo"
def pv_auto_opt "Automatique (logo de la distribution)" "Automatic (distribution logo)"
def imp_done2 "%s entrée(s) importée(s) dans le bootloader.\nRedémarrez pour tester." \
"%s entry(ies) imported into the bootloader.\nReboot to test."
def fo_name "Options supplémentaires" "More options"
def sp_insuf "Espace insuffisant sur l'ESP (%s ko nécessaires)." "Not enough space on the ESP (%s KB needed)."
def hook_inst "Installation du hook GRUB (%s) et régénération de la configuration" "Installing GRUB hook (%s) and regenerating the configuration"
def imp_done "%s entrée(s) importée(s) dans le bootloader.\nL'entrée « %s » ouvre le menu GRUB complet.\nRedémarrez pour tester." \
"%s entry(ies) imported into the bootloader.\nThe \"%s\" entry opens the full GRUB menu.\nReboot to test."
def cp_done "EFI/BOOT remplacé par GRUB" "EFI/BOOT replaced by GRUB"
def st_title "Etat" "Status"
def st_esp "Partition EFI : %s" "EFI partition : %s"
def st_oc_on "OpenCore : installé" "OpenCore : installed"
def st_oc_off "OpenCore : absent" "OpenCore : not installed"
def st_fw "Entrée firmware : %s" "Firmware entry : %s"
def st_fw_none "absente" "missing"
def st_tools "Entrées importées : %s" "Imported entries : %s"
def st_hook_on "Hook GRUB : présent" "GRUB hook : present"
def st_hook_off "Hook GRUB : absent" "GRUB hook : absent"
def st_cp_on "Mode EFI/BOOT : activé" "EFI/BOOT mode : enabled"
def st_cp_off "Mode EFI/BOOT : inactif" "EFI/BOOT mode : disabled"
def st_bk "Sauvegardes : %s" "Backups : %s"
def un_title "Désinstallation" "Uninstall"
def un_warn "Ceci supprime OpenCore, les entrées importées et le hook GRUB et restaure l'état d'origine.\n\nContinuer ?" \
"This removes OpenCore, the imported entries and the GRUB hook and restores original state.\n\nContinue?"
def un_fw "Entrée firmware Boot%s supprimée." "Firmware entry Boot%s removed."
def un_ord_ok "Ordre de demarrage d'origine restauré" "Original boot order restored"
def un_ord_ko "Ordre de démarrage non restauré vérifie avec efibootmgr" "Boot order not restored check efibootmgr"
def un_hook "Hook GRUB supprimé" "GRUB hook removed"
def un_oc "Dossier EFI/OC supprimé" "EFI/OC folder removed"
def un_boot_ok "EFI/BOOT d'origine restauré" "Original EFI/BOOT restored"
def un_boot_rm "EFI/BOOT supprimé" "EFI/BOOT removed"
def un_manual "Une sauvegarde manuelle /root/EFI-BOOT-backup a eté trouvée.\nL'utiliser pour restaurer EFI/BOOT ?" \
"A manual backup /root/EFI-BOOT-backup was found.\nUse it to restore EFI/BOOT ?"
def un_delbk "Supprimer aussi les sauvegardes (%s) ?" "Also delete the backups (%s)?"
def un_done "Le système démarre de nouveau comme avant l'installation" "The system boots like it did before the installation"
def hint_dialog "Gauche/droite ou Tab : changer de bouton Entrée/clic : valider Haut/bas : défiler" \
"Left/right or Tab: switch button Enter/click: confirm Up/Down: scroll"
def quit "Quitter" "Quit"
def dep_title "Dépendances manquantes" "Missing dependencies"
def dep_missing "Il manque des outils nécessaires sur ce terminal :\n\n %s\n\nPaquets à installer : %s\n\nVoulez-vous les installer maintenant ?" \
"Some required tools are missing on this computer:\n\n %s\n\nPackages to install: %s\n\nDo you want to install them now ?"
def dep_install "Installer maintenant" "Install now"
def dep_nopm "Il manque des outils nécessaires sur ce terminal :\n\n %s\n\nAucun gestionnaire de paquets reconnu, installez les manuellement puis relancez le script" \
"Some required tools are missing on this computer:\n\n %s\n\nNo supported package manager found install them manually then run the script again"
def dep_still "Certaines dépendances sont toujours manquantes :\n\n %s\n\nL'installation a échoué ou le paquet porte un autre nom sur votre distribution" \
"Some dependencies are still missing\n\n %s\n\nThe installation failed or the package has another name on your distribution"
def set_title "Paramètres OpenCore" "OpenCore settings"
def set_sub "Sélectionnez un paramètre pour le modifier, les changements sont écrits dans config.plist (backup : config.plist.bak)" \
"Select a setting to change, changes are written in config.plist (backup: config.plist.bak)"
def s_timeout "Délai avant démarrage automatique : %s" "Automatic boot delay: %s"
def s_show "Afficher le sélecteur au démarrage : %s" "Show the picker at startup: %s"
def s_variant "Thème OpenCanopy : %s" "OpenCanopy theme: %s"
def s_pointer "Souris dans le sélecteur (beta) : %s" "Mouse in the picker (beta): %s"
def s_aux "Afficher les entrées importées (auxiliaires) : %s" "Show imported (auxiliary) entries: %s"
def s_res "Résolution de l'interface : %s" "Interface resolution: %s"
def s_scale "Échelle de l'interface : %s" "Interface scale: %s"
def s_reset "Rétablir les valeurs recommandées" "Restore recommended values"
def s_back "Retour" "Back"
def v_on "Activé" "On"
def v_off "Désactivé" "Off"
def v_auto "Automatique" "Automatic"
def v_secs "%s s" "%s s"
def v_forever "attendre indéfiniment" "wait forever"
def s_bad "Valeur invalide : %s" "Invalid value: %s"
def s_show_q "Afficher le sélecteur de démarrage ?\n\n(non : OpenCore démarre directement l'entrée par défaut sans afficher de menu)" \
"Show the boot picker ?\n\n(no: OpenCore boots the default entry directly, without showing menu)"
def s_variant_s "Choisissez le thème de l'interface OpenCanopy. Auto choisit selon le mode clair/sombre." \
"Choose the OpenCanopy interface theme. Auto follows the light/dark mode"
def s_pointer_q "Activer la souris dans le sélecteur de démarrage ?\n\n(Beta : dépend du firmware. En cas de comportement bizarre, le désactiver)" \
"Enable mouse in the boot picker ?\n\n(Beta: depends on the firmware. If it behaves strangely, disable it)"
def s_aux_q "Afficher les entrées importées dans le sélecteur ?\n\n(Non : elles sont masquées tant que vous n'appuyez pas sur la touche Espace.)" \
"Show the imported entries in the picker?\n\n(No: they stay hidden until you press the Space key.)"
def s_res_s "Choisissez la résolution de l'interface. Max utilise la résolution maximale de l'écran" \
"Choose the interface resolution. Max uses the screen's maximum resolution"
def s_res_cust "Personnalisée…" "Custom…"
def s_res_p "Résolution (ex. 1920x1080 ou 1920x1080@32) :" "Resolution (e.g. 1920x1080 or 1920x1080@32):"
def s_scale_s "Choisissez l'échelle de l'interface (2x pour les écrans HiDPI / 4K)." "Choose the interface scale (2x for HiDPI / 4K screens)."
def s_reset_q "Rétablir les valeurs recommandées ?\n\nDélai 10 s, sélecteur affiché et graphique, thème automatique, souris activée, entrées visibles, résolution Max, échelle automatique." \
"Restore the recommended values?\n\n10 s delay, graphical picker shown, automatic theme, mouse on, entries visible, Max resolution, automatic scale."
def un_sum_head "Voici ce qui va être supprimé :" "Here is what will be removed:"
def un_sum_fw " - %s entrée(s) de démarrage OpenCore dans le firmware :\n %s" " - %s OpenCore boot entry(ies) in the firmware:\n %s"
def un_sum_fw0 " - aucune entrée OpenCore dans le firmware (rien à retirer)" " - no OpenCore entry in the firmware (nothing to remove)"
def un_sum_oc " - le dossier EFI/OC (%s) : OpenCore, thème, ressources et %s entrée(s) importée(s)" " - the EFI/OC folder (%s): OpenCore, theme, resources and %s imported entry(ies)"
def un_sum_hook " - le hook GRUB %s (la configuration GRUB sera régénérée)" " - the GRUB hook %s (the GRUB configuration will be regenerated)"
def un_sum_nv " - %s variable(s) NVRAM laissée(s) par OpenCore" " - %s NVRAM variable(s) left by OpenCore"
def un_sum_bk " - EFI/BOOT sera restauré à partir de la sauvegarde" " - EFI/BOOT will be restored from the backup"
def un_sum_bkrm " - EFI/BOOT (créé par ce script) sera supprimé" " - EFI/BOOT (created by this script) will be removed"
def un_sum_ord " - l'ordre de démarrage d'origine sera rétabli : %s" " - the original boot order will be restored: %s"
def un_sum_keep "Rien d'autre n'est impacté : vos entrées, grub et vos données restent intactes" \
"Nothing else is affected: your entries, grub and your data remain intact"
def un_confirm "Lancer la désinstallation complète ?" "Run the complete uninstall?"
def un_v_fw "Plus aucune entrée OpenCore dans le firmware" "No OpenCore entry left in the firmware"
def un_v_fw_ko "Des entrées OpenCore subsistent dans le firmware voir efibootmgr -v" "Some OpenCore entries remain in the firmware see efibootmgr -v"
def un_v_ord "Ordre de démarrage actuel : %s" "Current boot order : %s"
def un_v_nv "Variables NVRAM d'OpenCore supprimées" "OpenCore NVRAM variables removed"
def un_v_nv_ko "Certaines variables NVRAM n'ont pas pu être supprimées" "Some NVRAM variables could not be removed"
def un_v_hook "Hook GRUB supprimé et configuration GRUB régénérée" "GRUB hook removed and GRUB configuration regenerated"
def un_v_hook_ko "Le hook GRUB est encore présent dans la configuration : lancez update-grub" "The GRUB hook is still in the configuration: run update-grub"
def un_v_oc "Dossier EFI/OC supprimé de la partition EFI" "EFI/OC folder removed from the EFI partition"
def un_v_oc_ko "Le dossier EFI/OC n'a pas pu être supprimé" "The EFI/OC folder could not be removed"
def un_v_boot "EFI/BOOT restauré à son état d'origine" "EFI/BOOT restored to its original state"
def un_v_bootrm "EFI/BOOT supprimé (n'existait pas avant)" "EFI/BOOT removed (did not exist before)"
def un_v_boot0 "EFI/BOOT non restauré : aucune sauvegarde n'était disponible" "EFI/BOOT not restored: no backup was available"
def m_sync "Resynchroniser GRUB (après une mise à jour de GRUB)" "Resync GRUB (after a GRUB update)"
def m_tools "Outils : sauvegarde, diagnostic, synchro auto" "Tools: backup, diagnostics, auto-sync"
def lock_busy "Une autre instance du script est déjà en cours d'exécution." "Another instance of this script is already running."
def sync_title "Synchronisation de GRUB" "GRUB sync"
def sync_none "Rien à synchroniser : aucune entrée n'a encore été importée (option 2)." "Nothing to sync: no entry has been imported yet (option 2)."
def sync_done "GRUB resynchronisé (%s élément(s) mis à jour)." "GRUB resynced (%s item(s) updated)."
def menu_outsync "Attention : GRUB a changé depuis la dernière synchronisation. Lancez « Resynchroniser GRUB »." \
"Warning: GRUB changed since the last sync. Run \"Resync GRUB\"."
def st_ver "Version du script : %s" "Script version : %s"
def st_sync_ok "GRUB synchronisé : oui" "GRUB in sync : yes"
def st_sync_ko "GRUB synchronisé : NON (option « Resynchroniser »)" "GRUB in sync : NO (use \"Resync\")"
def st_auto_on "Synchro auto : activée" "Auto-sync : enabled"
def st_auto_off "Synchro auto : inactive" "Auto-sync : disabled"
def tl_title "Outils" "Tools"
def tl_sub "Choisissez une action." "Choose an action."
def tl_backup "Sauvegarder l'ESP maintenant" "Back up the ESP now"
def tl_report "Générer un rapport de diagnostic" "Generate a diagnostic report"
def tl_auto "Synchronisation automatique de GRUB (systemd) : %s" "Automatic GRUB sync (systemd): %s"
def tl_back "Retour" "Back"
def tl_bk_done "Sauvegarde de l'ESP créée :\n%s" "ESP backup created:\n%s"
def tl_bk_fail "La sauvegarde de l'ESP a échoué." "The ESP backup failed."
def tl_rep_done "Rapport enregistré dans :\n%s\n\nJoignez-le si vous demandez de l'aide." "Report saved in:\n%s\n\nAttach it when asking for help."
def tl_auto_q_on "Activer la synchronisation automatique ?\n\nUn service systemd surveille %s et relance la synchronisation dès que votre distribution met GRUB à jour." \
"Enable automatic sync?\n\nA systemd service watches %s and runs the sync as soon as your distribution updates GRUB."
def tl_auto_q_off "Désactiver la synchronisation automatique ?" "Disable automatic sync?"
def tl_auto_nosd "systemd n'est pas disponible sur ce système." "systemd is not available on this system."
def tl_auto_ko "Impossible d'activer le service systemd." "Could not enable the systemd service."
def tl_auto_on_ok "Synchronisation automatique activée." "Automatic sync enabled."
def tl_auto_off_ok "Synchronisation automatique désactivée." "Automatic sync disabled."
def s_picker "Sélecteur graphique (OpenCanopy) : %s" "Graphical picker (OpenCanopy): %s"
def s_picker_q "Utiliser le sélecteur graphique OpenCanopy ?\n\n(Non : sélecteur texte intégré, utile si l'affichage graphique pose problème)" \
"Use the graphical OpenCanopy picker?\n\n(No: built-in text picker, useful if graphics cause problems)"
def s_shell "Outil UEFI Shell (OpenShell) dans le sélecteur : %s" "UEFI Shell tool (OpenShell) in the picker: %s"
def s_shell_q "Ajouter l'outil UEFI Shell (OpenShell) au sélecteur ?\n\n(utile pour le dépannage, il apparaît en fin de liste)" \
"Add the UEFI Shell tool (OpenShell) to the picker?\n\n(useful for troubleshooting, it appears at the end of the list)"
def s_shell_no "OpenShell.efi est absent de la partition EFI.\nRelancez « Installer/mettre à jour OpenCore » (option 1) pour l'ajouter." \
"OpenShell.efi is missing from the EFI partition.\nRun \"Install / update OpenCore\" (option 1) to add it."
def un_sum_sync " - la synchronisation automatique de GRUB (service systemd)" " - the automatic GRUB sync (systemd service)"
def un_v_sync "Service de synchronisation automatique supprimé" "Automatic sync service removed"
# iu plein ecran
write_tui() {
cat > "$TUI" <<'PYEOF'
import argparse, curses, locale, os, sys, textwrap
os.environ.setdefault("ESCDELAY", "25")
try:
locale.setlocale(locale.LC_ALL, "")
except locale.Error:
pass
BTN5 = getattr(curses, "BUTTON5_PRESSED", 0x200000)
def parse():
p = argparse.ArgumentParser()
p.add_argument("mode"); p.add_argument("out")
p.add_argument("--brand", default=""); p.add_argument("--title", default="")
p.add_argument("--subtitle", default=""); p.add_argument("--hint", default="")
p.add_argument("--ok", default="OK"); p.add_argument("--cancel", default="Cancel")
p.add_argument("--default", type=int, default=0)
p.add_argument("--value", default=""); p.add_argument("--textfile", default="")
p.add_argument("--level", default="info")
p.add_argument("--iconsfile", default=""); p.add_argument("--autologo", default="Linux")
p.add_argument("--lab", action="append", default=[])
argv = sys.argv[1:]
items = []
if "--" in argv:
i = argv.index("--")
argv, items = argv[:i], argv[i + 1:]
a = p.parse_args(argv)
a.items = items
return a
def put(scr, y, x, s, attr=0):
h, w = scr.getmaxyx()
n = w - x - (1 if y == h - 1 else 0)
if y < 0 or y >= h or x < 0 or n <= 0:
return
try:
scr.addnstr(y, x, s, n, attr)
except curses.error:
pass
def wrap(text, width):
out = []
for para in text.split("\n"):
out += textwrap.wrap(para, max(10, width), replace_whitespace=False) or [""]
return out
def title_attr(level):
pair = {"error": 5, "warn": 3, "ok": 6}.get(level, 3)
return curses.color_pair(pair) | curses.A_BOLD
def draw_head(scr, a):
h, w = scr.getmaxyx()
scr.erase()
bar = curses.color_pair(1) | curses.A_BOLD
put(scr, 0, 0, " " * w, bar)
put(scr, 0, max(0, (w - len(a.brand)) // 2), a.brand, bar)
put(scr, 1, 2, a.title, title_attr(a.level))
lines = wrap(a.subtitle, w - 4) if a.subtitle else []
for i, line in enumerate(lines[:6]):
put(scr, 2 + i, 2, line)
return 2 + min(len(lines), 6) + 1
def footer(scr, a):
h, w = scr.getmaxyx()
attr = curses.color_pair(4)
put(scr, h - 1, 0, " " * w, attr)
put(scr, h - 1, 1, a.hint, attr)
def list_screen(scr, a, multi):
labels, state = [], []
for it in a.items:
if multi:
on, _, lab = it.partition("|")
state.append(on == "1"); labels.append(lab)
else:
labels.append(it)
n = len(labels)
if n == 0:
return []
cur = min(max(a.default, 0), n - 1); top = 0
sel_attr = curses.color_pair(2) | curses.A_BOLD
def chosen():
return [i for i, s in enumerate(state) if s]
while True:
h, w = scr.getmaxyx()
area_top = draw_head(scr, a)
area_h = max(1, h - 3 - area_top)
if cur < top: top = cur
if cur >= top + area_h: top = cur - area_h + 1
for r in range(area_h):
i = top + r
if i >= n: break
mark = ("[x] " if state[i] else "[ ] ") if multi else ""
line = (" > " if i == cur else " ") + mark + labels[i]
put(scr, area_top + r, 1, line.ljust(max(0, w - 2)),
sel_attr if i == cur else curses.A_NORMAL)
if n > area_h:
put(scr, 1, max(0, w - 12), "%d/%d" % (cur + 1, n))
btn = {}
if multi:
okl, cl = "[ %s ]" % a.ok, "[ %s ]" % a.cancel
y, x0 = h - 2, 3
put(scr, y, x0, okl, sel_attr)
put(scr, y, x0 + len(okl) + 2, cl, curses.A_BOLD)
btn = {"ok": (y, x0, x0 + len(okl)),
"cancel": (y, x0 + len(okl) + 2, x0 + len(okl) + 2 + len(cl))}
footer(scr, a)
scr.refresh()
try:
k = scr.get_wch()
except curses.error:
continue
if isinstance(k, str):
if k in ("\n", "\r"):
return chosen() if multi else [cur]
if k == " " and multi: state[cur] = not state[cur]
elif k in ("\x1b", "q"): return None
elif k == "j": cur = min(n - 1, cur + 1)
elif k == "k": cur = max(0, cur - 1)
elif k == "a" and multi:
v = not all(state); state = [v] * n
elif k.isdigit() and not multi and 1 <= int(k) <= n: return [int(k) - 1]
elif k == "0" and not multi and labels[-1].startswith("0."): return [n - 1]
elif k == curses.KEY_UP: cur = max(0, cur - 1)
elif k == curses.KEY_DOWN: cur = min(n - 1, cur + 1)
elif k == curses.KEY_PPAGE: cur = max(0, cur - area_h)
elif k == curses.KEY_NPAGE: cur = min(n - 1, cur + area_h)
elif k == curses.KEY_HOME: cur = 0
elif k == curses.KEY_END: cur = n - 1
elif k == curses.KEY_ENTER: return chosen() if multi else [cur]
elif k == curses.KEY_MOUSE:
try:
_, mx, my, _, bs = curses.getmouse()
except curses.error:
continue
if bs & curses.BUTTON4_PRESSED: cur = max(0, cur - 1)
elif bs & BTN5: cur = min(n - 1, cur + 1)
elif bs & (curses.BUTTON1_PRESSED | curses.BUTTON1_CLICKED):
for name, (by, bx0, bx1) in btn.items():
if my == by and bx0 <= mx < bx1:
return chosen() if name == "ok" else None
i = top + (my - area_top)
if area_top <= my < area_top + area_h and 0 <= i < n:
cur = i
if multi: state[i] = not state[i]
else: return [i]
def input_screen(scr, a):
val = a.value
try: curses.curs_set(1)
except curses.error: pass
while True:
h, w = scr.getmaxyx()
area_top = draw_head(scr, a)
put(scr, area_top + 1, 2, "> " + val, curses.A_BOLD)
footer(scr, a)
try: scr.move(min(h - 2, area_top + 1), min(w - 1, 4 + len(val)))
except curses.error: pass
scr.refresh()
try: k = scr.get_wch()
except curses.error: continue
if isinstance(k, str):
if k in ("\n", "\r"): return val
if k == "\x1b": return None
if k in ("\x7f", "\b"): val = val[:-1]
elif k == "\x15": val = ""
elif k.isprintable(): val += k
elif k in (curses.KEY_BACKSPACE, curses.KEY_DC): val = val[:-1]
elif k == curses.KEY_ENTER: return val
LEVEL_PAIR = {"error": 8, "warn": 9, "ok": 10, "info": 11}
def draw_box(scr, y, x, h, w, body):
for r in range(h):
put(scr, y + r, x, " " * w, body)
try:
scr.hline(y, x + 1, curses.ACS_HLINE | body, w - 2)
scr.hline(y + h - 1, x + 1, curses.ACS_HLINE | body, w - 2)
scr.vline(y + 1, x, curses.ACS_VLINE | body, h - 2)
scr.vline(y + 1, x + w - 1, curses.ACS_VLINE | body, h - 2)
scr.addch(y, x, curses.ACS_ULCORNER | body)
scr.addch(y, x + w - 1, curses.ACS_URCORNER | body)
scr.addch(y + h - 1, x, curses.ACS_LLCORNER | body)
scr.addch(y + h - 1, x + w - 1, curses.ACS_LRCORNER | body)
except curses.error:
pass
def dialog_screen(scr, a):
"""Boîte de dialogue centrée, avec boutons. Retourne [index du bouton]."""
text = open(a.textfile, encoding="utf-8").read() if a.textfile else ""
buttons = a.items or ["OK"]
focus = min(max(a.default, 0), len(buttons) - 1)
top = 0
body = curses.color_pair(7)
bar = curses.color_pair(LEVEL_PAIR.get(a.level, 11)) | curses.A_BOLD
sel_attr = curses.color_pair(2) | curses.A_BOLD
while True:
h, w = scr.getmaxyx()
scr.erase()
top_bar = curses.color_pair(1) | curses.A_BOLD
put(scr, 0, 0, " " * w, top_bar)
put(scr, 0, max(0, (w - len(a.brand)) // 2), a.brand, top_bar)
btn_total = sum(len(b) + 4 for b in buttons) + 2 * (len(buttons) - 1)
bw = max(min(w - 4, 66), min(w - 2, btn_total + 6), 20)
lines = wrap(text, bw - 6)
vis = max(1, min(len(lines), h - 4 - 6))
bh = vis + 6
y0, x0 = max(1, (h - bh) // 2), max(0, (w - bw) // 2)
top = max(0, min(top, max(0, len(lines) - vis)))
draw_box(scr, y0, x0, bh, bw, body)
put(scr, y0 + 1, x0 + 1, " " * (bw - 2), bar)
put(scr, y0 + 1, x0 + max(1, (bw - len(a.title)) // 2), a.title[:bw - 4], bar)
for r in range(vis):
if top + r < len(lines):
put(scr, y0 + 3 + r, x0 + 3, lines[top + r].ljust(bw - 6), body)
if len(lines) > vis:
put(scr, y0 + 2, x0 + bw - 12, "(%d/%d)" % (top + 1, len(lines) - vis + 1), body)
rects, x = [], x0 + max(1, (bw - btn_total) // 2)
for i, b in enumerate(buttons):
label = "[ %s ]" % b
put(scr, y0 + bh - 2, x, label, sel_attr if i == focus else (body | curses.A_BOLD))
rects.append((x, x + len(label)))
x += len(label) + 2
footer(scr, a)
scr.refresh()
try:
k = scr.get_wch()
except curses.error:
continue
if isinstance(k, str):
if k in ("\n", "\r"): return [focus]
if k == "\x1b": return None
if k == "\t": focus = (focus + 1) % len(buttons)
elif k == "j": top += 1
elif k == "k": top -= 1
elif k == curses.KEY_RIGHT: focus = min(len(buttons) - 1, focus + 1)
elif k == curses.KEY_LEFT: focus = max(0, focus - 1)
elif k == curses.KEY_UP: top -= 1
elif k == curses.KEY_DOWN: top += 1
elif k == curses.KEY_PPAGE: top -= vis
elif k == curses.KEY_NPAGE: top += vis
elif k == curses.KEY_ENTER: return [focus]
elif k == curses.KEY_MOUSE:
try:
_, mx, my, _, bs = curses.getmouse()
except curses.error:
continue
if bs & curses.BUTTON4_PRESSED: top -= 1
elif bs & BTN5: top += 1
elif bs & (curses.BUTTON1_PRESSED | curses.BUTTON1_CLICKED) and my == y0 + bh - 2:
for i, (bx0, bx1) in enumerate(rects):
if bx0 <= mx < bx1:
return [i]
TW = 16
def centered(s, n):
return s[:n].center(n)
def popup_menu(scr, title, labels, cur):
"""Petite liste centrée par-dessus l'écran. Retourne l'index choisi ou None."""
n = len(labels)
body = curses.color_pair(7)
bar = curses.color_pair(11) | curses.A_BOLD
sel_attr = curses.color_pair(2) | curses.A_BOLD
top = 0
while True:
h, w = scr.getmaxyx()
bw = min(max(10, w - 2), max(34, len(title) + 6, max(len(l) for l in labels) + 8))
vis = max(1, min(n, h - 6))
bh = vis + 4
y0, x0 = max(0, (h - bh) // 2), max(0, (w - bw) // 2)
if cur < top: top = cur
if cur >= top + vis: top = cur - vis + 1
draw_box(scr, y0, x0, bh, bw, body)
put(scr, y0 + 1, x0 + 1, " " * (bw - 2), bar)
put(scr, y0 + 1, x0 + max(1, (bw - len(title)) // 2), title[:bw - 4], bar)
for r in range(vis):
i = top + r
if i >= n: break
line = (" > " if i == cur else " ") + labels[i]
put(scr, y0 + 2 + r, x0 + 1, line[:bw - 2].ljust(bw - 2), sel_attr if i == cur else body)
if n > vis:
put(scr, y0 + vis + 2, x0 + max(1, bw - 10), "%d/%d" % (cur + 1, n), body)
scr.refresh()
try:
k = scr.get_wch()
except curses.error:
continue
if isinstance(k, str):
if k in ("\n", "\r"): return cur
if k in ("\x1b", "q"): return None
if k == "j": cur = min(n - 1, cur + 1)
elif k == "k": cur = max(0, cur - 1)
elif k == curses.KEY_UP: cur = max(0, cur - 1)
elif k == curses.KEY_DOWN: cur = min(n - 1, cur + 1)
elif k == curses.KEY_PPAGE: cur = max(0, cur - vis)
elif k == curses.KEY_NPAGE: cur = min(n - 1, cur + vis)
elif k == curses.KEY_HOME: cur = 0
elif k == curses.KEY_END: cur = n - 1
elif k == curses.KEY_ENTER: return cur
elif k == curses.KEY_MOUSE:
try:
_, mx, my, _, bs = curses.getmouse()
except curses.error:
continue
if bs & curses.BUTTON4_PRESSED: cur = max(0, cur - 1)
elif bs & BTN5: cur = min(n - 1, cur + 1)
elif bs & (curses.BUTTON1_PRESSED | curses.BUTTON1_CLICKED):
i = top + (my - (y0 + 2))
if y0 + 2 <= my < y0 + 2 + vis and 0 <= i < n:
return i
def preview_screen(scr, a):
"""Aperçu du sélecteur OpenCore : ordre, visibilité, logo, sous-dossier.
Entrée : fichier TSV (clé, nom, visible, logo, dossier, type).
Sortie : lignes « clé<TAB>visible<TAB>logo<TAB>dossier » dans le nouvel ordre."""
labs = dict(x.split("=", 1) for x in a.lab if "=" in x)
L = labs.get
items = []
if a.textfile:
for line in open(a.textfile, encoding="utf-8").read().splitlines():
p = line.split("\t")
if len(p) >= 6:
items.append({"key": p[0], "name": p[1], "vis": p[2] == "1", "logo": p[3],
"fol": p[4] == "1", "kind": p[5]})
icons = []
if a.iconsfile and os.path.exists(a.iconsfile):
icons = [l for l in open(a.iconsfile, encoding="utf-8").read().splitlines() if l]
n = len(items)
if n == 0:
return ""
cur, first = 0, 0
sel_attr = curses.color_pair(2) | curses.A_BOLD
bg = curses.color_pair(12)
plain = ("X", "F") # X = menu GRUB complet, F = sous-dossier
def members():
return [m for m in items if m["vis"] and m["fol"] and m["kind"] not in plain]
def final_row():
out = []
for it in items:
if not it["vis"]:
continue
if it["kind"] == "F":
if members():
out.append(it["name"])
elif it["fol"]:
continue
else:
out.append(it["name"])
return out
def result():
return "\n".join("\t".join([e["key"], "1" if e["vis"] else "0", e["logo"],
"1" if e["fol"] else "0"]) for e in items)
while True:
h, w = scr.getmaxyx()
top = draw_head(scr, a)
per = max(1, (w - 4) // TW)
if cur < first: first = cur
if cur >= first + per: first = cur - per + 1
first = max(0, min(first, max(0, n - per)))
box_h, box_w = 8, min(max(10, w - 2), per * TW + 2)
bx = max(0, (w - box_w) // 2)
draw_box(scr, top, bx, box_h, box_w, bg)
put(scr, top, bx + 2, " OpenCore ", bg | curses.A_BOLD)
put(scr, top, max(0, bx + box_w - 10), " %d/%d " % (cur + 1, n), bg)
nm = len(members())
for idx in range(first, min(n, first + per)):
it = items[idx]
tx, ty = bx + 2 + (idx - first) * TW, top + 1
if it["kind"] == "F" and nm == 0:
status = "(%s)" % L("empty", "empty")
elif it["vis"]:
status = "[x] " + L("on", "visible")
else:
status = "[ ] " + L("off", "hidden")
label = ("> " if (it["fol"] and it["kind"] not in plain) else "") + it["name"]
logo = it["logo"] or "(%s)" % a.autologo
rows = ["+" + "-" * 12 + "+",
"|" + centered("[ %s ]" % (it["name"][:1] or "?").upper(), 12) + "|",
"|" + centered(logo, 12) + "|",
"+" + "-" * 12 + "+",
centered(label, 14),
centered(status, 14)]
if idx == cur:
attr = sel_attr if it["vis"] else curses.color_pair(13) | curses.A_BOLD
else:
attr = bg if it["vis"] else bg | curses.A_DIM
for r, txt in enumerate(rows):
put(scr, ty + r, tx, txt, attr)
if first > 0:
put(scr, top + 3, bx + 1, "<", bg | curses.A_BOLD)
if first + per < n:
put(scr, top + 3, bx + box_w - 2, ">", bg | curses.A_BOLD)
y = top + box_h
pl = wrap("%s %s" % (L("prev", "OpenCore:"), " ".join(final_row()) or "-"), w - 4)
for i, line in enumerate(pl[:2]):
put(scr, y + i, 2, line, curses.A_BOLD)
y += min(len(pl), 2)
it = items[cur]
tag = {"S": L("kS", ""), "C": L("kC", ""), "M": L("kM", "")}.get(it["kind"], "")
put(scr, y, 2, ("%s %s" % (it["name"], tag)).strip(), curses.color_pair(3) | curses.A_BOLD)
logo_t = it["logo"] or "%s (%s)" % (L("auto", "auto"), a.autologo)
put(scr, y + 1, 2, "%s %s %s %d/%d" % (L("logo", "Logo:"), logo_t, L("pos", "Position:"), cur + 1, n))
if it["kind"] == "F":
put(scr, y + 2, 2, "%s %s" % (L("has", "Contains:"), ", ".join(m["name"] for m in members()) or "-"))
okl, cl = "[ %s ]" % a.ok, "[ %s ]" % a.cancel
brow, bx0 = h - 2, 3
put(scr, brow, bx0, okl, sel_attr)
put(scr, brow, bx0 + len(okl) + 2, cl, curses.A_BOLD)
btn = {"ok": (brow, bx0, bx0 + len(okl)),
"cancel": (brow, bx0 + len(okl) + 2, bx0 + len(okl) + 2 + len(cl))}
parts = a.hint.split("|")
extra = parts[:-1]
for i, pt in enumerate(extra):
put(scr, h - 3 - (len(extra) - 1 - i), 2, pt, curses.A_DIM)
fattr = curses.color_pair(4)
put(scr, h - 1, 0, " " * w, fattr)
put(scr, h - 1, 1, parts[-1], fattr)
scr.refresh()
try:
k = scr.get_wch()
except curses.error:
continue
if isinstance(k, str):
if k in ("\n", "\r"): return result()
if k in ("\x1b", "q"): return None
if k == "\t": cur = (cur + 1) % n
elif k == " ": it["vis"] = not it["vis"]
elif k in ("d", "D"):
if it["kind"] not in plain:
it["fol"] = not it["fol"]
elif k in ("<", ","):
if cur > 0:
items[cur - 1], items[cur] = items[cur], items[cur - 1]
cur -= 1
elif k in (">", "."):
if cur < n - 1:
items[cur + 1], items[cur] = items[cur], items[cur + 1]
cur += 1
elif k in ("l", "L"):
labels = [L("auto_opt", "Automatic")] + icons
start = icons.index(it["logo"]) + 1 if it["logo"] in icons else 0
r = popup_menu(scr, "%s : %s" % (L("pick", "Logo"), it["name"]), labels, start)
if r is not None:
it["logo"] = "" if r == 0 else icons[r - 1]
elif k == "j": cur = min(n - 1, cur + 1)
elif k == "k": cur = max(0, cur - 1)
elif k == curses.KEY_LEFT: cur = max(0, cur - 1)
elif k == curses.KEY_RIGHT: cur = min(n - 1, cur + 1)
elif k == curses.KEY_UP: cur = max(0, cur - 1)
elif k == curses.KEY_DOWN: cur = min(n - 1, cur + 1)
elif k == curses.KEY_BTAB: cur = (cur - 1) % n
elif k == curses.KEY_HOME: cur = 0
elif k == curses.KEY_END: cur = n - 1
elif k == curses.KEY_ENTER: return result()
elif k == curses.KEY_MOUSE:
try:
_, mx, my, _, bs = curses.getmouse()
except curses.error:
continue
if bs & curses.BUTTON4_PRESSED: cur = max(0, cur - 1)
elif bs & BTN5: cur = min(n - 1, cur + 1)
elif bs & (curses.BUTTON1_PRESSED | curses.BUTTON1_CLICKED):
for name, (by_, bx_0, bx_1) in btn.items():
if my == by_ and bx_0 <= mx < bx_1:
return result() if name == "ok" else None
col = (mx - (bx + 2)) // TW
if top < my < top + box_h - 1 and 0 <= col < per and first + col < n:
cur = first + col
def main():
a = parse()
def run(scr):
try: curses.curs_set(0)
except curses.error: pass
try:
curses.start_color()
bg = curses.COLOR_BLACK
try:
curses.use_default_colors(); bg = -1
except curses.error:
pass
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)
curses.init_pair(3, curses.COLOR_YELLOW, bg)
curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(5, curses.COLOR_RED, bg)
curses.init_pair(6, curses.COLOR_GREEN, bg)
curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE) # corps des dialogues
curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_RED) # dialogue : erreur
curses.init_pair(9, curses.COLOR_BLACK, curses.COLOR_YELLOW) # dialogue : attention
curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_GREEN) # dialogue : succès
curses.init_pair(11, curses.COLOR_WHITE, curses.COLOR_BLUE) # dialogue : information
curses.init_pair(12, curses.COLOR_WHITE, curses.COLOR_BLACK) # aperçu : écran de démarrage
curses.init_pair(13, curses.COLOR_BLACK, curses.COLOR_WHITE)
except curses.error:
pass
try:
curses.mousemask(curses.ALL_MOUSE_EVENTS); curses.mouseinterval(0)
except curses.error:
pass
scr.keypad(True)
if a.mode == "menu": return list_screen(scr, a, False)
if a.mode == "check": return list_screen(scr, a, True)
if a.mode == "input": return input_screen(scr, a)
if a.mode == "preview": return preview_screen(scr, a)
return dialog_screen(scr, a)
try:
res = curses.wrapper(run)
except KeyboardInterrupt:
sys.exit(130)
if res is None:
sys.exit(1)
with open(a.out, "w", encoding="utf-8") as f:
f.write(res if isinstance(res, str) else " ".join(str(i) for i in res))
main()
PYEOF
}
# enveloppes bash autour de l'interface
ui_run() {
[ "$NONINT" = 1 ] && { UI_RESULT=""; return 1; }
local mode=$1 title=$2 sub=$3 hint=$4; shift 4
rm -f "$WORK/ui.out"
python3 "$TUI" "$mode" "$WORK/ui.out" --brand "$BRAND" --title "$title" --subtitle "$sub" \
--hint "$hint" --ok "$(t btn_ok)" --cancel "$(t btn_cancel)" "$@"
local rc=$?
UI_RESULT=$(cat "$WORK/ui.out" 2>/dev/null || true)
return $rc
}
ui_menu() { local ti=$1 su=$2 de=$3; shift 3; ui_run menu "$ti" "$su" "$(t hint_menu)" --default "$de" -- "$@"; }
ui_check() { local ti=$1 su=$2; shift 2; ui_run check "$ti" "$su" "$(t hint_check)" -- "$@"; }
ui_input() { ui_run input "$1" "$2" "$(t hint_input)" --value "${3:-}"; }
ui_alert() {
local ti=$1 tx=$2 lv=$3; shift 3
printf '%s' "$tx" > "$WORK/msg.txt"
ui_run dialog "$ti" "" "$(t hint_dialog)" --textfile "$WORK/msg.txt" --level "$lv" \
--default "${UI_DEFAULT:-0}" -- "$@"
}
ui_msg() {
if [ "$NONINT" = 1 ]; then echo "[$1] $2" >&2; return 0; fi
ui_alert "$1" "$2" "${3:-info}" "$(t btn_ok)" || true
}
ui_yesno() {
UI_DEFAULT=${3:-0} ui_alert "$1" "$2" "${4:-info}" "$(t yes)" "$(t no)" || return 1
[ "$UI_RESULT" = 0 ]
}
plain_begin() { [ "$NONINT" = 1 ] || clear; printf '%s%s%s\n\n' "$C_B" "$BRAND" "$C_0"; }
info() { echo "${C_G}==>${C_0} $*"; }
warn() { echo "${C_Y}[!]${C_0} $*"; }
die() { ui_msg "$(t err_title)" "$*" error; exit 1; }
# etat
load_state() { if [ -f "$STATE_FILE" ]; then source "$STATE_FILE"; fi; }
save_state() {
[ "$NO_SAVE" = 1 ] && return 0
[ "$EUID" -eq 0 ] || return 0
mkdir -p "$STATE_DIR"
local v
for v in LANG_UI ESP BOOT_EXISTED ORIG_BOOTORDER OC_BOOTNUM COMPAT GRUBDIR; do
printf '%s=%q\n' "$v" "${!v}"
done > "$STATE_FILE"
}
#verifs
find_esp() {
if [ -n "$ESP" ] && mountpoint -q "$ESP"; then return 0; fi
local d
for d in /boot/efi /efi /boot; do
if mountpoint -q "$d" && [ "$(findmnt -no FSTYPE "$d")" = vfat ]; then ESP=$d; return 0; fi
done
ui_input "$(t esp_title)" "$(t esp_prompt)" "" || {
if [ "$NONINT" = 1 ]; then echo "$(t esp_title)" >&2; exit 1; fi
exit 0
}
ESP=$UI_RESULT
mountpoint -q "$ESP" || die "$(t esp_nomount "$ESP")"
}
check_secureboot() {
local f=/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c v
if [ -r "$f" ]; then
v=$(od -An -t u1 -j4 -N1 "$f" | tr -d ' ')
if [ "$v" = 1 ]; then ui_yesno "$(t warn_title)" "$(t sb_warn)" 1 warn || return 1; fi
fi
return 0
}
DEP_CMDS=(curl unzip efibootmgr python3 lsblk findmnt mountpoint tar flock)
MISSING=()
detect_pm() {
local pm
for pm in apt-get dnf pacman zypper xbps-install; do
if command -v "$pm" >/dev/null; then echo "$pm"; return 0; fi
done
return 0
}
dep_pkg() {
case $1 in
lsblk|findmnt|mountpoint|flock) echo util-linux ;;
python3) if [ "$(detect_pm)" = pacman ]; then echo python; else echo python3; fi ;;
*) echo "$1" ;;
esac
}
missing_deps() {
MISSING=(); local c
for c in "${DEP_CMDS[@]}"; do command -v "$c" >/dev/null || MISSING+=("$c"); done
}
pm_install() {
case $(detect_pm) in
apt-get) apt-get update -qq; apt-get install -y "$@" ;;
dnf) dnf install -y "$@" ;;
pacman) pacman -S --needed --noconfirm "$@" ;;
zypper) zypper --non-interactive install "$@" ;;
xbps-install) xbps-install -Sy "$@" ;;
*) return 1 ;;
esac
}
check_deps() {
missing_deps
[ ${#MISSING[@]} -eq 0 ] && return 0
local pkgs=() c p list pm
for c in "${MISSING[@]}"; do
p=$(dep_pkg "$c")
[[ " ${pkgs[*]-} " == *" $p "* ]] || pkgs+=("$p")
done
list=$(IFS=,; echo "${MISSING[*]}"); list=${list//,/, }
pm=$(detect_pm)
if [ -z "$pm" ]; then ui_msg "$(t dep_title)" "$(t dep_nopm "$list")" error; return 1; fi
UI_DEFAULT=0 ui_alert "$(t dep_title)" "$(t dep_missing "$list" "${pkgs[*]}")" warn \
"$(t dep_install)" "$(t quit)" || return 1
[ "$UI_RESULT" = 0 ] || return 1
plain_begin
pm_install "${pkgs[@]}" || true
missing_deps
if [ ${#MISSING[@]} -gt 0 ]; then
ui_msg "$(t dep_title)" "$(t dep_still "${MISSING[*]}")" error
return 1
fi
return 0
}
# Python3
ensure_python() {
if command -v python3 >/dev/null && python3 -c 'import curses' 2>/dev/null; then return 0; fi
echo "${C_B}$BRAND${C_0}"; echo
echo "Python 3 (module curses) est requis pour afficher l'interface."
echo "Python 3 (curses module) is required to display the interface."
if [ "$EUID" -ne 0 ]; then echo; echo " sudo bash $0"; exit 1; fi
local r pk=(python3)
if command -v pacman >/dev/null; then pk=(python); fi
if command -v zypper >/dev/null; then pk=(python3 python3-curses); fi
read -rp "Installer maintenant / Install now ? [o/y/N] " r
[[ $r =~ ^[oOyY]$ ]] || exit 1
pm_install "${pk[@]}" || exit 1
python3 -c 'import curses' 2>/dev/null || { echo "python3 curses: KO"; exit 1; }
}
# sauvegarde
backup_esp() {
mkdir -p "$BACKUP_DIR"
[ -n "$ORIG_BOOTORDER" ] || ORIG_BOOTORDER=$(efibootmgr | awk '/^BootOrder/{print $2}')
if [ -f "$BACKUP_DIR/.done" ]; then return 0; fi
local src="" guess=""
if [ -d "$ESP/EFI/OC" ]; then
[ -d /root/EFI-BOOT-backup ] && guess=/root/EFI-BOOT-backup
ui_input "$(t old_title)" "$(t old_prompt)" "$guess" || return 1
src=$UI_RESULT
if [ -n "$src" ] && [ ! -d "$src" ]; then die "$(t dir_nf "$src")"; fi
fi
[ -n "$src" ] || src="$ESP/EFI/BOOT"
if [ -d "$src" ]; then
rm -rf "$BACKUP_DIR/EFI-BOOT"
cp -a "$src" "$BACKUP_DIR/EFI-BOOT" || die "$(t bk_fail)"
BOOT_EXISTED=1