-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlinux_setup.sh
More file actions
executable file
·1782 lines (1501 loc) · 53.2 KB
/
Copy pathlinux_setup.sh
File metadata and controls
executable file
·1782 lines (1501 loc) · 53.2 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
# =============================================================================
# Linux 系统部署脚本
# 适用系统:Debian 12+、Ubuntu 22.04/24.04
# 功能:模块化部署、依赖处理、模块版本固定下载
# =============================================================================
set -uo pipefail
# === 全局常量 ===
readonly SCRIPT_VERSION="5.0.0"
readonly RUN_COMMIT="${RUN_COMMIT:-}"
readonly MODULE_BASE_URL="https://raw.githubusercontent.com/LucaLin233/Linux"
readonly GITHUB_API_URL="https://api.github.com/repos/LucaLin233/Linux/commits/main"
readonly MODULES_API_URL="https://api.github.com/repos/LucaLin233/Linux/contents/modules"
readonly LINUX_SETUP_TEST_MODE="${LINUX_SETUP_TEST_MODE:-0}"
if [[ "$LINUX_SETUP_TEST_MODE" == "1" ]]; then
LOG_FILE="${LINUX_SETUP_LOG_FILE:-/var/log/linux-setup.log}"
SUMMARY_FILE="${LINUX_SETUP_SUMMARY_FILE:-/root/deployment_summary.txt}"
CACHE_DIR="${LINUX_SETUP_CACHE_DIR:-/var/cache/linux-setup}"
HOSTS_FILE="${LINUX_SETUP_HOSTS_FILE:-/etc/hosts}"
CLOUD_CONFIG_FILE="${LINUX_SETUP_CLOUD_CONFIG_FILE:-/etc/cloud/cloud.cfg}"
else
LOG_FILE="/var/log/linux-setup.log"
SUMMARY_FILE="/root/deployment_summary.txt"
CACHE_DIR="/var/cache/linux-setup"
HOSTS_FILE="/etc/hosts"
CLOUD_CONFIG_FILE="/etc/cloud/cloud.cfg"
fi
readonly SUMMARY_FILE CACHE_DIR HOSTS_FILE CLOUD_CONFIG_FILE
readonly CACHE_MARKER_NAME=".linux-setup-managed-cache-v1"
readonly LINE="============================================================"
TEMP_DIR=""
TEMP_DIR_IDENTITY=""
PREPARED_SCRIPT=""
TOTAL_START_TIME=0
SELECTED_MODULES=()
declare -A MODULE_PREPARATION_ERROR
declare -A MODULE_STATUS
declare -A MODULE_EXEC_TIME
# 模块注册信息从固定 Commit 的 modules/*.sh 元数据动态生成。
declare -A MODULES
declare -A MODULE_DEPS
declare -A MODULE_ORDER_VALUE
declare -A MODULE_FILES
MODULE_ORDER=()
# === 颜色 ===
readonly C_RED='\033[0;31m'
readonly C_GREEN='\033[0;32m'
readonly C_YELLOW='\033[0;33m'
readonly C_CYAN='\033[0;36m'
readonly C_NC='\033[0m'
# =============================================================================
# 基础函数
# =============================================================================
log() {
local message="$1"
local level="${2:-info}"
local timestamp
local color
local icon
timestamp=$(date '+%H:%M:%S')
case "$level" in
info)
color="$C_CYAN"
icon="ℹ️ "
;;
warn)
color="$C_YELLOW"
icon="⚠️ "
;;
error)
color="$C_RED"
icon="❌"
;;
success)
color="$C_GREEN"
icon="✅"
;;
*)
color="$C_NC"
icon="•"
;;
esac
echo -e "${color}${icon} ${message}${C_NC}"
echo "[$timestamp] [$level] $message" >> "$LOG_FILE" 2>/dev/null || true
}
command_exists() {
command -v "$1" >/dev/null 2>&1
}
is_regular_file() {
local file="$1"
[[ -f "$file" && ! -L "$file" ]]
}
atomic_copy_file() {
local source="$1" destination="$2" destination_dir destination_base stage
is_regular_file "$source" || return 1
[[ ! -L "$destination" && ( ! -e "$destination" || -f "$destination" ) ]] || return 1
destination_dir=$(dirname -- "$destination")
destination_base=$(basename -- "$destination")
[[ -d "$destination_dir" && ! -L "$destination_dir" ]] || return 1
stage=$(mktemp "$destination_dir/.${destination_base}.linux-setup.XXXXXX") || return 1
rm -f -- "$stage"
if ! cp -a -- "$source" "$stage" || ! mv -fT -- "$stage" "$destination"; then
rm -f -- "$stage"
return 1
fi
}
atomic_replace_file() {
local source="$1" destination="$2" destination_dir destination_base stage
is_regular_file "$source" || return 1
is_regular_file "$destination" || return 1
destination_dir=$(dirname -- "$destination")
destination_base=$(basename -- "$destination")
[[ -d "$destination_dir" && ! -L "$destination_dir" ]] || return 1
stage=$(mktemp "$destination_dir/.${destination_base}.linux-setup.XXXXXX") || return 1
rm -f -- "$stage"
if ! cp -a -- "$destination" "$stage" ||
! cat -- "$source" > "$stage" ||
! mv -fT -- "$stage" "$destination"; then
rm -f -- "$stage"
return 1
fi
}
backup_initial_and_previous() {
local file="$1" initial="${1}.initial-backup" previous="${1}.previous-backup"
is_regular_file "$file" || return 1
[[ ! -L "$initial" && ( ! -e "$initial" || -f "$initial" ) ]] || return 1
[[ ! -L "$previous" && ( ! -e "$previous" || -f "$previous" ) ]] || return 1
[[ -e "$initial" ]] || atomic_copy_file "$file" "$initial" || return 1
atomic_copy_file "$file" "$previous"
}
temp_directory_trusted() {
local identity
[[ -n "$TEMP_DIR" && -n "$TEMP_DIR_IDENTITY" && -d "$TEMP_DIR" && ! -L "$TEMP_DIR" ]] || return 1
identity=$(stat -c '%d:%i:%u:%a' -- "$TEMP_DIR" 2>/dev/null) || return 1
[[ "$identity" == "$TEMP_DIR_IDENTITY" && "$identity" == *":$EUID:700" ]]
}
remove_owned_temp_directory() {
[[ -n "$TEMP_DIR" ]] || return 0
temp_directory_trusted || {
log "临时目录身份不可验证,拒绝删除:$TEMP_DIR" "error"
return 1
}
# /tmp is sticky; mode 0700 excludes other users from the owned directory.
# Never authorize recursive removal from a caller-supplied path alone.
rm -rf -- "$TEMP_DIR" || return 1
[[ ! -e "$TEMP_DIR" && ! -L "$TEMP_DIR" ]] || return 1
TEMP_DIR=""
TEMP_DIR_IDENTITY=""
}
cleanup() {
local exit_code=$?
if [[ -n "$TEMP_DIR" ]]; then
if (( exit_code == 0 )); then
remove_owned_temp_directory || exit_code=1
else
log "脚本异常退出,临时文件保留在:$TEMP_DIR" "error"
log "详细日志:$LOG_FILE" "error"
fi
fi
exit "$exit_code"
}
init_logging() {
mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || true
if ! touch "$LOG_FILE" 2>/dev/null; then
echo "⚠️ 无法写入日志文件 $LOG_FILE,将仅输出到终端"
LOG_FILE="/dev/null"
else
: > "$LOG_FILE"
fi
}
create_temp_dir() {
if ! TEMP_DIR=$(mktemp -d -p /tmp linux-setup.XXXXXX); then
log "无法创建安全临时目录" "error"
exit 1
fi
chmod 700 "$TEMP_DIR" || return 1
TEMP_DIR_IDENTITY=$(stat -c '%d:%i:%u:%a' -- "$TEMP_DIR") || return 1
temp_directory_trusted
}
# =============================================================================
# 系统检查
# =============================================================================
pre_check() {
if (( EUID != 0 )); then
log "需要 root 权限运行" "error"
exit 1
fi
if [[ ! -r /etc/os-release ]]; then
log "无法读取 /etc/os-release,无法识别系统" "error"
exit 1
fi
local os_id
local version_id
local major_version
# shellcheck disable=SC1091 # /etc/os-release is provided by the target OS, not this repository.
. /etc/os-release
os_id="${ID:-}"
version_id="${VERSION_ID:-}"
major_version="${version_id%%.*}"
case "$os_id" in
debian)
if [[ ! "$major_version" =~ ^[0-9]+$ ]] || (( major_version < 12 )); then
log "仅支持 Debian 12 或更高版本,当前版本:${version_id:-未知}" "error"
exit 1
fi
;;
ubuntu)
case "$version_id" in
22.04|24.04) ;;
*)
log "仅支持 Ubuntu 22.04 或 24.04,当前版本:${version_id:-未知}" "error"
exit 1
;;
esac
;;
*)
log "仅支持 Debian 12+、Ubuntu 22.04/24.04,当前系统:${PRETTY_NAME:-${os_id:-未知}}" "error"
exit 1
;;
esac
log "检测到受支持系统:${PRETTY_NAME:-$os_id $version_id}"
local free_space_kb
free_space_kb=$(LANG=C df / 2>/dev/null |
awk 'NR == 2 {print $4}' |
tr -cd '0-9')
if [[ -n "$free_space_kb" && "$free_space_kb" != "0" ]]; then
if (( free_space_kb < 1048576 )); then
log "根分区可用空间不足 1GB" "error"
exit 1
fi
fi
if ! curl -fsI \
--connect-timeout 5 \
--max-time 10 \
"https://raw.githubusercontent.com/" >/dev/null 2>&1; then
log "无法连接 raw.githubusercontent.com,模块下载可能失败" "warn"
local choice
read -r -p "是否继续执行?[y/N]: " choice
if [[ ! "$choice" =~ ^[Yy]$ ]]; then
log "用户取消执行" "info"
exit 0
fi
fi
log "系统预检查通过" "success"
}
# =============================================================================
# 旧版 APT 软件源备份迁移
# =============================================================================
migrate_legacy_apt_source_backups() {
local source_dir="/etc/apt/sources.list.d"
local state_dir="/var/lib/linux-setup/apt-source-backups"
local base
local suffix
local source
local destination
[[ -d "$source_dir" ]] || return 0
install -d -m 0700 "$state_dir"
for base in docker.sources nexttrace.sources xanmod-release.list xanmod-release.sources; do
for suffix in initial-backup previous-backup initial-absent previous-absent initial-unknown; do
source="$source_dir/${base}.${suffix}"
[[ -e "$source" || -L "$source" ]] || continue
destination="$state_dir/${base}.${suffix}"
if [[ -e "$destination" || -L "$destination" ]]; then
destination="${destination}.legacy.$(date +%s).$$"
fi
mv "$source" "$destination" || {
log "无法迁移旧版 APT 软件源备份:$source" "warn"
continue
}
chmod 600 "$destination" 2>/dev/null || true
done
done
}
# =============================================================================
# 依赖安装
# =============================================================================
install_dependencies() {
log "检查基础依赖"
local required_deps=(
"curl:curl"
"wget:wget"
"git:git"
"jq:jq"
"rsync:rsync"
"sudo:sudo"
"dig:dnsutils"
"crontab:cron"
"fuser:psmisc"
"locale-gen:locales"
"gpg:gpg"
"gpg-agent:gpg-agent"
"dirmngr:dirmngr"
)
local missing_packages=()
local dependency
local command_name
local package_name
for dependency in "${required_deps[@]}"; do
command_name="${dependency%%:*}"
package_name="${dependency#*:}"
if ! command_exists "$command_name"; then
missing_packages+=("$package_name")
fi
done
if (( ${#missing_packages[@]} == 0 )); then
log "基础依赖已满足"
return 0
fi
log "安装缺失依赖:${missing_packages[*]}"
if ! apt-get update -qq; then
log "无法更新 APT 软件包索引" "error"
exit 1
fi
if ! apt-get install -y "${missing_packages[@]}"; then
log "基础依赖安装失败" "error"
exit 1
fi
log "基础依赖安装完成" "success"
}
# =============================================================================
# 系统更新与 hosts 修复
# =============================================================================
system_update() {
if apt-get update -qq; then
log "软件包索引已更新" "success"
else
log "软件包索引更新失败,后续模块可能无法安装软件包" "warn"
fi
}
validate_hostname_value() {
local hostname_value="$1"
(( ${#hostname_value} >= 1 && ${#hostname_value} <= 253 )) || return 1
[[ "$hostname_value" != *..* ]] || return 1
[[ "$hostname_value" =~ ^[A-Za-z0-9]$ ||
"$hostname_value" =~ ^[A-Za-z0-9][A-Za-z0-9.-]*[A-Za-z0-9]$ ]]
}
render_cloud_config() {
local source="$1" output="$2"
awk '
{
content = $0
sub(/^ */, "", content)
}
content ~ /^manage_etc_hosts *:/ {
if (!written) {
indentation = $0
sub(/[^ ].*$/, "", indentation)
print indentation "manage_etc_hosts: false"
written = 1
}
next
}
{ print }
END { if (!written) print "manage_etc_hosts: false" }
' "$source" > "$output"
}
hosts_contains_hostname() {
local hosts_file="$1" hostname_value="$2"
awk -v hostname="$hostname_value" '
$1 == "127.0.1.1" {
data = $0
sub(/#.*/, "", data)
count = split(data, fields, /[[:space:]]+/)
for (field = 1; field <= count; field++) {
if (fields[field] == hostname) found = 1
}
}
END { exit !found }
' "$hosts_file"
}
render_hosts_file() {
local source="$1" output="$2" hostname_value="$3"
awk -v hostname="$hostname_value" '
$1 == "127.0.1.1" && !updated {
data = $0
comment_position = index(data, "#")
if (comment_position) {
comment = substr(data, comment_position)
data = substr(data, 1, comment_position - 1)
} else {
comment = ""
}
count = split(data, fields, /[[:space:]]+/)
present = 0
for (field = 1; field <= count; field++) {
if (fields[field] == hostname) present = 1
}
if (present) {
print
} else if (comment_position) {
spacing = data
sub(/^.*[^[:space:]]/, "", spacing)
sub(/[[:space:]]+$/, "", data)
if (spacing == "") spacing = " "
print data " " hostname spacing comment
} else {
print $0 " " hostname
}
updated = 1
next
}
{ print }
END { if (!updated) print "127.0.1.1 " hostname }
' "$source" > "$output"
}
fix_hosts_file() {
local hostname_value cloud_temp="" hosts_temp=""
local cloud_changed=false hosts_changed=false cloud_applied=false
if ! hostname_value=$(hostname 2>/dev/null) ||
! validate_hostname_value "$hostname_value"; then
log "主机名为空或格式不安全,拒绝修改 hosts 配置" "error"
return 1
fi
if [[ -e "$CLOUD_CONFIG_FILE" || -L "$CLOUD_CONFIG_FILE" ]]; then
if ! is_regular_file "$CLOUD_CONFIG_FILE"; then
log "cloud-init 配置不是安全的普通文件:$CLOUD_CONFIG_FILE" "error"
return 1
fi
cloud_temp=$(mktemp "$TEMP_DIR/cloud.cfg.XXXXXX") || return 1
render_cloud_config "$CLOUD_CONFIG_FILE" "$cloud_temp" || return 1
cmp -s -- "$CLOUD_CONFIG_FILE" "$cloud_temp" || cloud_changed=true
fi
if ! is_regular_file "$HOSTS_FILE"; then
log "hosts 配置不是安全的普通文件:$HOSTS_FILE" "error"
return 1
fi
if ! hosts_contains_hostname "$HOSTS_FILE" "$hostname_value"; then
hosts_temp=$(mktemp "$TEMP_DIR/hosts.XXXXXX") || return 1
render_hosts_file "$HOSTS_FILE" "$hosts_temp" "$hostname_value" || return 1
hosts_changed=true
fi
if [[ "$cloud_changed" == "true" ]]; then
backup_initial_and_previous "$CLOUD_CONFIG_FILE" || {
log "无法安全备份 cloud-init 配置" "error"
return 1
}
fi
if [[ "$hosts_changed" == "true" ]]; then
backup_initial_and_previous "$HOSTS_FILE" || {
log "无法安全备份 hosts 配置" "error"
return 1
}
fi
if [[ "$cloud_changed" == "true" ]]; then
if ! atomic_replace_file "$cloud_temp" "$CLOUD_CONFIG_FILE"; then
log "无法安全写入 cloud-init 配置" "error"
return 1
fi
cloud_applied=true
fi
if [[ "$hosts_changed" == "true" ]] &&
! atomic_replace_file "$hosts_temp" "$HOSTS_FILE"; then
log "无法安全写入 hosts 配置" "error"
if [[ "$cloud_applied" == "true" ]] &&
! atomic_replace_file "${CLOUD_CONFIG_FILE}.previous-backup" "$CLOUD_CONFIG_FILE"; then
log "cloud-init 配置回滚失败,请从 previous-backup 手动恢复" "error"
fi
return 1
fi
if [[ "$cloud_changed" == "true" || "$hosts_changed" == "true" ]]; then
log "已修复 hostname 与 hosts 配置" "success"
fi
return 0
}
# =============================================================================
# 模块选择
# =============================================================================
select_deployment_mode() {
echo
echo "$LINE"
echo "部署模式选择:"
echo "1) 🚀 全部安装(安装全部 ${#MODULE_ORDER[@]} 个模块)"
echo "2) 🎯 自定义选择(按需选择模块)"
echo "3) ❌ 退出脚本"
echo
local mode_choice
read -r -p "请选择模式 [1-3]: " mode_choice
case "$mode_choice" in
1)
SELECTED_MODULES=("${MODULE_ORDER[@]}")
log "已选择全部模块"
;;
2)
custom_module_selection
;;
3)
log "用户选择退出" "info"
exit 0
;;
*)
log "无效选择,已取消部署" "error"
exit 1
;;
esac
}
custom_module_selection() {
local index=1
local module
local selection
local number
local max_index
local selected=()
echo
echo "可用模块:"
for module in "${MODULE_ORDER[@]}"; do
echo " $index) $module - ${MODULES[$module]}"
((index++))
done
echo
echo "请输入要安装的模块编号,多个编号用空格分隔,例如:1 3 5"
echo "输入 q 取消并退出。"
read -r -p "请选择: " selection
if [[ "$selection" == "q" || "$selection" == "Q" ]]; then
log "用户取消选择" "info"
exit 0
fi
max_index=${#MODULE_ORDER[@]}
for number in $selection; do
if [[ "$number" =~ ^[0-9]+$ ]] &&
(( number >= 1 && number <= max_index )); then
selected+=("${MODULE_ORDER[number - 1]}")
else
log "跳过无效编号:$number" "warn"
fi
done
if (( ${#selected[@]} == 0 )); then
log "未选择有效模块" "error"
exit 1
fi
SELECTED_MODULES=("${selected[@]}")
log "已选择模块:${SELECTED_MODULES[*]}"
}
# =============================================================================
# 依赖解析
# =============================================================================
module_is_selected() {
local target="$1"
local module
for module in "${SELECTED_MODULES[@]}"; do
[[ "$module" == "$target" ]] && return 0
done
return 1
}
module_in_list() {
local target="$1"
shift
local module
for module in "$@"; do
[[ "$module" == "$target" ]] && return 0
done
return 1
}
resolve_dependencies() {
local all_needed=()
local added_deps=()
local sorted=()
local module
local choice
local continue_choice
local -A visit_state=()
collect_dependencies() {
local current_module="$1"
local dependency
case "${visit_state[$current_module]:-}" in
visiting)
log "检测到模块循环依赖:$current_module" "error"
return 1
;;
done)
return 0
;;
esac
if [[ -z "${MODULES[$current_module]:-}" ]]; then
log "依赖的模块不存在或不可用:$current_module" "error"
return 1
fi
visit_state["$current_module"]="visiting"
for dependency in ${MODULE_DEPS[$current_module]:-}; do
[[ -n "${MODULES[$dependency]:-}" ]] || continue
collect_dependencies "$dependency" || return 1
done
visit_state["$current_module"]="done"
all_needed+=("$current_module")
}
for module in "${SELECTED_MODULES[@]}"; do
collect_dependencies "$module" || return 1
done
for module in "${all_needed[@]}"; do
if ! module_is_selected "$module"; then
added_deps+=("$module")
fi
done
if (( ${#added_deps[@]} > 0 )); then
echo
log "检测到模块依赖:${added_deps[*]}" "warn"
read -r -p "是否自动添加依赖模块?[Y/n]: " choice
choice="${choice:-Y}"
if [[ ! "$choice" =~ ^[Yy]$ ]]; then
log "未自动添加依赖模块,将仅执行已选择的模块" "warn"
read -r -p "确认系统已满足依赖并继续执行?[y/N]: " continue_choice
if [[ ! "$continue_choice" =~ ^[Yy]$ ]]; then
log "已取消部署" "info"
exit 0
fi
all_needed=("${SELECTED_MODULES[@]}")
fi
fi
# 无论用户输入编号的先后如何,都按模块声明的稳定顺序执行。
for module in "${MODULE_ORDER[@]}"; do
if module_in_list "$module" "${all_needed[@]}"; then
sorted+=("$module")
fi
done
SELECTED_MODULES=("${sorted[@]}")
if (( ${#added_deps[@]} > 0 )) && [[ "$choice" =~ ^[Yy]$ ]]; then
log "已加入依赖,最终模块顺序:${SELECTED_MODULES[*]}" "success"
fi
}
# =============================================================================
# GitHub Commit 与模块下载
# =============================================================================
is_valid_commit() {
local commit="$1"
[[ "$commit" =~ ^[0-9a-f]{40}$ ]]
}
get_latest_commit() {
local commit_hash
commit_hash=$(
curl -fsSL \
--connect-timeout 5 \
--max-time 15 \
"$GITHUB_API_URL" 2>/dev/null |
grep -m 1 '"sha"' |
cut -d '"' -f 4 |
cut -c 1-40
) || true
if [[ "$commit_hash" =~ ^[0-9a-f]{40}$ ]]; then
echo "$commit_hash"
return 0
fi
return 1
}
validate_bash_script() {
local file="$1" first_line
is_regular_file "$file" || return 1
[[ -s "$file" ]] || return 1
IFS= read -r first_line < "$file" || return 1
case "$first_line" in
'#!/usr/bin/env bash'|'#!/bin/bash') ;;
*) return 1 ;;
esac
bash -n "$file" >/dev/null 2>&1
}
download_with_retry() {
local url="$1" output="$2" validator="${3:-validate_bash_script}"
local max_attempts=3 attempt
for ((attempt = 1; attempt <= max_attempts; attempt++)); do
if curl -fsSL --connect-timeout 10 --max-time 60 "$url" -o "$output" &&
"$validator" "$output"; then
return 0
fi
rm -f -- "$output"
if (( attempt < max_attempts )); then
log "下载或脚本验证失败,2 秒后重试($attempt/$max_attempts)..." "warn"
sleep 2
fi
done
return 1
}
read_module_metadata() {
local module_file="$1"
local key="$2"
awk -v key="$key" '
$0 ~ "^#[[:space:]]*linux-setup:" key "=" {
value = $0
sub("^#[[:space:]]*linux-setup:" key "=[[:space:]]*", "", value)
sub("[[:space:]]*$", "", value)
print value
exit
}
' "$module_file"
}
register_module() {
local module="$1"
local module_file="$2"
local name
local order
local depends
local enabled
local dependency
if ! bash -n "$module_file"; then
log "模块语法检查失败,已跳过:$module" "error"
return 1
fi
name=$(read_module_metadata "$module_file" "name")
order=$(read_module_metadata "$module_file" "order")
depends=$(read_module_metadata "$module_file" "depends")
enabled=$(read_module_metadata "$module_file" "enabled")
name="${name:-$module}"
order="${order:-900}"
enabled="${enabled:-true}"
if [[ "$enabled" == "false" ]]; then
return 2
fi
if [[ "$enabled" != "true" ]]; then
log "模块 enabled 元数据无效,已跳过:$module" "error"
return 1
fi
if [[ ! "$order" =~ ^[0-9]+$ ]] || (( 10#$order > 999999 )); then
log "模块 order 元数据无效,已跳过:$module" "error"
return 1
fi
for dependency in $depends; do
if [[ ! "$dependency" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
log "模块依赖名称无效,已跳过:$module -> $dependency" "error"
return 1
fi
done
MODULES["$module"]="$name"
MODULE_DEPS["$module"]="$depends"
MODULE_ORDER_VALUE["$module"]="$((10#$order))"
MODULE_FILES["$module"]="$module_file"
}
validate_module_dependencies() {
local module dependency
for module in "${!MODULES[@]}"; do
for dependency in ${MODULE_DEPS[$module]:-}; do
if [[ -z "${MODULES[$dependency]:-}" ]]; then
MODULE_PREPARATION_ERROR["$module"]="依赖不存在或已禁用:$dependency"
log "$module:${MODULE_PREPARATION_ERROR[$module]}" "warn"
fi
done
done
}
register_unavailable_module() {
local module="$1" reason="$2"
MODULES["$module"]="$module(准备失败)"
MODULE_ORDER_VALUE["$module"]=900
MODULE_DEPS["$module"]=""
MODULE_PREPARATION_ERROR["$module"]="$reason"
}
build_module_order() {
local module
mapfile -t MODULE_ORDER < <(
for module in "${!MODULES[@]}"; do
printf '%010d\t%s\n' \
"${MODULE_ORDER_VALUE[$module]}" \
"$module"
done |
sort -k1,1n -k2,2 |
awk -F '\t' '{print $2}'
)
}
download_module() {
local module="$1"
local module_file="$TEMP_DIR/${module}.sh"
local module_url
module_url="$MODULE_BASE_URL/$RUN_COMMIT/modules/${module}.sh"
if ! download_with_retry "$module_url" "$module_file"; then
return 1
fi
chmod 700 "$module_file"
}
discover_and_prepare_modules() {
local index_file="$TEMP_DIR/modules-index.json"
local file_name
local module
local module_file
local register_result
local -a module_files=()
log "从固定 Commit 发现部署模块:${RUN_COMMIT:0:7}"
if ! curl -fsSL \
--connect-timeout 10 \
--max-time 30 \
"${MODULES_API_URL}?ref=${RUN_COMMIT}" \
-o "$index_file"; then
log "无法获取 modules 目录列表" "error"
return 1
fi
if ! jq -e 'type == "array"' "$index_file" >/dev/null 2>&1; then
log "GitHub modules 目录响应格式异常" "error"
return 1
fi
mapfile -t module_files < <(
jq -r '
.[]
| select(.type == "file")
| .name
| select(test("^[a-z0-9][a-z0-9-]*\\.sh$"))
' "$index_file" |
sort -u
)
if (( ${#module_files[@]} == 0 )); then
log "modules 目录中没有符合命名规范的脚本" "error"
return 1
fi
for file_name in "${module_files[@]}"; do
module="${file_name%.sh}"
module_file="$TEMP_DIR/$file_name"
if ! download_module "$module"; then
register_unavailable_module "$module" "下载或完整性验证失败"
log "模块准备失败,选择后将计入失败:$module" "error"
continue
fi
if register_module "$module" "$module_file"; then
continue
else
register_result=$?
fi
if (( register_result != 2 )); then
register_unavailable_module "$module" "语法或元数据验证失败"
rm -f "$module_file"
fi
done
validate_module_dependencies
build_module_order
if (( ${#MODULE_ORDER[@]} == 0 )); then
log "没有可用的部署模块" "error"
return 1
fi
log "模块发现完成:${#MODULE_ORDER[@]} 个可用模块" "success"
}
# =============================================================================
# 脚本自更新
# =============================================================================
cache_digest_path() {
printf '%s.sha256\n' "$1"
}
file_owner_and_mode_are_safe() {
local file="$1" owner mode
owner=$(stat -c '%u' -- "$file" 2>/dev/null) || return 1
mode=$(stat -c '%a' -- "$file" 2>/dev/null) || return 1
[[ "$owner" == "$EUID" && "$mode" =~ ^[0-7]{3,4}$ ]] || return 1