-
Notifications
You must be signed in to change notification settings - Fork 52
/
sdm-cparse
2243 lines (2086 loc) · 63.4 KB
/
sdm-cparse
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
#
# This file is sourced by other sdm scripts
#
#
# Common functions
#
function errexit() {
echo -e "$1"
exit 1
}
function ferrexit() {
[ "$1" != "" ] && printf "$1"
exit 1
}
function exitiferr() {
[ "${1:0:1}" == "?" ] && errexit "$1"
}
function errifrc() {
[ $1 -ne 0 ] && errexit "$2"
}
function warnifrc() {
# Requires logtoboth active
[ $1 -ne 0 ] && logtoboth "$2 ($1)"
}
function logit {
#
# Writes message to /etc/sdm/history
#
# $1="message string"
#
[ -f $SDMPT/etc/sdm/history ] && echo "$(thisdate) $1" >> $SDMPT/etc/sdm/history
}
function logtoboth() {
#
# Writes the message to the terminal and also to /etc/sdm/history
#
# $1="message string" which will be split up across multiple lines if needed
# $2="nosplit" if lines should not be split up
#
local msg="$1"
local str=() i spc=""
if [[ ${#msg} -le $logwidth ]] || [[ "$2" == "nosplit" ]]
then
logit "$msg"
echo "$msg"
else
readarray -t str <<< $(fold -s -w$logwidth <<< $(echo "$msg"))
for (( i=0 ; i < ${#str[@]} ; i++))
do
logit "${spc}${str[$i]}"
echo "${spc}${str[$i]}"
spc=" "
done
fi
}
function logtobothex() {
#
# Write message via logtoboth and then exit 1
#
local msg="$1" nosplit="$2"
logtoboth "$msg" "$nosplit"
exit 1
}
function bootlog() {
# Write string in $1 to the system log/journal and /etc/sdm/history.log
logger "sdm FirstBoot: $1"
logit "> sdm FirstBoot: $1"
}
function bootlogx() {
# Write string only to the system log
logger "sdm FirstBoot: $1"
}
function write_console() {
#
# $1 string to write
# Written to /dev/console as "\n$(thisdate) sdm FirstBoot: $1"
echo -e "\n$(thisdate) sdm FirstBoot: $1" > /dev/console
}
function write_console0() {
#
# $1 string to write
# Written to /dev/console as "$1"
echo -e "$1" > /dev/console
}
function askyn() {
local ans
echo -n "$1" '[y/n]? ' ; read $2 ans
case "$ans" in
y*|Y*) return 0 ;;
*) return 1 ;;
esac
}
function outlong () {
#
# Write the string in $1 to the file in $2
# If the line is too long, it will be split up
#
local str=() i spc="" lw=${logwidth:-96}
if [ ${#1} -le $lw ]
then
echo "$(date +'%Y-%m-%d %H:%M:%S') $1" >> $2
else
readarray -t str <<< $(fold -s -w96 <<< $(echo $1))
for (( i=0 ; i < ${#str[@]} ; i++))
do
echo "$(date +'%Y-%m-%d %H:%M:%S') ${spc}${str[$i]}" >> $2
spc=" "
done
fi
}
function logapterror() {
logtobothex "? apt returned an error; review /etc/sdm/apt.log"
}
function doapt() {
#
# $1 is apt command
# $2 is $showapt value
# $3 is optional apt command [D:apt-get]
#
function pline() {
local line
while read line
do
echo "$(thisdate) $line" >> /etc/sdm/apt.log
done
}
local aptcmd="$3" sts td
[ "$aptcmd" == "" ] && aptcmd="apt-get -qq"
echo "" >> /etc/sdm/apt.log
outlong "$aptcmd $1" "/etc/sdm/apt.log"
echo "" >> /etc/sdm/apt.log
if [ "$2" == "1" ]
then
DEBIAN_FRONTEND=noninteractive $aptcmd -o=Dpkg::Use-Pty=0 $1 2>&1 | tee -a /etc/sdm/apt.log
sts=$?
else
if [[ "$poptions" =~ "nologdates" ]]
then
DEBIAN_FRONTEND=noninteractive $aptcmd -o=Dpkg::Use-Pty=0 $1 >> /etc/sdm/apt.log 2>&1
sts=$?
else
# Technique from https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another/73180#73180
{ { { { DEBIAN_FRONTEND=noninteractive $aptcmd -o=Dpkg::Use-Pty=0 $1 2>&1; echo $? >&3; } | pline >&4; } 3>&1; } | { read xs; exit $xs; } } 4>&1
sts=$?
fi
fi
[[ "$poptions" =~ "nologdates" ]] && td="" || td="$(thisdate) "
echo "${td}[Done]" >> /etc/sdm/apt.log
return $sts
}
function doaptrpterror() {
#
# $1 is apt command
# $2 is $showapt value
#
# Note: Reports and exits if error
#
doapt "$1" "$2" || { sts=$? ; logapterror ; return $sts ; }
}
function runcaptureout() {
#
# Run command, capturing output via logtoboth
#
local cmd="$1"
function pline() {
local line
while read line
do
logtoboth "$line"
done
}
{ { { { $cmd 2>&1; echo $? >&3; } | pline >&4; } 3>&1; } | { read xs; exit $xs; } } 4>&1
}
function setfileownmode() {
#
# $1 is full path to file
# $2 is file mode (defaults to 0755)
# $2 is file owner (defaults to root:root)
local fp="$1" fm="$2" fo="$3"
[ "$fm" == "" ] && fm="755"
[ "$fo" == "" ] && fo="root:root"
chown $fo $fp
chmod $fm $fp
}
function pkgexists() {
#
# $1 has apt package name to check
#
pkg=$1
[ "$($sudo apt-cache showpkg $pkg 2>/dev/null)" != "" ] && return 0 || return 1
}
function ispkginstalled() {
#
# $1 has package name
#
iver=$(apt-cache policy $1 | grep Installed: 2> /dev/null)
if [ "$iver" == "" ]
then
return 1
else
[[ "$iver" =~ "(none)" ]] && return 1 || return 0
fi
return
}
function installpkgsif() {
local pkglist="$1" pkgs=() newpkgs="" p
IFS=" " read -a pkgs <<< $pkglist
for p in "${pkgs[@]}"
do
ispkginstalled $p || newpkgs="$newpkgs $p"
done
[ "$newpkgs" == "" ] || doaptrpterror "install --no-install-recommends --yes $newpkgs" $showapt
}
function getaptver() {
# $1: package name
# $2: 'installed' or 'candidate'
#
# returns requested version string or "" if doesn't exist
local pkg="$1" vertype="$2" sstr
case $vertype in
installed) sstr="Installed:"
;;
candidate) sstr="Candidate:"
;;
esac
while read line
do
if [[ "$line" =~ "$sstr" ]] && [[ ! "$line" =~ "(none)" ]]
then
ver="${line#*: }"
echo "$ver"
return
fi
done < <($sudo apt policy $pkg 2>/dev/null)
echo ""
return
}
function getpipver() {
# $1: package name
[ "$(type -p pip3)" == "" ] && echo "" && return
echo "$($sudo pip3 list 2>>/dev/null | grep $1 | (read mname mver ; echo $mver))"
return
}
function installviapip() {
function pline() {
local line
while read line
do
echo "$(thisdate) $line" >> /etc/sdm/apt.log
done
}
# $1: package name
# $2: /path/to/pip3 in the venv
# $3: pip install options
# $4: Message to logtoboth
local pkg=$1 vpip3="$2" options="$3" msg="$4"
# Use --ignore-installed b/c we def want it to be installed!
logtoboth "$msg"
echo "" >> /etc/sdm/apt.log
outlong "$vpip3 install --ignore-installed $pkg" /etc/sdm/apt.log
echo "" >> /etc/sdm/apt.log
if [[ "$poptions" =~ "nologdates" ]]
then
$vpip3 install --ignore-installed $pkg 2>&1 | tee -a /etc/sdm/apt.log
sts=$?
else
# Technique from https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another/73180#73180
{ { { { $vpip3 install --ignore-installed $pkg 2>&1; echo $? >&3; } | pline >&4; } 3>&1; } | { read xs; exit $xs; } } 4>&1
sts=$?
fi
[[ "$poptions" =~ "nologdates" ]] && td="" || td="$(thisdate) "
echo "${td}[Done] [$sts]" >> /etc/sdm/apt.log
return $sts
}
function thisdate() {
echo "$(date +"$datefmt")"
}
function ord() {
#
# Returns the value in decimal of the character in $1
# e.g. c="a" ; echo $(ord $c) will print 97
#
printf '%d' "'$1"
}
function isactive() {
#
# Returns "0" if service in $1 is active
#
systemctl --quiet is-active $1
sts=$?
echo "$sts"
return $sts
}
function getfilegroup() {
#
# $1: /path/to/file
#
# Returns the string for the group owning the file
#
local tfile="$1" gx
gx=$(stat -c '%G' $tfile)
[ "$gx" == "" ] && gx=users
echo $gx
}
function getgbstr() {
#
# $1: # of bytes in partition
#
# Returns the string "(nn.nnGB, mm.mmGiB)"
local nbytes=$1
local gb=1000000000 gib=1073741824 gb2=500000000 gi2=536870912
local ngbytes ngibytes
ngbytes=$(printf %.1f "$(( ((10 * $nbytes)+$gb2) / $gb ))e-1")
ngibytes=$(printf %.1f "$(( ((10 * $nbytes)+$gi2) / $gib))e-1")
echo "(${ngbytes}GB, ${ngibytes}GiB)"
return
}
function getfsdf() {
#
# $1: fs name
# $2: df component: pcent, avail, etc
#
echo $(df --output=$2 $1 | tail -1 | (IFS="%" ; read a ; a="${a% }" ; a="${a# }" echo $a))
}
function logfreespace() {
#
# Logs the current free space on $dimg
#
local dev="/" extramsg="$1" free1k freeby dused
[ "$SDMPT" != "" ] && dev="$SDMPT"
free1k=$(getfsdf $dev avail)
freeby=$(($free1k*1024))
logtoboth "> $dimgdevname '$dimg' has $free1k 1K-blocks $(getgbstr $freeby) free $extramsg" nosplit
dused=$(getfsdf / pcent)
if [ $dused -ge 98 ]
then
logtoboth "!!!"
logtoboth "% $dimgdevname '$dimg' is ${dused}% full" nosplit
logtoboth "% Review /etc/sdm/apt.log in the IMG for insufficient disk space errors" nosplit
logtoboth "% If needed use --extend --xmb nnnn with --customize to create more space in the IMG" nosplit
logtoboth "% Customization terminated due to low disk space condition" nosplit
logtoboth "!!!"
exit 1
fi
}
function do_raspiconfig() {
#
# $1=command
# $2=value
local cmd=$1 value=$2
if type -P raspi-config > /dev/null
then
SUDO_USER=${myuser:-nobody} raspi-config $cmd "$value" nonint # prefer to not block outputs! > /dev/null 2>&1
else
logtoboth "% Unable to find raspi-config for function '$cmd' with value '$value'"
fi
}
function configitemlog() {
# $1: Message
# $2: function to call
local msg=$1 fn=$2
if [ "$fn" != "" ]
then
if [ "$(type -t "$fn")" == "function" ]
then
[ "$fn" == "logtoboth" ] && msg="> $msg"
$fn "$msg"
else
echo "% Unrecognized config item log function: $fn"
fi
fi
}
function doconfigitem() {
#
# $1: function keyword
# $2: value
# $3: "" or "bootlog" (first boot) or "logtoboth" (phase1)
# NOTE; first boot only at the moment!
local rpifun=$1 value=$2 msgfn=$3 tval
case "$rpifun" in
# * do_resolution still needs to be sorted out
serial)
logtoboth "% Consider using the sdm 'serial' plugin to control the serial configuration"
configitemlog "Set Serial Port to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_serial $value nonint
do_raspiconfig do_serial $value nonint
;;
delayed_boot_behavior)
# Processed at the very end of FirstBoot
;;
boot_behavior|boot_behaviour) # Allow US spelling as well ;)
configitemlog "Set boot_behaviour '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_boot_behaviour $value nonint
[ "$msgfun" == "bootlog" ] && do_raspiconfig do_boot_behaviour $value || setdelayedbbh "$value"
;;
vnc_resolution)
configitemlog "Set VNC resolution to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_vnc_resolution $value nonint
do_raspiconfig do_vnc_resolution $value nonint
;;
powerled)
ssys=0
(grep -q "\\[actpwr\\]" /sys/class/leds/led0/trigger > /dev/null 2>&1) && ssys=1
(grep -q "\\[default-on\\]" /sys/class/leds/led0/trigger > /dev/null 2>&1) && ssys=1
if [ $ssys -eq 1 ]
then
configitemlog "Set Power LED to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_leds $value nonint
do_raspiconfig do_leds $value
else
configitemlog "This Pi does not support setting the Power LED; Skipped" $msgfn
fi
;;
audio|pi4video|boot_splash|boot_order|\
spi|i2c|boot_wait|net_names|overscan|blanking|\
pixdub|overclock|rgpio|camera|onewire)
# These are simple on/off and less commonly used so no elaborate logging for them
configitemlog "Set $rpifun to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_$rpifun $value nonint
do_raspiconfig do_$rpifun $value
;;
fstab)
configitemlog "Append fstab extension '$value' to /etc/fstab" $msgfn
cat $value >> /etc/fstab
;;
overlayfs)
[[ "$2" == "" ]] || [[ "$2" == "0" ]] && tval="ro" || tval=$2
$msgfn "Enable overlayfs with '$tval' bootfs"
sed -i -e "s/^/overlayroot=tmpfs /" /boot/firmware/cmdline.txt
sed -i -e "s#\(.*/boot/firmware.*\)defaults\(.*\)#\1defaults,$tval\2#" /etc/fstab
;;
#
# keymap, locale, and timezone may be set via sdm --burn command
#
keymap)
configitemlog "Set Keymap to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_configure_keyboard "$value" nonint
do_raspiconfig do_configure_keyboard "$value"
;;
locale)
configitemlog "Set Locale to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_change_locale "$value" nonint
do_raspiconfig do_change_locale "$value"
declare -x LANG="$value"
;;
timezone)
configitemlog "Set Timezone to '$value'" $msgfn
#SUDO_USER=${myuser:-pi} raspi-config do_change_timezone "$value" nonint
do_raspiconfig do_change_timezone "$value"
;;
*)
configitemlog "% Unrecognized option '$rpifun'" $msgfn
;;
esac
}
function getosinfo() {
#
# extract an element from /etc/os-release
#
local item="$1" where="$2"
str="$( { IFS="=" read id name ; echo $name ;} <<< $(grep ^$item= $where/etc/os-release))"
str=$(stripquotes "$str")
echo $str
}
function getosdate() {
#
# Returns the OS date from /etc/rpi-issue
#
echo $(grep -s -m1 -o '[[:digit:]]\{4\}-[[:digit:]]\{2\}-[[:digit:]]\{2\}' $SDMPT/etc/rpi-issue)
return
}
function israspios() {
#
# Returns true if host is RasPiOS, false if not
#
# os-release says ID=debian, arch is aarch64 or armv7l (uname -m) and /etc/rpi-issue exists
[ -f /etc/os-release -a -f /etc/rpi-issue ] || return 1
[ "$(grep ^ID= $SDMPT/etc/os-release | (IFS="=" read v id ; id=${id%\"} ; echo ${id#\"}))" == "debian" ] || return 1
[[ "aarch64|armv7l" =~ "$(uname -m)" ]] || return 1
return 0
}
function is64bit() {
#
# Look at /bin/ls to decide the arch
# Return 0 if is64 else 1
#
local wtf wtfelf wtfarch rest
wtf=$(file $SDMPT/bin/ls)
IFS="," read wtfelf wtfarch rest <<< "$wtf"
[[ "$wtfarch" =~ "aarch64" ]] && return 0 || return 1
}
function ispdevp() {
local dev="$1"
[[ "$dev" =~ "mmcblk" ]] || [[ "$dev" =~ "nvme" ]] && return 0 || return 1
}
function getspname() {
local dev="$1" pn="$2"
ispdevp $dev && echo "${dev}p${pn}" || echo "${dev}${pn}"
}
function getpartname() {
local dev="$1" pn="$2"
ispdevp $dev && echo "p${pn}" || echo "${pn}"
}
function getcdate() {
#
# Returns date in canonical format
#
local cdtfmt="+%Y-%m-%dT%H:%M:%S" # Canonical date format for manipulation
echo $(date "$cdtfmt")
}
function datediff() {
#
# Computes difference between two dates
# returns it as a string of Days:Hours:Minutes:Seconds
#
local days hours minutes seconds eseconds
local btime="$1" etime="$2"
eseconds=$(($(/bin/date -d "$etime" +%s) - $(/bin/date -d "$btime" +%s)))
days=$((eseconds/86400))
hours=$(((eseconds - $((days*86400)))/3600))
minutes=$(((eseconds - $((days*86400)) - $((hours*3600)))/60))
seconds=$((eseconds - $((days*86400)) - $((hours*3600)) - $((minutes*60))))
#printf "%02d:%02d:%02d:%02d\n" "$days" "$hours" "$minutes" "$seconds"
[ $days -ne 0 ] && printf "%02d:%02d:%02d:%02d\n" "$days" "$hours" "$minutes" "$seconds" || printf "%02d:%02d:%02d\n" "$hours" "$minutes" "$seconds"
}
function writeconfig() {
#
# Write config parameters into the image
#
local paramfile="$SDMPT/etc/sdm/cparams"
local bkfile="${paramfile}.old" orgfile="${paramfile}.orig"
rm -f $bkfile
[ -f $paramfile ] && mv $paramfile $bkfile
echo "#Arguments passed from sdm into the IMG on $(date +'%Y-%m-%d %H:%M:%S')" > $paramfile
for e in version thishost aptcache aptdistupgrade autologin fbatch b0script b1script bootscripts \
burnplugins cscript csrc customizestart datefmt debugs dimg dimgdev dimgdevname domain ecolors \
expandroot exports fchroot fdirtree fnoexpandroot hname hostname loadlocal logwidth \
dgroups myuser nowaittimesync os pi1bootconf plugindebug poptions \
raspiosver reboot fredact regensshkeys noreboot rebootwait \
redocustomize sdmdir sdmflist showapt src swapsize \
timezone virtmode vqemu custom1 custom2 custom3 custom4 plugins allplugins
do
echo "$e:\"${!e}\"" >> $paramfile
done
[ -f $orgfile ] || cp -a $paramfile $orgfile
}
function resetpluginlist() {
#
# Juggle plugin list in cparams
#
[ "$plugins" != "" ] && allplugins="${allplugins}~${plugins}"
plugins=""
writeconfig
}
function updatehostname() {
hnm="$1" hnimg=""
[ -f $SDMPT/etc/hostname ] && read hnimg < <(tr -d " \t\n\r" < $SDMPT/etc/hostname)
[ "$hnimg" == "" ] && hnm="raspberrypi"
if [ "$hnm" != "$hnimg" ]
then
[ "$domain" != "" ] && shn="${hnm}.${domain}" || shn=""
logtoboth "> Set hostname '$hnm'"
echo $hnm > $SDMPT/etc/hostname
sed -i "s/127\.0\.1\.1.*${hnimg}.*/127.0.1.1\t${hnm} ${shn}/g" $SDMPT/etc/hosts
fi
}
function runoneplugin() {
#
# Run the plugin $1 for the phase specified in $2 with args in $3
# By the time we get here plugin will be in the sdmdir hierarchy
#
# If Phase is not 0, caller must be in the container or use sdm_runspawn instead of calling this directly
#
local p=$(basename $1) phase=$2 pargs="$3" sts=1 xsts=1
[ "$pargs" != "" ] && argstr="with arguments: '$pargs'" || argstr="with no arguments"
#[ $fredact -eq 1 ] && argstr=""
for d in $SDMPT$sdmdir/local-plugins $SDMPT$sdmdir/plugins
do
if [ -f $d/$p ]
then
[[ "$p" =~ ^sdm. ]] || logtoboth "> Run Plugin '$p' ($d/$p) Phase $phase $argstr"
if [ -x $d/$p ]
then
$d/$p "$phase" "$pargs"
xsts=$?
sts=0
break
else
logtoboth "!!Plugin '$p' file '$d/$p' not executable"
break
fi
#else
fi
done
[ $sts -eq 1 ] && logtoboth "? Unable to find Plugin '$p'"
return $xsts
}
function runonepluginx() {
#
# $1: Plugin name and args (in $plugin format: plugin:key=value:key=value)
# $2 phase
# If specified, $3 is a string to append to the plugin args (argname=value)
#
# If Phase is not 0, caller must be in the container or use sdm_runspawn instead of calling this directly
#
local p="$1" phase=$2 xargv="$3" in
IFS=":" read -r pin pargs <<< "$p"
[ "$pargs" == "$p" ] && pargs="" #Really a null argument list
if [ "$xargv" != "" ]
then
[ "$pargs" == "" ] && pargs="$xargv" || pargs="$pargs|$xargv"
fi
runoneplugin $pin $phase "$pargs"
}
function runplugins() {
#
# Run the plugins in $1 with the phase specified in $2
# If specified, $3 is a string to append to the plugin args (argname=value)
# If Phase is not 0, caller must be in the container or use sdm_runspawn instead of calling this directly
#
local mnt="$SDMPT" theseplugs="$1" phase=$2 xargv="$3" p pin pargs plugs=()
if [ "$theseplugs" != "" ]
then
logtoboth "> Run Plugins Phase '$phase'"
IFS="~" read -r -a plugs <<< "$theseplugs"
#IFS="~" plugs=($theseplugs'') # bash doesn't like this ;(
for p in "${plugs[@]}"
do
if [ "$p" != "" ]
then
IFS=":" read -r pin pargs <<< "$p"
runonepluginx "$p" $phase "$xargv" || { logtoboth "? Plugin '$pin' exited with failure status '$?'" && return 1 ; }
fi
done
fi
return 0
}
function runplugins_exit() {
#
# Run plugins. Exit if there is an error
#
# $1: list of plugins
# $2: Phase
# If specified, $3 is a string to append to the plugin args (argname=value)
#
local plugins="$1" phase="$2" xargv="$3"
[ "$plugins" == "" ] && return
runplugins "$plugins" $phase "$xargv" && return || exit
}
function live0scripts() {
#
# Clear or run plugin boot scripts on the running system
#
# $1: path to clear or run (eg /etc/sdm/0piboot/*.sh)
#
local fni="$1" op=$2
local fbn ffn fpn
while read ffn
do
if [ "$op" == "run" ]
then
chmod 755 $ffn
logtoboth "* Run plugin FirstBoot script '$ffn'"
bash $ffn
fi
fbn=$(basename $ffn)
fpn=$(dirname $ffn)
rm -f $fpn/.$fbn
mv $ffn $fpn/.$fbn
done < <(compgen -G "$fni")
}
function ispluginselected() {
#
# Returns true if plugin name in $1 is on the command line
#
local thisplugin="$1" pluglist="$2"
IFS="~" read -r -a plugs <<< "$pluglist"
for p in "${plugs[@]}"
do
IFS=":" read -r thispn args <<< "$p"
[ "$thispn" == "$thisplugin" ] && return 0
done
return 1
}
function getpluginargs() {
#
# Returns the args provided for the plugin on the cmd line, for all instantiations of it
#
local thisplugin="$1" pluglist="$2" arglist=""
IFS="~" read -r -a plugs <<< "$pluglist"
for p in "${plugs[@]}"
do
IFS=":" read -r thispn args <<< "$p"
#??? needs to append correctly
[ "$thispn" == "$thisplugin" ] && arglist="${arglist}${args}"
echo "$arglist"
return
done
}
function isarginpluginlist() {
#
# $1 is plugin name
# $2 is plugin list
# $3 is the arg name
local pn="$1" plist="$2" lookarg="$3"
args=$(getpluginargs "$pn" "$plist")
[[ "$args" =~ "$lookarg" ]] && return 0 || return 1
}
function plugin_getargs() {
#
# Handles input data in the form: arg1=val1|arg2=val2|arg3=val3| ...
# $1: Plugin name
# $2: Argument list
# $3: [optional] list of valid keys. Validity not checked if ""
# $4: [optional] list of required keys. Required keys not checked if ""
#
# In addition to creating a key/value symbol for each found key/value,
# also creates symbol foundkeys="|key1|key2|...|"
#
local arglist=() pfx=$1 largs="$2" validkeys="$3" rqkeys="$4" keysfound=""
IFS="|" read -r -a arglist <<< "$largs"
for c in "${arglist[@]}"
do
# Put the args into variables
IFS="=" read -r key value remain <<< "$c"
[ "$remain" != "" ] && value="${value}=${remain}"
if [ "$validkeys" != "" ]
then
if ! [[ "$validkeys" =~ "|$key|" ]]
then
logtoboth "? Plugin $pfx: Unrecognized key '$key' in argument list '$largs'"
return 1
fi
fi
if [ "${key#\#}" != "$key" -o "${key#\\n}" != "$key" ]
then
# Handle a comment string that starts with '#' or '\n'. Prefix \n-led string with \n#
[ "${key#\\n}" != "$key" ] && key="\n#${key#\\n}"
printf -v "comment" "%s" "$key"
keysfound="${keysfound}|comment" # Mark as 'comment' found
else
# Turn word-word into word__word. User of the value must handle other end for display
[ "$key" != "${key/-/_}" ] && key="${key//-/__}"
# Don't slash-quote dollar signs. Breaks $ in passwords. What breaks if this is disabled?
# [[ "$value" =~ "$" ]] && value=${value//$/\\$} # Replace $ with \$
[ "$key" != "" ] && printf -v "${key}" "%s" "$value" #eval "${key}=\"$value\""
keysfound="${keysfound}|$key"
fi
done
#
# Check required keys
#
if [ "$rqkeys" != "" ]
then
# Strip leading "|" from rqkeys to avoid checking for a null first arg
IFS="|:" read -a arglist <<< "${rqkeys#|}"
for c in "${arglist[@]}"
do
if ! [[ "${keysfound}|" =~ "|$c|" ]]
then
logtoboth "? Plugin $pfx: Required key '$c' missing from argument list '$largs'"
return 1
fi
done
fi
# Strip leading "|" to avoid null string on subsequent splitting, but put one on the end
[ "$keysfound" == "" ] && eval "foundkeys=\"\"" || eval "foundkeys=\"${keysfound#|}|\""
return 0
}
function plugin_printkeys() {
#
# Print the keys found. plugin_getargs returns the list of found keys in $foundkeys
# Assumes $pfx:plugin name, $foundkeys:list of keys found, keys set up from plugin_getargs
# $1: List of keys to redact each separated by vbar [disabled]
#
#redactkeys="|$1|"
if [ "$foundkeys" != "" ]
then
logtoboth "> Plugin $pfx: Keys/values found:"
IFS="|" read -a fargs <<< "$foundkeys"
for c in "${fargs[@]}"
do
# The construct ${!c} gets the value of the variable 'pointed to' by contents of $c
kn="${c//__/-}"
kval="${!c}"
#[[ "$redactkeys" =~ "$c" ]] && kval="REDACTED"
logtoboth " ${kn}: $kval"
done
fi
}
function plugin_logorder() {
local plugins="$1" plist
logtoboth "* Plugins selected:"
if [ "$plugins" != "" ]
then
IFS="~" read -a plist <<< $plugins
for p in "${plist[@]}"
do
IFS=':' read fpn pargs <<< "$p"
logtoboth " * $fpn"
#[ $fredact -eq 1 ] && pargs=""
[ "$pargs" != "" ] && logtoboth " Args: $pargs" nosplit
done
else
logtoboth " * No plugins are selected"
fi
}
function plugin_dbgprint() {
[ $plugindebug -eq 1 ] && logtoboth "D!Plugin $pfx: $1"
}
function plugin_addnote() {
#
# Adds a line of text to the notes file for the run
# The notes file is appended to the console and log at end of run
#
# $1: Line of text to write
#
msg="$1"
echo "Plugin $pfx: $msg" >> $SDMPT/etc/sdm/rnotes
}
function printnotes() {
if [ -f $SDMPT/etc/sdm/rnotes ]
then
logtoboth ""
logtoboth "*** Plugin Notes ***"
logtoboth ""
while read line
do
logtoboth " $line" nosplit
done < $SDMPT/etc/sdm/rnotes
rm -f $SDMPT/etc/sdm/rnotes
fi
}
function checkpluginsx() {
#
# $1: Plugin list
# $2: y if shoud copyifnewer
#
local plugins="$1" cif=$2
local p plugs fpn pargs pf dfpn d
if [ "$plugins" != "" ]
then
IFS="~" read -a plugs <<< $plugins
for p in "${plugs[@]}"
do
IFS=':' read fpn pargs <<< "$p"
pf=0
dfpn=$(dirname $fpn)
for d in $dfpn $src/local-plugins $src/plugins
do
pn=$(basename $fpn)
# Don't look in current directory unless explicit './' provided
if [[ "$d" != "." ]] || [[ "$fpn" == "./$pn" ]]
then
if [ -f $d/$pn ]
then
[ -x $d/$pn ] || errexit "? Plugin $d/$pn is not executable"
# if plugin found outside of sdm hierarchy copy it in
if [ "$d" == "$dfpn" -a $burning -eq 0 -a $frunonly -eq 0 ] # Don't update plugins on host if burning or runonly
then
[ "$cif" == "y" ] && copyifnewer $d/$pn $src/local-plugins && write_premsg "% Copy Plugin '$pn' from '$d/$pn' to '$src/local-plugins'"
fi
pf=1
break
fi
fi
done
[ $pf -eq 0 ] && errexit "? Unrecognized plugin '$fpn'"
done
fi
}
function adjust_wifinmpsk() {
#
# $1: Input PSK
#
# return: single string with all schars letters backslash-quoted
local psk="$1" i c schars=" '|!"
# Quote characters that need it
for (( i=0 ; i < ${#schars} ; i++ ))
do
c=${schars:$i:1}
psk="${psk//$c/\\$c}"
done
echo "$psk"
}
function encrypt_wifipsk() {
# $1 psk
# $2 SSID
local psk="$1" ssid="$2" opsk
opsk="$(wpa_passphrase "$ssid" "$psk" | grep $'\tpsk=')"
IFS='=' read lhpsk psk <<< "$opsk"
echo "$psk"
}
function dosshsetup() {
#
# Set up ssh as requested
# Must be called in Phase 1
#
ssh="$1" pfx="$2"
case "$ssh" in
service)
logtoboth "> Plugin $pfx: Enable SSH service"
systemctl enable ssh >/dev/null 2>&1
systemctl enable sshswitch >/dev/null 2>&1
;;
socket)
logtoboth "> Plugin $pfx: Enable SSH using ssh.socket"
systemctl enable ssh.socket > /dev/null 2>&1
systemctl disable sshswitch.service > /dev/null 2>&1
;;
none)
logtoboth "> Plugin $pfx: Disable SSH"
systemctl disable ssh.service > /dev/null 2>&1
;;
esac
}
function iswsl() {
#
# Return true if running system is a WSL instance
#