-
-
Notifications
You must be signed in to change notification settings - Fork 551
/
trans.sh
5280 lines (4494 loc) · 164 KB
/
trans.sh
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/ash
# shellcheck shell=dash
# shellcheck disable=SC2086,SC3047,SC3036,SC3010,SC3001,SC3060
# alpine 默认使用 busybox ash
# 出错后停止运行,将进入到登录界面,防止失联
set -eE
# 用于判断 reinstall.sh 和 trans.sh 是否兼容
# shellcheck disable=SC2034
SCRIPT_VERSION=4BACD833-A585-23BA-6CBB-9AA4E08E0002
TRUE=0
FALSE=1
EFI_UUID=C12A7328-F81F-11D2-BA4B-00A0C93EC93B
error() {
color='\e[31m'
plain='\e[0m'
echo -e "${color}***** ERROR *****${plain}" >&2
echo -e "${color}Error: $*${plain}" >&2
}
info() {
color='\e[32m'
plain='\e[0m'
echo -e "${color}***** $(echo "$*" | to_upper) *****${plain}" >&2
}
error_and_exit() {
error "$@"
exit 1
}
trap_err() {
line_no=$1
ret_no=$2
error "Line $line_no return $ret_no"
if [ -f "/trans.sh" ]; then
sed -n "$line_no"p /trans.sh
fi
}
is_run_from_locald() {
[[ "$0" = "/etc/local.d/*" ]]
}
add_community_repo() {
# 先检查原来的repo是不是egde
if grep -q '^http.*/edge/main$' /etc/apk/repositories; then
alpine_ver=edge
else
alpine_ver=v$(cut -d. -f1,2 </etc/alpine-release)
fi
if ! grep -q "^http.*/$alpine_ver/community$" /etc/apk/repositories; then
alpine_mirror=$(grep '^http.*/main$' /etc/apk/repositories | sed 's,/[^/]*/main$,,' | head -1)
echo $alpine_mirror/$alpine_ver/community >>/etc/apk/repositories
fi
}
# 有时网络问题下载失败,导致脚本中断
# 因此需要重试
apk() {
retry 5 command apk "$@" >&2
}
# 在没有设置 set +o pipefail 的情况下,限制下载大小:
# retry 5 command wget | head -c 1048576 会触发 retry,下载 5 次
# command wget "$@" --tries=5 | head -c 1048576 不会触发 wget 自带的 retry,只下载 1 次
wget() {
echo "$@" | grep -o 'http[^ ]*' >&2
if command wget 2>&1 | grep -q BusyBox; then
# busybox wget 没有重试功能
# 好像默认永不超时
retry 5 command wget "$@" -T 10
else
# 原版 wget 自带重试功能
command wget --tries=5 --progress=bar:force "$@"
fi
}
is_have_cmd() {
command -v "$1" >/dev/null
}
is_have_cmd_on_disk() {
os_dir=$1
cmd=$2
for bin_dir in /bin /sbin /usr/bin /usr/sbin; do
if [ -f "$os_dir$bin_dir/$cmd" ]; then
return
fi
done
return 1
}
retry() {
max_try=$1
shift
for i in $(seq $max_try); do
if "$@"; then
return
else
ret=$?
if [ $i -ge $max_try ]; then
return $ret
fi
sleep 1
fi
done
}
download() {
url=$1
path=$2
# 有ipv4地址无ipv4网关的情况下,aria2可能会用ipv4下载,而不是ipv6
# axel 在 lightsail 上会占用大量cpu
# aria2 下载 fedora 官方镜像链接会将meta4文件下载下来,而且占用了指定文件名,造成重命名失效。而且无法指定目录
# https://download.opensuse.org/distribution/leap/15.5/appliances/openSUSE-Leap-15.5-Minimal-VM.x86_64-kvm-and-xen.qcow2
# https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-o
# 构造 aria2 参数
# 没有指定文件名的情况
if [ -z "$path" ]; then
save=""
else
# 文件名是绝对路径
if [[ "$path" = '/*' ]]; then
save="-d / -o $path"
else
# 文件名是相对路径
save="-o $path"
fi
fi
if ! is_have_cmd aria2c; then
apk add aria2
fi
# stdbuf 在 coreutils 包里面
if ! is_have_cmd stdbuf; then
apk add coreutils
fi
# 阿里云源限速,而且检测 user-agent 禁止 axel/aria2 下载
# aria2 默认 --max-tries 5
# 默认 --max-tries=5,但以下情况服务器出错,aria2不会重试,而是直接返回错误
# 因此添加 for 循环
# [ERROR] CUID#7 - Download aborted. URI=https://aka.ms/manawindowsdrivers
# Exception: [AbstractCommand.cc:351] errorCode=1 URI=https://aka.ms/manawindowsdrivers
# -> [SocketCore.cc:1019] errorCode=1 SSL/TLS handshake failure: `not signed by known authorities or invalid'
# 用 if 的话,报错不会中断脚本
# if aria2c xxx; then
# return
# fi
# --user-agent=Wget/1.21.1 \
echo "$url"
retry 5 stdbuf -oL -eL aria2c -x4 \
--allow-overwrite=true \
--summary-interval=0 \
--max-tries 1 \
$save "$url"
}
update_part() {
sleep 1
sync
# partprobe
if is_have_cmd partprobe; then
partprobe /dev/$xda 2>/dev/null
fi
# partx
# https://access.redhat.com/solutions/199573
if is_have_cmd partx; then
partx -u /dev/$xda
fi
# mdev
# mdev 不会删除 /dev/disk/ 的旧分区,因此手动删除
# 如果 rm -rf 的时候刚好 mdev 在创建链接,rm -rf 会报错 Directory not empty
# 因此要先停止 mdev 服务
# 还要删除 /dev/$xda*?
ensure_service_stopped mdev
rm -rf /dev/disk/*
# 没挂载 modloop 时会提示
# modprobe: can't change directory to '/lib/modules': No such file or directory
# 因此强制不显示上面的提示
mdev -sf 2>/dev/null
ensure_service_started mdev 2>/dev/null
sleep 1
}
is_efi() {
if [ -n "$force" ]; then
[ "$force" = efi ]
else
[ -d /sys/firmware/efi/ ]
fi
}
is_use_cloud_image() {
[ -n "$cloud_image" ] && [ "$cloud_image" = 1 ]
}
is_allow_ping() {
[ -n "$allow_ping" ] && [ "$allow_ping" = 1 ]
}
setup_nginx() {
apk add nginx
# shellcheck disable=SC2154
wget $confhome/logviewer.html -O /logviewer.html
wget $confhome/logviewer-nginx.conf -O /etc/nginx/http.d/default.conf
if [ -z "$web_port" ]; then
web_port=80
fi
sed -i "s/@WEB_PORT@/$web_port/gi" /etc/nginx/http.d/default.conf
# rc-service -q nginx start
if pgrep nginx >/dev/null; then
nginx -s reload
else
nginx
fi
}
setup_websocketd() {
apk add websocketd
wget $confhome/logviewer.html -O /tmp/index.html
apk add coreutils
if [ -z "$web_port" ]; then
web_port=80
fi
pkill websocketd || true
# websocketd 遇到 \n 才推送,因此要转换 \r 为 \n
websocketd --port "$web_port" --loglevel=fatal --staticdir=/tmp \
stdbuf -oL -eL sh -c "tail -fn+0 /reinstall.log | tr '\r' '\n'" &
}
get_approximate_ram_size() {
# lsmem 需要 util-linux
if false && is_have_cmd lsmem; then
ram_size=$(lsmem -b 2>/dev/null | grep 'Total online memory:' | awk '{ print $NF/1024/1024 }')
fi
if [ -z $ram_size ]; then
ram_size=$(free -m | awk '{print $2}' | sed -n '2p')
fi
echo "$ram_size"
}
setup_web_if_enough_ram() {
total_ram=$(get_approximate_ram_size)
# 512内存才安装
if [ $total_ram -gt 400 ]; then
# lighttpd 虽然运行占用内存少,但安装占用空间大
# setup_lighttpd
# setup_nginx
setup_websocketd
fi
}
setup_lighttpd() {
apk add lighttpd
ln -sf /reinstall.html /var/www/localhost/htdocs/index.html
rc-service -q lighttpd start
}
get_ttys() {
prefix=$1
# shellcheck disable=SC2154
wget $confhome/ttys.sh -O- | sh -s $prefix
}
find_xda() {
# 出错后再运行脚本,硬盘可能已经格式化,之前记录的分区表 id 无效
# 因此找到 xda 后要保存 xda 到 /config/xda
# 先读取之前保存的
if xda=$(get_config xda 2>/dev/null) && [ -n "$xda" ]; then
return
fi
# 防止 $main_disk 为空
if [ -z "$main_disk" ]; then
error_and_exit "cmdline main_disk is empty."
fi
# busybox fdisk/lsblk/blkid 不显示 mbr 分区表 id
# 可用以下工具:
# fdisk 在 util-linux-misc 里面,占用大
# sfdisk 占用小
# lsblk
# blkid
tool=sfdisk
is_have_cmd $tool && need_install_tool=false || need_install_tool=true
if $need_install_tool; then
apk add $tool
fi
if [ "$tool" = sfdisk ]; then
# sfdisk
for disk in $(get_all_disks); do
if sfdisk --disk-id "/dev/$disk" | sed 's/0x//' | grep -ix "$main_disk"; then
xda=$disk
break
fi
done
else
# lsblk
xda=$(lsblk --nodeps -rno NAME,PTUUID | grep -iw "$main_disk" | awk '{print $1}')
fi
if [ -n "$xda" ]; then
set_config xda "$xda"
else
error_and_exit "Could not find xda: $main_disk"
fi
if $need_install_tool; then
apk del $tool
fi
}
get_all_disks() {
# shellcheck disable=SC2010
ls /sys/block/ | grep -Ev '^(loop|sr|nbd)'
}
extract_env_from_cmdline() {
# 提取 finalos/extra 到变量
for prefix in finalos extra; do
while read -r line; do
if [ -n "$line" ]; then
key=$(echo $line | cut -d= -f1)
value=$(echo $line | cut -d= -f2-)
eval "$key='$value'"
fi
done < <(xargs -n1 </proc/cmdline | grep "^${prefix}_" | sed "s/^${prefix}_//")
done
}
ensure_service_started() {
service=$1
if ! rc-service -q $service status; then
if ! retry 5 rc-service -q $service start; then
error_and_exit "Failed to start $service."
fi
fi
}
ensure_service_stopped() {
service=$1
if rc-service -q $service status; then
if ! retry 5 rc-service -q $service stop; then
error_and_exit "Failed to stop $service."
fi
fi
}
mod_motd() {
# 安装后 alpine 后要恢复默认
# 自动安装失败后,可能手动安装 alpine,因此无需判断 $distro
file=/etc/motd
if ! [ -e $file.orig ]; then
cp $file $file.orig
# shellcheck disable=SC2016
echo "mv "\$mnt$file.orig" "\$mnt$file"" |
insert_into_file "$(which setup-disk)" before 'cleanup_chroot_mounts "\$mnt"'
cat <<EOF >$file
Reinstalling...
To view logs run:
tail -fn+1 /reinstall.log
EOF
fi
}
umount_all() {
dirs="/mnt /os /iso /wim /installer /nbd /nbd-boot /nbd-efi /root /nix"
regex=$(echo "$dirs" | sed 's, ,|,g')
if mounts=$(mount | grep -Ew "$regex" | awk '{print $3}' | tac); then
for mount in $mounts; do
echo "umount $mount"
umount $mount
done
fi
}
# 可能脚本不是首次运行,先清理之前的残留
clear_previous() {
if is_have_cmd vgchange; then
umount -R /os /nbd || true
vgchange -an
apk add device-mapper
dmsetup remove_all
fi
disconnect_qcow
# 安装 arch 有 gpg-agent 进程驻留
pkill gpg-agent || true
rc-service -q --ifexists --ifstarted nix-daemon stop
swapoff -a
umount_all
# 以下情况 umount -R /1 会提示 busy
# mount /file1 /1
# mount /1/file2 /2
}
# virt-what 自动安装 dmidecode,因此同时缓存
cache_dmi_and_virt() {
if ! [ "$_dmi_and_virt_cached" = 1 ]; then
apk add virt-what
# 区分 kvm 和 virtio,原因:
# 1. 阿里云 c8y virt-what 不显示 kvm
# 2. 不是所有 kvm 都需要 virtio 驱动,例如 aws nitro
# 3. virt-what 不会检测 virtio
_virt=$(
virt-what
# hyper-v 环境下 modprobe virtio_scsi 也会创建 /sys/bus/virtio/drivers/virtio_scsi
# 因此用 devices 判断更准确,有设备时才有 /sys/bus/virtio/drivers/*
# 或者加上 lspci 检测?
# 不要用 ls /sys/bus/virtio/devices/* && echo virtio
# 因为有可能返回值不为 0 而中断脚本
if ls /sys/bus/virtio/devices/* >/dev/null 2>&1; then
echo virtio
fi
)
_dmi=$(dmidecode | grep -E '(Manufacturer|Asset Tag|Vendor): ' | awk -F': ' '{print $2}')
_dmi_and_virt_cached=1
apk del virt-what
fi
}
is_virt() {
cache_dmi_and_virt
[ -n "$_virt" ]
}
is_virt_contains() {
cache_dmi_and_virt
echo "$_virt" | grep -Eiwq "$1"
}
is_dmi_contains() {
# Manufacturer: Alibaba Cloud
# Manufacturer: Tencent Cloud
# Manufacturer: Huawei Cloud
# Asset Tag: OracleCloud.com
# Vendor: Amazon EC2
# Manufacturer: Amazon EC2
# Asset Tag: Amazon EC2
cache_dmi_and_virt
echo "$_dmi" | grep -Eiwq "$1"
}
cache_lspci() {
if [ -z "$_lspci" ]; then
apk add pciutils
_lspci=$(lspci)
apk del pciutils
fi
}
is_lspci_contains() {
cache_lspci
echo "$_lspci" | grep -Eiwq "$1"
}
get_config() {
cat "/configs/$1"
}
set_config() {
printf '%s' "$2" >"/configs/$1"
}
get_password_linux_sha512() {
get_config password-linux-sha512
}
get_password_windows_administrator_base64() {
get_config password-windows-administrator-base64
}
# debian 安装版、ubuntu 安装版、el/ol 安装版不使用该密码
get_password_plaintext() {
get_config password-plaintext
}
is_password_plaintext() {
get_password_plaintext >/dev/null 2>&1
}
show_netconf() {
grep -r . /dev/netconf/
}
get_ra_to() {
if [ -z "$_ra" ]; then
apk add ndisc6
# 有时会重复收取,所以设置收一份后退出
echo "Gathering network info..."
# shellcheck disable=SC2154
_ra="$(rdisc6 -1 "$ethx")"
apk del ndisc6
# 显示网络配置
info "Network info:"
echo
echo "$_ra" | cat -n
echo
ip addr | cat -n
echo
show_netconf | cat -n
echo
fi
eval "$1='$_ra'"
}
get_netconf_to() {
case "$1" in
slaac | dhcpv6 | rdnss | other) get_ra_to ra ;;
esac
# shellcheck disable=SC2154
# debian initrd 没有 xargs
case "$1" in
slaac) echo "$ra" | grep 'Autonomous address conf' | grep -q Yes && res=1 || res=0 ;;
dhcpv6) echo "$ra" | grep 'Stateful address conf' | grep -q Yes && res=1 || res=0 ;;
rdnss) res=$(echo "$ra" | grep 'Recursive DNS server' | cut -d: -f2-) ;;
other) echo "$ra" | grep 'Stateful other conf' | grep -q Yes && res=1 || res=0 ;;
*) res=$(cat /dev/netconf/$ethx/$1) ;;
esac
eval "$1='$res'"
}
is_ipv4_has_internet() {
grep -q 1 /dev/netconf/*/ipv4_has_internet
}
is_in_china() {
grep -q 1 /dev/netconf/*/is_in_china
}
# 有 dhcpv4 不等于有网关,例如 vultr 纯 ipv6
# 没有 dhcpv4 不等于是静态ip,可能是没有 ip
is_dhcpv4() {
get_netconf_to dhcpv4
# shellcheck disable=SC2154
[ "$dhcpv4" = 1 ]
}
is_staticv4() {
if ! is_dhcpv4; then
get_netconf_to ipv4_addr
get_netconf_to ipv4_gateway
if [ -n "$ipv4_addr" ] && [ -n "$ipv4_gateway" ]; then
return 0
fi
fi
return 1
}
is_staticv6() {
if ! is_slaac && ! is_dhcpv6; then
get_netconf_to ipv6_addr
get_netconf_to ipv6_gateway
if [ -n "$ipv6_addr" ] && [ -n "$ipv6_gateway" ]; then
return 0
fi
fi
return 1
}
should_disable_ra_slaac() {
get_netconf_to should_disable_ra_slaac
# shellcheck disable=SC2154
[ "$should_disable_ra_slaac" = 1 ]
}
is_slaac() {
# 防止部分机器slaac/dhcpv6获取的ip/网关无法上网
if should_disable_ra_slaac; then
return 1
fi
get_netconf_to slaac
# shellcheck disable=SC2154
[ "$slaac" = 1 ]
}
is_dhcpv6() {
# 防止部分机器slaac/dhcpv6获取的ip/网关无法上网
if should_disable_ra_slaac; then
return 1
fi
get_netconf_to dhcpv6
# shellcheck disable=SC2154
# 甲骨文即使没有添加 IPv6 地址,RA DHCPv6 标志也是开的
# 部分系统开机需要等 DHCPv6 超时
# 这种情况需要禁用 DHCPv6
if [ "$dhcpv6" = 1 ] && ! ip -6 -o addr show scope global dev "$ethx" | grep -q .; then
echo 'DHCPv6 flag is on, but DHCPv6 is not working.'
return 1
fi
[ "$dhcpv6" = 1 ]
}
is_have_ipv6() {
is_slaac || is_dhcpv6 || is_staticv6
}
is_enable_other_flag() {
get_netconf_to other
# shellcheck disable=SC2154
[ "$other" = 1 ]
}
is_have_rdnss() {
# rdnss 可能有几个
get_netconf_to rdnss
[ -n "$rdnss" ]
}
is_windows() {
for dir in /os /wim; do
[ -d $dir/Windows/System32 ] && return 0
done
return 1
}
# 15063 或之后才支持 rdnss
is_windows_support_rdnss() {
apk add pev
for dir in /os /wim; do
dll=$dir/Windows/System32/kernel32.dll
if [ -f $dll ]; then
build_ver="$(peres -v $dll | grep 'Product Version:' | cut -d. -f3)"
echo "Windows Build Version: $build_ver"
apk del pev
[ "$build_ver" -ge 15063 ] && return 0 || return 1
fi
done
error_and_exit "Not found kernel32.dll"
}
is_elts() {
[ -n "$elts" ] && [ "$elts" = 1 ]
}
is_need_change_ssh_port() {
[ -n "$ssh_port" ] && ! [ "$ssh_port" = 22 ]
}
is_need_change_rdp_port() {
[ -n "$rdp_port" ] && ! [ "$rdp_port" = 3389 ]
}
is_need_manual_set_dnsv6() {
# 有没有可能是静态但是有 rdnss?
! is_have_ipv6 && return $FALSE
is_dhcpv6 && return $FALSE
is_staticv6 && return $TRUE
is_slaac && ! is_enable_other_flag &&
{ ! is_have_rdnss || { is_have_rdnss && is_windows && ! is_windows_support_rdnss; }; }
}
get_current_dns() {
mark=$(
case "$1" in
4) echo . ;;
6) echo : ;;
esac
)
# debian 11 initrd 没有 xargs awk
# debian 12 initrd 没有 xargs
if false; then
grep '^nameserver' /etc/resolv.conf | awk '{print $2}' | grep -F "$mark"
else
grep '^nameserver' /etc/resolv.conf | cut -d' ' -f2 | grep -F "$mark"
fi
}
to_upper() {
tr '[:lower:]' '[:upper:]'
}
to_lower() {
tr '[:upper:]' '[:lower:]'
}
del_empty_lines() {
sed '/^[[:space:]]*$/d'
}
get_part_num_by_part() {
dev_part=$1
echo "$dev_part" | grep -o '[0-9]*' | tail -1
}
get_fallback_efi_file_name() {
case $(arch) in
x86_64) echo bootx64.efi ;;
aarch64) echo bootaa64.efi ;;
*) error_and_exit ;;
esac
}
del_invalid_efi_entry() {
info "del invalid EFI entry"
apk add lsblk efibootmgr
efibootmgr --quiet --remove-dups
while read -r line; do
part_uuid=$(echo "$line" | awk -F ',' '{print $3}')
efi_index=$(echo "$line" | grep_efi_index)
if ! lsblk -o PARTUUID | grep -q "$part_uuid"; then
echo "Delete invalid EFI Entry: $line"
efibootmgr --quiet --bootnum "$efi_index" --delete-bootnum
fi
done < <(efibootmgr | grep 'HD(.*,GPT,')
}
grep_efi_index() {
awk -F '*' '{print $1}' | sed 's/Boot//'
}
# 某些机器可能不会回落到 bootx64.efi
# 阿里云 ECS 启动项有 EFI Shell
# 添加 bootx64.efi 到最后的话,会进入 EFI Shell
# 因此添加到最前面
add_default_efi_to_nvram() {
info "add default EFI to nvram"
apk add lsblk efibootmgr
if efi_row=$(lsblk /dev/$xda -ro NAME,PARTTYPE,PARTUUID | grep -i "$EFI_UUID"); then
efi_part_uuid=$(echo "$efi_row" | awk '{print $3}')
efi_part_name=$(echo "$efi_row" | awk '{print $1}')
efi_part_num=$(get_part_num_by_part "$efi_part_name")
efi_file=$(get_fallback_efi_file_name)
# 创建条目,先判断是否已经存在
# 好像没必要先判断
if true || ! efibootmgr | grep -i "HD($efi_part_num,GPT,$efi_part_uuid,.*)/File(\\\EFI\\\boot\\\\$efi_file)"; then
efibootmgr --create \
--disk "/dev/$xda" \
--part "$efi_part_num" \
--label "$efi_file" \
--loader "\\EFI\\boot\\$efi_file"
fi
else
# shellcheck disable=SC2154
if [ "$confirmed_no_efi" = 1 ]; then
echo 'Confirmed no EFI in previous step.'
else
# reinstall.sh 里确认过一遍,但是逻辑扇区大于 512 时,可能漏报?
# 这里的应该会根据逻辑扇区来判断?
echo "
Warning: This machine is currently using EFI boot, but the main hard drive does not have an EFI partition.
If this machine supports Legacy BIOS boot (CSM), you can safely restart into the new system by running the reboot command.
If this machine does not support Legacy BIOS boot (CSM), you will not be able to enter the new system after rebooting.
警告:本机目前使用 EFI 引导,但主硬盘没有 EFI 分区。
如果本机支持 Legacy BIOS 引导 (CSM),你可以运行 reboot 命令安全地重启到新系统。
如果本机不支持 Legacy BIOS 引导 (CSM),重启后将无法进入新系统。
"
exit
fi
fi
}
unix2dos() {
target=$1
# 先原地unix2dos,出错再用cat,可最大限度保留文件权限
if ! command unix2dos $target 2>/tmp/unix2dos.log; then
# 出错后删除 unix2dos 创建的临时文件
rm "$(awk -F: '{print $2}' /tmp/unix2dos.log | xargs)"
tmp=$(mktemp)
cp $target $tmp
command unix2dos $tmp
# cat 可以保留权限
cat $tmp >$target
rm $tmp
fi
}
insert_into_file() {
file=$1
location=$2
regex_to_find=$3
shift 3
# 默认 grep -E
if [ $# -eq 0 ]; then
set -- -E
fi
if [ "$location" = head ]; then
bak=$(mktemp)
cp $file $bak
cat - $bak >$file
else
line_num=$(grep "$@" -n "$regex_to_find" "$file" | cut -d: -f1)
found_count=$(echo "$line_num" | wc -l)
if [ ! "$found_count" -eq 1 ]; then
return 1
fi
case "$location" in
before) line_num=$((line_num - 1)) ;;
after) ;;
*) return 1 ;;
esac
sed -i "${line_num}r /dev/stdin" "$file"
fi
}
get_eths() {
(
cd /dev/netconf
ls
)
}
is_distro_like_debian() {
[ "$distro" = debian ] || [ "$distro" = kali ]
}
create_ifupdown_config() {
conf_file=$1
rm -f $conf_file
if is_distro_like_debian; then
cat <<EOF >>$conf_file
source /etc/network/interfaces.d/*
EOF
fi
# 生成 lo配置
cat <<EOF >>$conf_file
auto lo
iface lo inet loopback
EOF
# ethx
for ethx in $(get_eths); do
mode=auto
enpx=
if is_distro_like_debian; then
if [ -f /etc/network/devhotplug ] && grep -wo "$ethx" /etc/network/devhotplug; then
mode=allow-hotplug
fi
if is_have_cmd udevadm; then
enpx=$(udevadm test-builtin net_id /sys/class/net/$ethx 2>&1 | grep ID_NET_NAME_PATH= | cut -d= -f2)
fi
fi
# dmit debian 普通内核和云内核网卡名不一致,因此需要 rename
# 安装系统时 ens18
# 普通内核 ens18
# 云内核 enp6s18
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=928923
# 头部
{
echo
if [ -n "$enpx" ] && [ "$enpx" != "$ethx" ]; then
echo rename $enpx=$ethx
fi
echo $mode $ethx
} >>$conf_file
# ipv4
if is_dhcpv4; then
echo "iface $ethx inet dhcp" >>$conf_file
elif is_staticv4; then
get_netconf_to ipv4_addr
get_netconf_to ipv4_gateway
cat <<EOF >>$conf_file
iface $ethx inet static
address $ipv4_addr
gateway $ipv4_gateway
EOF
# dns
if list=$(get_current_dns 4); then
for dns in $list; do
cat <<EOF >>$conf_file
dns-nameservers $dns
EOF
done
fi
fi
# ipv6
if is_slaac; then
echo "iface $ethx inet6 auto" >>$conf_file
elif is_dhcpv6; then
echo "iface $ethx inet6 dhcp" >>$conf_file
elif is_staticv6; then
get_netconf_to ipv6_addr
get_netconf_to ipv6_gateway
cat <<EOF >>$conf_file
iface $ethx inet6 static
address $ipv6_addr
gateway $ipv6_gateway
EOF
fi
# dns
# 有 ipv6 但需设置 dns 的情况
if is_need_manual_set_dnsv6; then
for dns in $(get_current_dns 6); do
cat <<EOF >>$conf_file
dns-nameserver $dns
EOF
done
fi
# 禁用 ra
if should_disable_ra_slaac; then
if [ "$distro" = alpine ]; then
cat <<EOF >>$conf_file
pre-up echo 0 >/proc/sys/net/ipv6/conf/$ethx/accept_ra
EOF
else
cat <<EOF >>$conf_file
accept_ra 0
EOF
fi
fi
done
}
space_to_newline() {
sed 's/ /\n/g'
}
trim() {
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
quote_word() {
sed -E 's/([^[:space:]]+)/"\1"/g'
}
quote_line() {
awk '{print "\""$0"\""}'
}
add_space() {
space_count=$1
spaces=$(printf '%*s' "$space_count" '')
sed "s/^/$spaces/"
}
# 不够严谨,谨慎使用
nix_replace() {
local key=$1
local value=$2
local type=$3
local file=$4