-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.sh
More file actions
1159 lines (1016 loc) · 42.3 KB
/
Copy pathinstall.sh
File metadata and controls
1159 lines (1016 loc) · 42.3 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
#!/bin/bash
set -euo pipefail
# --- 1. CRITICAL SETUP & RESTART FIX ---
SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
cd "$SCRIPT_DIR" || { echo "Failed to change directory to $SCRIPT_DIR"; exit 1; }
# --- 2. VISUAL STYLING ---
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly YELLOW='\033[1;33m'
readonly WHITE='\033[1;37m'
readonly NC='\033[0m'
readonly UI_WIDTH=86
readonly SCRIPT_VERSION="3.8.1"
readonly CHECKSUM_FILE="$SCRIPT_DIR/Installers/.checksums.sha256"
readonly UPDATE_STATE_FILE="$SCRIPT_DIR/.update-state"
readonly EXIT_APP_CODE=42
# --- 3. COMMAND AVAILABILITY CACHE ---
HAS_GIT=$(command -v git &>/dev/null && echo 1 || echo 0)
HAS_SHA256SUM=$(command -v sha256sum &>/dev/null && echo 1 || echo 0)
HAS_FILE=$(command -v file &>/dev/null && echo 1 || echo 0)
HAS_SUDO=$(command -v sudo &>/dev/null && echo 1 || echo 0)
HAS_TIMEOUT=$(command -v timeout &>/dev/null && echo 1 || echo 0)
# --- 4. STATIC SYSTEM INFO CACHE ---
readonly CACHED_HOSTNAME=$(hostname)
readonly CACHED_KERNEL=$(uname -r)
# cleanup restores the terminal cursor to a visible state when the script exits.
cleanup() {
tput cnorm 2>/dev/null || true
}
trap cleanup EXIT
# --- 6. SETTINGS & CONFIGURATION ---
SETTINGS_FILE="$SCRIPT_DIR/settings.local.conf"
# trim_whitespace removes leading and trailing whitespace from a string and prints the trimmed result to stdout.
trim_whitespace() {
local str="$1"
str="${str#"${str%%[![:space:]]*}"}"
str="${str%"${str##*[![:space:]]}"}"
printf '%s' "$str"
}
# load_settings loads update preferences from the local, ignored settings file.
load_settings() {
AUTO_UPDATE_CHECK="false"
AUTO_APPLY_UPDATES="false"
if [[ ! -f "$SETTINGS_FILE" ]]; then
save_settings
return
fi
local file_perms
file_perms=$(stat -c %a "$SETTINGS_FILE" 2>/dev/null || stat -f %OLp "$SETTINGS_FILE" 2>/dev/null)
if [[ -n "$file_perms" && "$file_perms" != "600" ]]; then
chmod 600 "$SETTINGS_FILE" 2>/dev/null || true
fi
local line key value
while IFS= read -r line; do
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
key="${line%%=*}"
value="${line#*=}"
key=$(trim_whitespace "$key")
value=$(trim_whitespace "$value")
value="${value#\"}"
value="${value%\"}"
case "$key" in
AUTO_UPDATE_CHECK)
[[ "$value" =~ ^(true|false)$ ]] && AUTO_UPDATE_CHECK="$value"
;;
AUTO_APPLY_UPDATES)
[[ "$value" =~ ^(true|false)$ ]] && AUTO_APPLY_UPDATES="$value"
;;
esac
done < "$SETTINGS_FILE"
}
# save_settings writes local preferences without modifying tracked repository files.
save_settings() {
cat > "$SETTINGS_FILE" << EOF
# System Setup Menu - Configuration
# AUTO_UPDATE_CHECK: Check for updates on startup (true/false)
AUTO_UPDATE_CHECK="$AUTO_UPDATE_CHECK"
# AUTO_APPLY_UPDATES: Apply fast-forward updates without prompting (true/false)
AUTO_APPLY_UPDATES="$AUTO_APPLY_UPDATES"
EOF
chmod 600 "$SETTINGS_FILE" 2>/dev/null || true
}
load_settings
# print_centered prints TEXT centered within UI_WIDTH, using an optional COLOR escape code for output.
print_centered() {
local text="$1"
local color="${2:-$NC}"
local padding=$(( (UI_WIDTH - ${#text}) / 2 ))
((padding < 0)) && padding=0
printf "${color}%${padding}s%s${NC}\n" "" "$text"
}
# print_line prints a line made of a repeated character (default '=') spanning UI_WIDTH and echoes it using an optional color (default BLUE).
print_line() {
local char="${1:-=}"
local color="${2:-$BLUE}"
local line
line=$(printf "%${UI_WIDTH}s" "" | tr ' ' "$char")
echo -e "${color}${line}${NC}"
}
# print_status prints an informational message prefixed with [INFO] in cyan; the message text is taken from the first argument.
print_status() { echo -e "${CYAN}[INFO]${NC} $1"; }
# print_success prints a success message prefixed with "[OK]" in green and echoes the provided text.
print_success() { echo -e "${GREEN}[OK]${NC} $1"; }
# print_warn prints a warning message prefixed with `[WARN]` in yellow color to stdout.
print_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
# print_error prints an error message prefixed with "[ERROR]" in red.
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# pause waits for the user to press Enter to continue and return to the menu.
pause() {
echo ""
read -rp "Press [Enter] to return to the menu..."
}
# confirm_prompt displays a prompt, reads a single-line response (defaults to 'n' if empty), and exits with status 0 when the response is `y` or `Y` (non-zero otherwise).
confirm_prompt() {
local prompt="$1"
local default="${2:-n}"
local response
read -rp "$prompt" response
response="${response:-$default}"
[[ "$response" =~ ^[Yy]$ ]]
}
# truncate_string truncates a string to a maximum length and appends `..` when truncation occurs.
truncate_string() {
local str="$1"
local max_len="$2"
if ((${#str} > max_len)); then
printf '%s..' "${str:0:$((max_len - 2))}"
else
printf '%s' "$str"
fi
}
# get_current_branch prints the current Git branch name or "unknown" if not in a Git repository or Git cannot determine the branch.
get_current_branch() {
if ((HAS_GIT)); then
git branch --show-current 2>/dev/null || echo "unknown"
else
echo "unknown"
fi
}
# is_root determines whether the effective user ID is 0 (root).
is_root() {
((EUID == 0))
}
# git_fetch performs a git fetch, using a 10-second timeout when the `timeout` command is available, and accepts optional git fetch arguments.
git_fetch() {
local -a fetch_args=("$@")
((${#fetch_args[@]})) || fetch_args=(--quiet)
if ((HAS_TIMEOUT)); then
timeout 10 git fetch "${fetch_args[@]}" 2>/dev/null
else
git fetch "${fetch_args[@]}" 2>/dev/null
fi
}
# handle_uncommitted_changes prompts to stash, discard, or cancel when uncommitted Git changes exist in the current repository.
# The optional `context` argument is included in the stash message; returns 0 when changes were handled and the caller may proceed, or 1 if the user cancelled or an operation failed.
handle_uncommitted_changes() {
local context="$1"
if [[ -z "$(git status --porcelain 2>/dev/null)" ]]; then
return 0
fi
print_warn "You have uncommitted changes."
echo ""
echo -e " ${WHITE}Options:${NC}"
echo -e " ${CYAN}1.${NC} Stash changes and continue"
echo -e " ${CYAN}2.${NC} Discard changes and continue"
echo -e " ${CYAN}0.${NC} Cancel"
echo ""
read -rp " Select option [0-2]: " change_option
case "$change_option" in
1)
print_status "Stashing changes..."
local stash_msg="Auto-stash $context on $(date '+%Y-%m-%d %H:%M')"
if ! git stash push --include-untracked -m "$stash_msg" 2>/dev/null; then
print_error "Failed to stash changes."
return 1
fi
print_success "Changes stashed. Use 'git stash pop' to restore."
;;
2)
if ! confirm_prompt " Are you sure? This cannot be undone. (y/N): " "n"; then
return 1
fi
print_status "Discarding changes..."
if ! git reset --hard HEAD &>/dev/null; then
print_error "Failed to reset working directory."
return 1
fi
print_warn "Untracked files were preserved."
print_success "Tracked changes discarded."
;;
*)
print_status "Cancelled."
return 1
;;
esac
return 0
}
# fix_permissions ensures all Installers/*.sh files are executable.
# When the first argument is "silent" it suppresses per-file messages and the summary; when the Installers directory is missing it prints an error unless run in silent mode.
fix_permissions() {
local silent="${1:-}"
local installers_dir="$SCRIPT_DIR/Installers"
local fixed=0
local total=0
if [[ ! -d "$installers_dir" ]]; then
[[ "$silent" != "silent" ]] && print_error "Installers directory not found."
return 0
fi
while IFS= read -r -d '' script; do
((total++))
if [[ ! -x "$script" ]]; then
if chmod +x "$script" 2>/dev/null; then
((fixed++))
[[ "$silent" != "silent" ]] && print_success "Fixed: $(basename "$script")"
else
[[ "$silent" != "silent" ]] && print_error "Failed: $(basename "$script")"
fi
fi
done < <(find "$installers_dir" -maxdepth 1 -name "*.sh" -type f -print0 2>/dev/null) || true
if [[ "$silent" != "silent" ]]; then
echo ""
if ((fixed == 0)); then
print_success "All $total scripts already have correct permissions."
else
print_success "Fixed permissions on $fixed of $total scripts."
fi
fi
return 0
}
# show_header prints the colored ASCII-art banner, a centered VERSION/author line, and a divider.
show_header() {
clear
echo -e "${BLUE}███████╗██╗ ██╗███████╗████████╗███████╗███╗ ███╗ ███████╗███████╗████████╗██╗ ██╗██████╗ ${NC}"
echo -e "${BLUE}██╔════╝╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔════╝████╗ ████║ ██╔════╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗${NC}"
echo -e "${BLUE}███████╗ ╚████╔╝ ███████╗ ██║ █████╗ ██╔████╔██║ ███████╗█████╗ ██║ ██║ ██║██████╔╝${NC}"
echo -e "${BLUE}╚════██║ ╚██╔╝ ╚════██║ ██║ ██╔══╝ ██║╚██╔╝██║ ╚════██║██╔══╝ ██║ ██║ ██║██╔═══╝ ${NC}"
echo -e "${BLUE}███████║ ██║ ███████║ ██║ ███████╗██║ ╚═╝ ██║ ███████║███████╗ ██║ ╚██████╔╝██║ ${NC}"
echo -e "${BLUE}╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ${NC}"
print_centered "VERSION $SCRIPT_VERSION | BY: NAREHOOD" "$CYAN"
print_line "=" "$BLUE"
}
# get_os_info retrieves an OS field from /etc/os-release; accepts `id`, `version_id`, or `pretty_name` and echoes the corresponding value (quotes stripped) or an empty string if unavailable.
get_os_info() {
local info_type="$1"
if [[ -f /etc/os-release ]]; then
case "$info_type" in
id)
sed -n 's/^ID=//p' /etc/os-release 2>/dev/null | tr -d '"' || echo ""
;;
version_id)
sed -n 's/^VERSION_ID=//p' /etc/os-release 2>/dev/null | tr -d '"' || echo ""
;;
pretty_name)
sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"' || echo ""
;;
esac
fi
}
# show_stats prints a concise system information panel including OS, kernel, hostname, IP, subnet, gateway, load average, memory and disk usage, uptime, and current Git branch; it truncates long values and handles missing files/commands gracefully.
show_stats() {
local distro="Unknown"
local os_id=""
local version_id=""
os_id=$(get_os_info "id")
version_id=$(get_os_info "version_id")
if [[ -n "$os_id" ]]; then
case "$os_id" in
alpine)
distro="Alpine ${version_id}"
;;
pop)
distro="Pop!_OS ${version_id}"
;;
endeavouros)
distro="EndeavourOS"
;;
manjaro)
distro="Manjaro ${version_id}"
;;
arch)
distro="Arch Linux"
;;
ubuntu|debian|fedora|rocky|almalinux|centos|rhel|opensuse*|suse|sles|linuxmint|kali)
distro=$(get_os_info "pretty_name")
[[ -z "$distro" ]] && distro="$os_id"
;;
*)
distro=$(get_os_info "pretty_name")
[[ -z "$distro" ]] && distro="$os_id"
;;
esac
fi
distro=$(truncate_string "$distro" 32)
local kernel
kernel=$(truncate_string "$CACHED_KERNEL" 32)
local uptime_str="N/A"
if [[ -f /proc/uptime ]]; then
local uptime_secs
uptime_secs=$(cut -d. -f1 /proc/uptime)
local days=$((uptime_secs / 86400))
local hours=$(( (uptime_secs % 86400) / 3600 ))
local mins=$(( (uptime_secs % 3600) / 60 ))
if ((days > 0)); then
uptime_str="${days}d ${hours}h ${mins}m"
elif ((hours > 0)); then
uptime_str="${hours}h ${mins}m"
else
uptime_str="${mins}m"
fi
fi
local cpu_load="N/A"
if [[ -f /proc/loadavg ]]; then
cpu_load=$(awk '{printf "%.2f (1m)", $1}' /proc/loadavg)
fi
local mem_usage="N/A"
if [[ -f /proc/meminfo ]]; then
local mem_total mem_avail
read -r mem_total mem_avail < <(awk '/^MemTotal:/ {t=int($2/1024)} /^MemAvailable:/ {a=int($2/1024)} END {print t, a}' /proc/meminfo)
if [[ -n "$mem_total" && -n "$mem_avail" && "$mem_total" -gt 0 ]]; then
local mem_used=$((mem_total - mem_avail))
local mem_pct=$((mem_used * 100 / mem_total))
mem_usage="${mem_used}/${mem_total}MB (${mem_pct}%)"
fi
fi
local disk_usage="N/A"
if command -v df &>/dev/null; then
local disk_info
disk_info=$(df -P / 2>/dev/null | awk 'NR==2 {print $3, $2, $5}')
if [[ -n "$disk_info" ]]; then
local used total pct
read -r used total pct <<< "$disk_info"
if [[ -n "$used" && -n "$total" && -n "$pct" ]]; then
local used_h total_h
if ((total >= 1048576)); then
used_h="$((used / 1048576))G"
total_h="$((total / 1048576))G"
else
used_h="$((used / 1024))M"
total_h="$((total / 1024))M"
fi
disk_usage="${used_h}/${total_h} (${pct})"
fi
fi
fi
local hostname_str
hostname_str=$(truncate_string "$CACHED_HOSTNAME" 30)
local ip_addr="N/A"
local subnet="N/A"
local gateway="N/A"
if command -v ip &>/dev/null; then
local full_ip
full_ip=$(ip -4 addr show scope global 2>/dev/null | awk '/inet / {print $2; exit}')
if [[ -n "$full_ip" ]]; then
ip_addr="${full_ip%%/*}"
subnet="/${full_ip##*/}"
fi
gateway=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')
gateway=$(truncate_string "${gateway:-N/A}" 20)
fi
local current_branch
current_branch=$(truncate_string "$(get_current_branch)" 30)
echo -e "${WHITE}SYSTEM INFORMATION${NC}"
printf " ${YELLOW}%-11s${NC} : %-30s ${YELLOW}%-11s${NC} : %s\n" "OS" "$distro" "IP Address" "$ip_addr"
printf " ${YELLOW}%-11s${NC} : %-30s ${YELLOW}%-11s${NC} : %s\n" "Kernel" "$kernel" "Subnet" "$subnet"
printf " ${YELLOW}%-11s${NC} : %-30s ${YELLOW}%-11s${NC} : %s\n" "Hostname" "$hostname_str" "Gateway" "$gateway"
print_line "-" "$BLUE"
printf " ${YELLOW}%-11s${NC} : %-30s ${YELLOW}%-11s${NC} : %s\n" "Load Avg" "$cpu_load" "Memory" "$mem_usage"
printf " ${YELLOW}%-11s${NC} : %-30s ${YELLOW}%-11s${NC} : %s\n" "Disk Usage" "$disk_usage" "Uptime" "$uptime_str"
print_line "-" "$BLUE"
printf " ${YELLOW}%-11s${NC} : %-30s\n" "Branch" "$current_branch"
print_line "=" "$BLUE"
}
# read_launcher_constant prints the value of a readonly assignment from a launcher script.
read_launcher_constant() {
local file_path="$1"
local constant_name="$2"
awk -F= -v name="$constant_name" '
$0 ~ "^readonly[[:space:]]+" name "=" {
value=$2
gsub(/"/, "", value)
print value
exit
}
' "$file_path" 2>/dev/null || true
}
# capture_component_snapshot writes version metadata for the current tree into named variables via stdout.
capture_component_snapshot() {
local commit version docker_rev docker_ver linutil_rev
commit=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
version="$SCRIPT_VERSION"
docker_rev=$(read_launcher_constant "$SCRIPT_DIR/Installers/Docker-Prep.sh" "REPO_REVISION")
docker_ver=$(read_launcher_constant "$SCRIPT_DIR/Installers/Docker-Prep.sh" "REPO_VERSION")
linutil_rev=$(read_launcher_constant "$SCRIPT_DIR/Installers/linutil.sh" "LINUTIL_REVISION")
printf '%s\n' \
"commit=${commit}" \
"version=${version}" \
"docker_prep_revision=${docker_rev:-unknown}" \
"docker_prep_version=${docker_ver:-unknown}" \
"linutil_revision=${linutil_rev:-unknown}"
}
# write_update_state records the before/after snapshot used to announce a completed update after restart.
write_update_state() {
local before_file="$1"
local after_file="$2"
local mode="$3"
local release_url="$4"
cat > "$UPDATE_STATE_FILE" << EOF
mode=${mode}
previous_commit=$(awk -F= '$1=="commit"{print $2}' "$before_file")
previous_version=$(awk -F= '$1=="version"{print $2}' "$before_file")
previous_docker_prep_revision=$(awk -F= '$1=="docker_prep_revision"{print $2}' "$before_file")
previous_docker_prep_version=$(awk -F= '$1=="docker_prep_version"{print $2}' "$before_file")
previous_linutil_revision=$(awk -F= '$1=="linutil_revision"{print $2}' "$before_file")
new_commit=$(awk -F= '$1=="commit"{print $2}' "$after_file")
new_version=$(awk -F= '$1=="version"{print $2}' "$after_file")
new_docker_prep_revision=$(awk -F= '$1=="docker_prep_revision"{print $2}' "$after_file")
new_docker_prep_version=$(awk -F= '$1=="docker_prep_version"{print $2}' "$after_file")
new_linutil_revision=$(awk -F= '$1=="linutil_revision"{print $2}' "$after_file")
release_url=${release_url}
EOF
chmod 600 "$UPDATE_STATE_FILE" 2>/dev/null || true
}
# show_pending_update_summary announces a completed update once, then clears the state file.
show_pending_update_summary() {
[[ -f "$UPDATE_STATE_FILE" ]] || return 0
local mode previous_version new_version previous_commit new_commit
local previous_docker_prep_revision new_docker_prep_revision
local previous_docker_prep_version new_docker_prep_version
local previous_linutil_revision new_linutil_revision release_url
mode=$(sed -n 's/^mode=//p' "$UPDATE_STATE_FILE")
previous_version=$(sed -n 's/^previous_version=//p' "$UPDATE_STATE_FILE")
new_version=$(sed -n 's/^new_version=//p' "$UPDATE_STATE_FILE")
previous_commit=$(sed -n 's/^previous_commit=//p' "$UPDATE_STATE_FILE")
new_commit=$(sed -n 's/^new_commit=//p' "$UPDATE_STATE_FILE")
previous_docker_prep_revision=$(sed -n 's/^previous_docker_prep_revision=//p' "$UPDATE_STATE_FILE")
new_docker_prep_revision=$(sed -n 's/^new_docker_prep_revision=//p' "$UPDATE_STATE_FILE")
previous_docker_prep_version=$(sed -n 's/^previous_docker_prep_version=//p' "$UPDATE_STATE_FILE")
new_docker_prep_version=$(sed -n 's/^new_docker_prep_version=//p' "$UPDATE_STATE_FILE")
previous_linutil_revision=$(sed -n 's/^previous_linutil_revision=//p' "$UPDATE_STATE_FILE")
new_linutil_revision=$(sed -n 's/^new_linutil_revision=//p' "$UPDATE_STATE_FILE")
release_url=$(sed -n 's/^release_url=//p' "$UPDATE_STATE_FILE")
echo ""
print_line "=" "$GREEN"
print_centered "UPDATE COMPLETE" "$WHITE"
print_line "=" "$GREEN"
echo ""
if [[ "$mode" == "auto" ]]; then
print_success "Automatic update applied successfully."
else
print_success "Update applied successfully."
fi
echo ""
printf " ${YELLOW}%-14s${NC} %s → %s\n" "VM-Setup" "${previous_version} (${previous_commit:0:12})" "${new_version} (${new_commit:0:12})"
printf " ${YELLOW}%-14s${NC} %s → %s\n" "Docker-Prep" "${previous_docker_prep_version} (${previous_docker_prep_revision:0:12})" "${new_docker_prep_version} (${new_docker_prep_revision:0:12})"
printf " ${YELLOW}%-14s${NC} %s → %s\n" "LinUtil" "${previous_linutil_revision:0:12}" "${new_linutil_revision:0:12}"
echo ""
if [[ "$previous_docker_prep_revision" != "$new_docker_prep_revision" ]]; then
print_status "Docker-Prep pin changed. Review that pin before running Docker Host Preparation."
fi
if [[ -n "$release_url" ]]; then
print_status "Changes: $release_url"
fi
print_line "-" "$GREEN"
pause
rm -f -- "$UPDATE_STATE_FILE"
}
# prepare_update_check verifies git/upstream availability and populates local/remote revisions.
# Sets UPDATE_LOCAL_REV and UPDATE_REMOTE_REV on success.
prepare_update_check() {
UPDATE_LOCAL_REV=""
UPDATE_REMOTE_REV=""
if ((! HAS_GIT)); then
print_error "Git is not installed. Cannot check for updates."
return 1
fi
if [[ ! -d "$SCRIPT_DIR/.git" ]]; then
print_warn "Not a git repository. Skipping update check."
return 1
fi
if ! git_fetch --quiet; then
print_error "Failed to fetch from remote. Check your network connection."
return 1
fi
UPDATE_LOCAL_REV=$(git rev-parse @ 2>/dev/null || true)
if ! UPDATE_REMOTE_REV=$(git rev-parse '@{u}' 2>/dev/null); then
print_error "No upstream branch configured. Skipping update check."
return 1
fi
return 0
}
# apply_repository_update applies a fast-forward update, records a summary, and restarts the menu.
apply_repository_update() {
local mode="${1:-manual}"
local before_file after_file compare_url new_commit
if [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then
if [[ "$mode" == "auto" ]]; then
print_warn "Uncommitted local changes are present."
if [[ ! -t 0 ]]; then
print_status "Non-interactive session; automatic update was skipped."
print_status "Resolve or stash changes, then check for updates again."
return 1
fi
print_status "Choose an option to update anyway, or cancel to keep local changes."
if ! handle_uncommitted_changes "before update"; then
print_status "Update skipped."
return 1
fi
elif ! handle_uncommitted_changes "before update"; then
return 1
fi
fi
before_file=$(mktemp)
after_file=$(mktemp)
capture_component_snapshot > "$before_file"
if ! git pull --ff-only --quiet; then
rm -f -- "$before_file" "$after_file"
print_error "Update failed. Please try manually with 'git pull --ff-only'."
return 1
fi
new_commit=$(git rev-parse HEAD)
{
echo "commit=${new_commit}"
awk -F= '/^readonly SCRIPT_VERSION=/{ gsub(/"/, "", $2); print "version="$2 }' "$SCRIPT_PATH"
echo "docker_prep_revision=$(read_launcher_constant "$SCRIPT_DIR/Installers/Docker-Prep.sh" "REPO_REVISION")"
echo "docker_prep_version=$(read_launcher_constant "$SCRIPT_DIR/Installers/Docker-Prep.sh" "REPO_VERSION")"
echo "linutil_revision=$(read_launcher_constant "$SCRIPT_DIR/Installers/linutil.sh" "LINUTIL_REVISION")"
} > "$after_file"
compare_url="https://github.com/Narehood/VM-Setup/compare/${UPDATE_LOCAL_REV:0:12}...${new_commit:0:12}"
write_update_state "$before_file" "$after_file" "$mode" "$compare_url"
rm -f -- "$before_file" "$after_file"
print_success "Updated successfully. Restarting..."
sleep 1
exec bash "$SCRIPT_PATH"
}
# check_for_updates_interactive prompts the user to download and apply updates from the script's git remote and restarts the script if updates are applied.
# Returns non-zero on failure or when update check cannot be performed (e.g., no git, not a repo, or no upstream).
check_for_updates_interactive() {
echo ""
print_status "Checking for updates..."
if ! prepare_update_check; then
sleep 2
return 1
fi
if [[ "$UPDATE_LOCAL_REV" = "$UPDATE_REMOTE_REV" ]]; then
print_success "Menu is up to date."
sleep 1
return 0
fi
print_warn "New version available."
print_status "Current: ${UPDATE_LOCAL_REV:0:12}"
print_status "Latest: ${UPDATE_REMOTE_REV:0:12}"
if ! confirm_prompt "Download and apply updates? (y/N): " "n"; then
print_status "Update skipped."
sleep 1
return 0
fi
apply_repository_update "manual" || {
sleep 1
return 1
}
}
# check_for_updates_automatic applies available fast-forward updates when AUTO_APPLY_UPDATES is enabled.
check_for_updates_automatic() {
echo ""
print_status "Checking for updates..."
if ! prepare_update_check; then
sleep 2
return 1
fi
if [[ "$UPDATE_LOCAL_REV" = "$UPDATE_REMOTE_REV" ]]; then
print_success "Menu is up to date."
sleep 1
return 0
fi
print_warn "New version available."
print_status "Applying fast-forward update automatically..."
print_status "Current: ${UPDATE_LOCAL_REV:0:12}"
print_status "Latest: ${UPDATE_REMOTE_REV:0:12}"
apply_repository_update "auto" || {
sleep 2
return 1
}
}
# switch_branch switches the script's Git workspace to a selected local or remote branch, offering to stash or discard uncommitted changes, creating a tracking branch if needed, pulling upstream changes when configured, and restarting the menu on success.
switch_branch() {
clear
print_line "=" "$BLUE"
print_centered "SWITCH BRANCH" "$WHITE"
print_line "=" "$BLUE"
echo ""
if ((! HAS_GIT)); then
print_error "Git is not installed."
pause
return 1
fi
if [[ ! -d "$SCRIPT_DIR/.git" ]]; then
print_error "Not a git repository."
pause
return 1
fi
print_status "Fetching branch information..."
if ! git_fetch --all --quiet; then
print_warn "Could not fetch from remote. Showing local branches only."
fi
local current_branch
current_branch=$(get_current_branch)
if [[ -z "$current_branch" || "$current_branch" = "unknown" ]]; then
print_warn "Currently in detached HEAD state."
current_branch="(detached)"
fi
echo -e " Current branch: ${GREEN}$current_branch${NC}"
echo ""
# Use associative array for faster local branch lookup
declare -A local_branches
local branches=()
local branch_display=()
while IFS= read -r branch; do
branch="${branch#\* }"
branch="${branch// /}"
if [[ -n "$branch" ]]; then
local_branches["$branch"]=1
branches+=("$branch")
if [[ "$branch" = "$current_branch" ]]; then
branch_display+=("$branch (current)")
else
branch_display+=("$branch")
fi
fi
done < <(git branch 2>/dev/null) || true
while IFS= read -r branch; do
branch="${branch// /}"
branch="${branch#origin/}"
if [[ -n "$branch" && "$branch" != "HEAD" ]]; then
if [[ -z "${local_branches[$branch]:-}" ]]; then
branches+=("$branch")
branch_display+=("$branch (remote)")
fi
fi
done < <(git branch -r 2>/dev/null | grep -v '\->') || true
if [[ ${#branches[@]} -eq 0 ]]; then
print_error "No branches found."
pause
return 1
fi
echo -e " ${WHITE}Available Branches:${NC}"
echo ""
local i=1
for display in "${branch_display[@]}"; do
printf " ${CYAN}%2d.${NC} %s\n" "$i" "$display"
((i++))
done
echo ""
printf " ${CYAN} 0.${NC} Cancel\n"
echo ""
print_line "-" "$BLUE"
read -rp " Select branch [0-$((${#branches[@]}))] : " selection
if [[ "$selection" = "0" || -z "$selection" ]]; then
print_status "Cancelled."
sleep 1
return 0
fi
if ! [[ "$selection" =~ ^[0-9]+$ ]] || ((selection < 1)) || ((selection > ${#branches[@]})); then
print_error "Invalid selection."
sleep 1
return 1
fi
local selected_branch="${branches[$((selection - 1))]}"
if [[ "$selected_branch" = "$current_branch" ]]; then
print_status "Already on branch '$selected_branch'."
sleep 1
return 0
fi
if ! handle_uncommitted_changes "before switching to $selected_branch"; then
pause
return 1
fi
echo ""
print_status "Switching to branch '$selected_branch'..."
local checkout_output
if git show-ref --verify --quiet "refs/heads/$selected_branch" 2>/dev/null; then
checkout_output=$(git checkout "$selected_branch" 2>&1)
else
checkout_output=$(git checkout -b "$selected_branch" "origin/$selected_branch" 2>&1)
fi
local checkout_status=$?
if ((checkout_status != 0)); then
print_error "Failed to switch branch."
echo -e " ${RED}Details:${NC} $checkout_output"
pause
return 1
fi
local new_branch
new_branch=$(get_current_branch)
if [[ "$new_branch" != "$selected_branch" ]]; then
print_error "Branch switch verification failed."
print_error "Expected: $selected_branch, Got: $new_branch"
pause
return 1
fi
if git rev-parse --abbrev-ref '@{u}' &>/dev/null; then
print_status "Pulling latest changes..."
if ! git pull --ff-only --quiet 2>/dev/null; then
print_warn "Could not pull latest changes. You may need to pull manually."
fi
else
print_warn "No upstream configured for this branch."
fi
print_success "Switched to '$selected_branch'. Restarting menu..."
sleep 1
exec bash "$SCRIPT_PATH"
}
# parse_script_metadata reads the first 20 lines of a script and echoes the value for a metadata header matching `key` (e.g., `REQUIRES_ROOT:` or `DESCRIPTION:`).
parse_script_metadata() {
local script_path="$1"
local key="$2"
head -n 20 "$script_path" 2>/dev/null | grep -i "^# *${key}:" | head -n 1 | sed "s/^# *${key}: *//i" || echo ""
}
# verify_script_checksum Verifies a script's SHA-256 checksum from CHECKSUM_FILE and prompts the user if the checksum is missing or does not match.
verify_script_checksum() {
local script_path="$1"
local script_name
script_name=$(basename "$script_path")
if [[ ! -f "$CHECKSUM_FILE" ]]; then
print_error "Trusted checksum manifest is missing: $CHECKSUM_FILE"
return 1
fi
if ((! HAS_SHA256SUM)); then
print_error "sha256sum is required for integrity verification."
return 1
fi
local expected_hash match_count
match_count=$(awk -v name="$script_name" '$2 == name { count++ } END { print count+0 }' "$CHECKSUM_FILE")
if ((match_count != 1)); then
print_error "Checksum manifest must contain exactly one entry for $script_name"
return 1
fi
expected_hash=$(awk -v name="$script_name" '$2 == name { print $1 }' "$CHECKSUM_FILE")
if [[ ! "$expected_hash" =~ ^[[:xdigit:]]{64}$ ]]; then
print_error "Invalid checksum entry for $script_name"
return 1
fi
local actual_hash
actual_hash=$(sha256sum "$script_path" 2>/dev/null | awk '{print $1}' || echo "")
if [[ "$expected_hash" != "$actual_hash" ]]; then
print_error "Checksum verification FAILED for $script_name"
print_error "Expected: $expected_hash"
print_error "Got: $actual_hash"
print_error "Refusing to execute modified or corrupted script."
return 1
else
print_success "Checksum verified for $script_name"
fi
return 0
}
# execute_script executes an installer from Installers/, validating presence, readability and type, optionally verifying its SHA-256 checksum, honoring REQUIRES_ROOT (prompting to use sudo, run anyway, or cancel), printing DESCRIPTION metadata when present, running the script, and if the script exits with code 42, printing a goodbye message and terminating the application.
execute_script() {
local script_name="$1"
local full_path="$SCRIPT_DIR/Installers/$script_name"
echo ""
if [[ ! -f "$full_path" ]]; then
print_error "Script not found: $full_path"
pause
return 0
fi
if [[ -L "$full_path" ]]; then
print_error "Refusing to execute symlinked script: $full_path"
pause
return 0
fi
if [[ ! -r "$full_path" ]]; then
print_error "Script not readable: $full_path"
pause
return 0
fi
local file_type
if ((HAS_FILE)); then
file_type=$(file -b "$full_path" 2>/dev/null || echo "unknown")
if [[ "$file_type" != "unknown" && ! "$file_type" =~ (shell|bash|sh|text|ASCII|script) ]]; then
print_error "File does not appear to be a shell script: $file_type"
pause
return 0
fi
else
local first_line
first_line=$(head -n 1 "$full_path" 2>/dev/null || echo "")
if [[ ! "$first_line" =~ ^#! ]]; then
print_warn "Cannot verify file type (file command not available)"
if ! confirm_prompt " Continue anyway? (y/N): " "n"; then
pause
return 0
fi
fi
fi
if ! verify_script_checksum "$full_path"; then
print_error "Script verification failed. Aborting."
pause
return 0
fi
[[ ! -x "$full_path" ]] && chmod +x "$full_path" 2>/dev/null || true
local requires_root=""
requires_root=$(parse_script_metadata "$full_path" "REQUIRES_ROOT")
if [[ -z "$requires_root" ]]; then
if grep -qE '^\s*(sudo|apt|dnf|yum|pacman|zypper|systemctl|hostnamectl|usermod|chmod|chown)\s' "$full_path" 2>/dev/null; then
requires_root="true"
fi
fi
if [[ "$requires_root" = "true" ]] && ! is_root; then
print_warn "This script requires root privileges."
echo ""
echo -e " ${WHITE}Options:${NC}"
echo -e " ${CYAN}1.${NC} Run with sudo"
echo -e " ${CYAN}2.${NC} Run anyway (may fail)"
echo -e " ${CYAN}0.${NC} Cancel"
echo ""
read -rp " Select option [0-2]: " root_option
case "$root_option" in
1)
if ((! HAS_SUDO)); then
print_error "sudo is not installed."
pause
return 0
fi
print_status "Executing with sudo..."
echo -e "${GREEN}>>> Executing: $script_name (as root)${NC}"
sleep 0.5
local script_exit=0
sudo bash "$full_path" || script_exit=$?
if ((script_exit == EXIT_APP_CODE)); then
echo -e "\n${GREEN}Goodbye!${NC}"
exit 0
fi
if ((script_exit != 0)); then
pause
fi
return 0
;;
2)
print_warn "Running without root - some operations may fail."
;;
*)
print_status "Cancelled."
sleep 1
return 0
;;
esac
fi
local description=""
description=$(parse_script_metadata "$full_path" "DESCRIPTION")
[[ -n "$description" ]] && print_status "Description: $description"
echo -e "${GREEN}>>> Executing: $script_name${NC}"
sleep 0.5
local script_exit=0
bash "$full_path" || script_exit=$?
if ((script_exit == EXIT_APP_CODE)); then
echo -e "\n${GREEN}Goodbye!${NC}"
exit 0
fi
if ((script_exit != 0)); then
pause
fi
return 0
}
# show_help displays the help and information screen describing menu options, supported distributions, script metadata headers, hidden commands, and current script location/branch.
show_help() {