forked from gitbls/sdm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdm-cmdsubs
executable file
·649 lines (628 loc) · 23.7 KB
/
sdm-cmdsubs
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
#!/bin/bash
#
# This file is sourced by sdm for the burn and shrink commands
# It is not callable by anything other than sdm
# because it needs access to a bazillion variables defined
# in sdm, so can only run in the context of sdm.
#
function write_burnmsg() {
#
# $1 has the message to write
# It's written to the terminal and added to burnmsg
#
burnmsg+=("$(thisdate) $1")
echo "$1"
return 0
}
function ddctrlc() {
printf "\n%% Caught CTRL/C during burn. Cleaning up...\n"
if [ "$ddpid" != "" ]
then
#echo "killing $ddpid"
kill -HUP $ddpid > /dev/null 2>&1
wait $ddpid > /dev/null 2>&1
exit 1
fi
}
errifrc() {
[ $1 -ne 0 ] && errexit "$2 $1"
}
function setdiskid() {
local dev="$1" diskid="$2"
sfdisk --disk-id $dev 0x${diskid}
if [ $? -ne 0 ] # Assume it's an older version of sfdisk without --disk-id if it fails
then
write_burnmsg "% sfdisk failed; Trying fdisk to set Disk ID"
fdisk "$dev" > /dev/null <<EOF
x
i
0x$diskid
r
w
EOF
errifrc $? "? fdisk error "
write_burnmsg "> Disk ID $diskid set successfully with fdisk"
else
write_burnmsg "> Disk ID $diskid set successfully with sfdisk"
fi
}
function expandpartition() {
# $1: devicename (/dev/sdX)
local fulldevname=$1
local dev=${fulldevname##/dev/}
local part="${dev}2" # RasPiOS Ext 4 partition is always partition 2
local gb=$((1024*1024*1024)) gib=$((1000*1000*1000))
while read line
do
if [[ "$line" =~ "msdos" ]]
then
fsize=$(IFS=":" read fs bytes file n1 n2 fs <<< $line ; echo $bytes)
fsize=${fsize%B} #Fsize is file system size in bytes
elif [[ "$line" =~ "ext4" ]]
then
IFS=":;" read partnum partstart partend partsize fstype etc etc2 etc3 <<< $line
partstart=${partstart%B}
partend=${partend%B}
partsize=${partsize%B}
fi
done < <(parted -ms /dev/$dev unit B print)
#
# https://alioth-lists.debian.net/pipermail/parted-devel/2006-December/000573.html
# $l1: BYT; ** error if not BYT
# $l2: filespec:bytesB:file:512:512:msdos::;
# $l3: partnum:startB:endB:sizeB:fstype:::;
# $l4: partnum:startB:endB:sizeB:fstype:::;
devsize=$(cat /sys/block/$dev/size) # 512byte blocks
newsize=$((devsize - 1 )) # 512byte blocks
partsize=$(cat /sys/block/$dev/$part/size) # 512byte blocks
pbytes=$((partsize*512))
nbytes=$(((devsize*512)-$partend+$pbytes))
pgbytes=$(python3 -c "print(\"{:.1f}\".format(round($pbytes/$gb, 2)))")
pgibytes=$(python3 -c "print(\"{:.1f}\".format(round($pbytes/$gib, 2)))")
ngbytes=$(python3 -c "print(\"{:.1f}\".format(round($nbytes/$gb, 2)))")
ngibytes=$(python3 -c "print(\"{:.1f}\".format(round($nbytes/$gib, 2)))")
write_burnmsg "> Expand Root: Expand partition from ${pgbytes}GB (${pgibytes}GiB) to ${ngbytes}GB (${ngibytes}GiB)"
parted -m /dev/$dev u s resizepart 2 $newsize
errifrc $? "? parted resizepart failed with status"
#echo ",+" | sfdisk -N 2 $fulldevname
#errifrc $? "? sfdisk expand last partition failed with status"
}
function checkupdsdm() {
#
# Loop through sdm files and plugins and check for any newer ones on host
# Warn or update if so
# $1: 'check' to report, or 'update' to check and update
# $2: bupdate (sdm, plugin, or sdm+plugin (--bupdate))
local copt=$1 bup=$2
#
# Check sdm components if --bupdate sdm
# Really for sdm dev work only
#
if [[ "$bup" =~ "sdm" ]]
then
for fsdm in $sdmflist
do
case "$copt" in
check)
checkifnewer $sdmdir/$fsdm $SDMPT/$sdmdir/$fsdm && logtoboth "% sdm file '$fsdm' on host is newer"
;;
update)
[[ "$bup" =~ "sdm" ]] && copyifnewer $sdmdir/$fsdm $SDMPT/$sdmdir/$fsdm && logtoboth "% Update sdm module '$fsdm' from host to '$SDMPT$sdmdir"
;;
esac
done
fi
#
# For plugins:
# Loop through plugin list from command line
# if has path always then copy to local-plugins in the img
# else if newer in plugins or local-plugins, copy into img if --bupdate plugin
if [ "$plugins" != "" ]
then
IFS="~" read -a plugs <<< "$plugins"
for p in "${plugs[@]}"
do
p="${p%:*}"
pn="$(basename $p)"
if [ "$p" != "$pn" ]
then
# plugin with path specified; copy into IMG if newer regardless of --bupdate
copyifnewer $p $SDMPT/$sdmdir/local-plugins && logtoboth "% Update (or add) Plugin '$p' to $sdmdir/local-plugins"
else
# no path on plugin. if find in plugins or local-plugins copy into img if --bupdate plugin else mention
# this code doesn't report if plugin not found. That will happen later when it gets run
for d in $sdmdir/local-plugins $sdmdir/plugins
do
if [ -f $d/$pn ]
then
case "$copt" in
check)
checkifnewer $d/$pn $SDMPT/$d/$pn && logtoboth "% Plugin '$p' on the host is newer"
;;
update)
if [[ "$bup" =~ "plugin" ]]
then
copyifnewer $d/$pn $SDMPT/$sdmdir/local-plugins && logtoboth "% Update Plugin '$pn' from '$d/$pn' to '$sdmdir/local-plugins'"
else
logtoboth "% Plugin '$pn' on the host is newer"
fi
;;
esac
break
fi
done
fi
done
fi
}
function sdm_burndevfile() {
# Stash burn messages in an array until log on SD Card is mounted and available
declare -x SDMNSPAWN="Burn0"
declare -a burnmsg
declare -x SDMPT=$(makemtpt)
newdiskid="$(printf "%x" "$(((RANDOM*RANDOM*RANDOM*RANDOM+RANDOM)&0xFFFFFFFF))")"
[ "$hname" == "" ] && echo "% hostname not specified with --host; will not be written"
if [ $burn -eq 1 ]
then
#
# Burning to a device
#
[ "$burndev" == "" ] && errexit "? No storage device specified"
perr=0
for p in 1 2 3 4
do
[[ "$burndev" =~ "mmcblk" ]] && pn="p${p}" || pn=$p
pdev="${burndev}${pn}"
ismounted $pdev && echo "? Partition $pdev is mounted" && perr=1
done
[ $perr -eq 1 ] && errexit "? Use 'sudo umount' to unmount each mounted partition, then redo the burn command"
ismounted $burndev && errexit "? Device '$burndev' is mounted"
[ ! -b $burndev ] && errexit "? '$burndev' is not a block device"
write_burnmsg "* Burn '$dimg' to '$burndev'..."
burnmsg+=("$(thisdate) > Burn command line: $cmdline")
ddcmd="dd if=$dimg of=$burndev status=progress $ddsw"
burnmsg+=("$(thisdate) > dd command: $ddcmd")
# Burn the IMG to the device
echo "$ddcmd"
trap "ddctrlc" SIGINT
$ddcmd &
ddpid=$!
wait $ddpid > /dev/null 2>&1
[ $? -ne 0 ] && errexit "? Exiting due to dd error"
trap SIGINT
burnmsg+=("$(thisdate) > dd Copy completed")
# Prevent mount errors
sync ; sync ; sleep 1
p1="1" ; p2="2"
[[ "$burndev" =~ "mmcblk" ]] && p1="p1" && p2="p2"
if [ $expandroot -eq 1 ]
then
expandpartition $burndev
fi
olddiskid="$((blkid -o value $burndev) | (read id ; echo $id))"
write_burnmsg "> Set new disk ID '$newdiskid' on '$burndev'"
setdiskid $burndev $newdiskid
sync ; sync ; sleep 1
mount -v ${burndev}${p2} $SDMPT
mount -v ${burndev}${p1} $SDMPT/boot
! ismounted ${burndev}${p2} && errexit "? Unable to mount ${burndev}${p2}"
else
#
# Burning to a file
#
[ "$burnfilefile" == "" ] && errexit "? No Output IMG file specified"
[ -f $burnfilefile ] && errexit "? Output IMG file '$burnfilefile' exists"
write_burnmsg "* Burn '$dimg' to Output IMG '$burnfilefile'..."
burnmsg+=("$(thisdate) > Burn IMG command line: $cmdline")
ddcmd="dd if=$dimg of=$burnfilefile status=progress $ddsw"
burnmsg+=("$(thisdate) > dd command: $ddcmd")
# Burn the IMG to the file
echo "$ddcmd"
trap "ddctrlc" SIGINT
$ddcmd &
ddpid=$!
wait $ddpid > /dev/null 2>&1
[ $? -ne 0 ] && errexit "? Exiting due to dd error"
trap SIGINT
burnmsg+=("$(thisdate) > Image copy completed")
olddiskid="$((blkid -o value $burnfilefile) | (read id ; echo $id))"
loopdev=$(losetup --show -P -f $burnfilefile)
setdiskid $loopdev $newdiskid
losetup -d $loopdev
domount "$burnfilefile"
expandroot=1 # Force Expand Root into the newly written IMG so it will happen when burned to something with sdm
fi
write_burnmsg "> Set new Disk ID '$newdiskid' in /etc/fstab and /boot/cmdline.txt"
sed -i "s/${olddiskid}/${newdiskid}/g" $SDMPT/etc/fstab
# init_resize disappeared in 2022-09-06 build, but keep this here for older IMGs
sed -i 's| init=/usr/lib/raspi-config/init_resize\.sh||' $SDMPT/boot/cmdline.txt
sed -i 's| sdhci\.debug_quirks2=4||' $SDMPT/boot/cmdline.txt
! grep -q splash $SDMPT/boot/cmdline.txt && sed -i "s/ quiet//g" $SDMPT/boot/cmdline.txt # Remove 'quiet' if Lite (no splash)
sed -i "s/${olddiskid}/${newdiskid}/" $SDMPT/boot/cmdline.txt
#
# Write out the accumulated messages into mounted image if image has been customized
#
if [ -d $SDMPT/etc/sdm ]
then
write_burnmsg "> Flush accumulated burn log messages"
for (( i=0 ; i < ${#burnmsg[@]} ; i++ ))
do
echo "${burnmsg[$i]}" >> $SDMPT/etc/sdm/history
done
#
# Burn messages are written, all further messages written with logtoboth, which will write them to the terminal
# and to $SDMPT/etc/sdm/history in the mounted image or image file
#
xsettings="apip apssid autologin b0script b1script bootsetpairs bootscripts dhcpcd disables domain expandroot exports keymap locale myuser myuid noreboot"
xsettings="$xsettings nowaittimesync passwordpi passwordroot passworduser plugindebug plugins redact rclocal reboot rebootwait regensshkeys"
xsettings="$xsettings svcdisable svcenable sysctl timezone wificountry wpaconf"
# Save settings made with the --burn command
# Define variable b<varname> for each <varname>
for e in $xsettings
do
eval b$e=\${!e}
done
source $SDMPT/etc/sdm/sdm-readparams # Read settings from the SD card
initvirt logtoboth
# Update settings with settings from cmd line as appropriate
[ "$bb0script" != "$b0script" ] && b0script=$bb0script
[ "$bb1script" != "$b1script" ] && b1script=$bb1script
[ "$bdomain" != "" ] && domain=$bdomain
[ $breboot -eq 1 ] && reboot=1
[ $bnoreboot -eq 1 ] && reboot=0 && noreboot=1
[ $bbootscripts -eq 1 ] && bootscripts=$bbootscripts
[ "$bbootsetpairs" != "" ] && bootsetpairs="$bbootsetpairs"
[ $brebootwait -ne $drebootwait ] && rebootwait=$brebootwait
[ "$bapip" != "10.1.1.1" ] && apip=$bapip
[ "$bapssid" != "sdm" ] && apssid=$bapssid
[ "$bwificountry" != "" ] && wificountry="$bwificountry"
[ "$bplugins" != "" ] && plugins="$bplugins" || plugins=""
[ "$bmyuser" != "" ] && myuser=$bmyuser && myuid=$bmyuid
[ "$bsvcenable" != "" ] && svcenable="$bsvcenable"
[ "$bsvcdisable" != "" ] && svcdisable="$bsvcdisable"
[ "$bdisables" != "" ] && disables="$bdisables"
[ $bautologin -eq 1 ] && autologin=1
expandroot=$((bexpandroot|expandroot))
regensshkeys=$((bregensshkeys|regensshkeys))
nowaittimesync=$((bnowaittimesync|nowaittimesync))
plugindebug=$((bplugindebug|plugindebug))
redact=$((bredact|redact))
# --bupdate must specified on the burn command line
[ "$bupdate" != "" ] && checkupdsdm update "$bupdate" || checkupdsdm check "$bupdate"
if [ $expandroot -eq 1 -a $regensshkeys -eq 1 ]
then
logtoboth "> Disable unneeded RasPiOS firstboot service in cmdline.txt; both --expand-root and --regen-ssh-host-keys set"
sed -i 's| init=/usr/lib/raspberrypi-sys-mods/firstboot||' $SDMPT/boot/cmdline.txt
else
logtoboth "> RasPiOS firstboot service not disabled; at least one of --expand-root and --regen-ssh-host-keys not set"
fi
#
# Set hostname into the image
#
if [ "$hname" != "" -a -f $SDMPT/etc/hostname ]
then
# don't include domain name. Leave that to user
# [ "$domain" != "" ] && hnd="${hname}.${domain}" || hnd=$hname
# [ "$domain" != "" ] && shn=$hnd || shn=""
hnd=$hname
[ "$domain" != "" ] && shn="${hname}.${domain}" || shn=""
logtoboth "> Set hostname '$hnd'"
echo $hnd > $SDMPT/etc/hostname
sed -i "s/127.0.1.1.*raspberrypi/127.0.1.1\t$hname $shn/g" $SDMPT/etc/hosts
fi
if [[ "$loadllocal" =~ "|wifi|" ]]
then
[ "$wificountry" == "" ] && logtoboth "% No --wifi-country specified with --loadlocal wifi; Using 'US' for a short time" && wificountry="US"
fi
[ "$bkeymap" != "" ] && keymap=$bkeymap && echo "keymap=$bkeymap" >> $SDMPT/etc/sdm/auto-1piboot.conf
[ "$btimezone" != "" ] && timezone=$btimezone && echo "timezone=$btimezone" >> $SDMPT/etc/sdm/auto-1piboot.conf
[ "$blocale" != "" ] && local=$blocale && echo "locale=$blocale" >> $SDMPT/etc/sdm/auto-1piboot.conf
if [ "$b1script" != "" ]
then
if [ -f $b1script ]
then
if [ ! -f $SDMPT/etc/sdm/assets/$(basename $b1script) ]
then
logtoboth "> Copy '$b1script' to /etc/sdm/assets"
cp $b1script $SDMPT/etc/sdm/assets
chmod 755 $SDMPT/etc/sdm/assets/$(basename $b1script)
fi
else
if [ ! -f $SDMPT/etc/sdm/assets/$(basename $b1script) ]
then
logtoboth "? --b1script '$b1script' not found"
b1script=""
fi
fi
fi
if [ "$bdhcpcd" != "" ]
then
cat $bdhcpcd >> $SDMPT/etc/dhcpcd.conf
logtoboth "> Append '$bdhcpcd' to /etc/dhcpcd.conf"
dhcpcd=$bdhcpcd
fi
if [ "$bexports" != "" ]
then
cp $bexports $SDMPT/etc/exports
logtoboth "> Copy '$bexports' to /etc/exports"
exports=$bexports
fi
if [ "$bsysctl" != "" ]
then
cp $bsysctl $SDMPT/etc/sysctl.d
logtoboth "> Copy '$bsysctl' to /etc/sysctl.d/$(basename $bsysctl)"
sysctl=$bsysctl
fi
if [ "$bwpaconf" != "" ] # was --wpa specified on the burn command?
then
[ ! -f $bwpaconf ] && echo "% --wpa config file '$bwpaconf' not found; Skipping"
[ $burn -eq 1 ] && state="'$burndev'" || state="$'burnfilefile'"
logtoboth "> Copy WPA Supplicant configuration '$bwpaconf' to '$burndev'"
[ -f $bwpaconf ] && cp $bwpaconf $SDMPT/etc/wpa_supplicant/wpa_supplicant.conf
wpaconf="$bwpaconf" # Write updated wpaconf to SD Card params
fi
if [ "$brclocal" != "" ]
then
logtoboth "> Add commands to /etc/rc.local per --rclocal"
grep -v 'exit 0' $SDMPT/etc/rc.local > $SDMPT/tmp/rc.local
IFS="~" read -a citems <<< "$brclocal"
for c in "${citems[@]}"
do
logtoboth " $c"
echo "$c" >> $SDMPT/tmp/rc.local
done
echo "exit 0" >> $SDMPT/tmp/rc.local
mv $SDMPT/etc/rc.local $SDMPT/etc/rc.local.sdm.burn
mv $SDMPT/tmp/rc.local $SDMPT/etc
chmod 755 $SDMPT/etc/rc.local
[ "$rclocal" == "" ] && rclocal="$brclocal" || rclocal="${rclocal}|$brclocal"
fi
hostname="$hname" # So it gets written to updated params on SD card
[ "$bbootsetpairs" != "" -o "$bsvcdisable" != "" -o "$bsvcenable" != "" ] && setbootset # Process --bootset settings
[ $bootscripts -eq 1 ] && state="enabled" || state="disabled"
logtoboth "> First System Boot Custom Boot Scripts $state"
[ $rebootwait -ne $drebootwait ] && wmsg=" with a $rebootwait second wait" || wmsg=""
[ $reboot -eq 1 ] && state="enabled${wmsg}" || state="disabled"
logtoboth "> First System Boot automatic restart $state"
bcp=""
if [ "$bmyuser" != "" -a "$bpassworduser" == "" ]
then
# Not in container so can't use getent
if grep -q ^$myuser: $SDMPT/etc/passwd
then
logtoboth "% User $myuser already exists; Skipping..."
bmyuser=""
else
while [ 1 ]
do
echo -n "** Enter password for user '$myuser': "
bpassworduser=$(getpwd)
echo ""
[ "$bpassworduser" != "" ] && break
done
fi
fi
if [ "$bmyuser" != "" -o "$bpasswordpi" != "" -o "$bpasswordroot" != "" -o "$bpassworduser" != "" ]
then
bcp="$SDMPT/etc/sdm/assets/ucp-run-script"
echo "#!/bin/bash" > $bcp
echo "source /etc/sdm/sdm-readparams" >> $bcp
[ "$bpasswordpi" != "" ] && echo "changepwd pi \"$bpasswordpi\"" >> $bcp && passwordpi=$bpasswordpi
[ "$bpasswordroot" != "" ] && echo "changepwd root \"$bpasswordroot\"" >> $bcp && passwordroot=$bpasswordroot
if [ "$bmyuser" == "" ]
then
[ "$bpassworduser" != "" ] && echo "changepwd $myuser \"$bpassworduser\"" >> $bcp && passworduser=$bpassworduser
else
echo "sdm_adduser $bmyuser \"$bmyuid\" \"$bpassworduser\"" >> $bcp && passworduser=$bpassworduser
fi
chmod 755 $bcp
fi
writeconfig # Write updated params to the SD card so they are available in the following
if [ "$b0script" != "" ]
then
logtoboth "> Execute function 'do_b0script' in --b0script '$b0script'"
source $b0script
ftype=$(type -t do_b0script)
[ "$ftype" == "function" ] && do_b0script || logtoboth "% Function 'do_b0script' not found in '$b0script'; Skipping..."
fi
if [ "$plugins" != "" ]
then
runplugins 0
fi
#declare -x SDMNSPAWN="Burn1"
if [ -d $SDMPT/etc/lightdm ]
then
if [ $breboot -eq 1 ]
then
sdm_spawn "$sdmdir/sdm-phase1 burn-enable-lightdm-delay" "" Burn1
else
[ $bautologin -eq 1 ] && sdm_spawn "$sdmdir/sdm-phase1 burn-enable-lightdm-autologin" "" Burn1
fi
fi
if [ "$bdisables" != "" ]
then
logtoboth "> Process --disable $bdisables"
sdm_spawn "$sdmdir/sdm-phase1 do-disables" "" Burn1
fi
if [ "$bcp" != "" ]
then
logtoboth "> Change passwords or add user per --user, --password-pi, --password-user, and/or --password-root"
sdm_spawn "$sdmdir/sdm-phase1 b1script $(basename $bcp)" "" Burn1
fi
if [ "$b1script" != "" ]
then
logtoboth "> Run --b1script '$b1script'"
sdm_spawn "$sdmdir/sdm-phase1 b1script $b1script" "" Burn1
fi
if [ "$plugins" != "" ]
then
sdm_spawn "$sdmdir/sdm-phase1 run-all-plugins 1" "" Burn1
sdm_spawn "$sdmdir/sdm-phase1 run-all-plugins post-install" "" Burn1
fi
#
# Redact passwords if requested
#
if [ $redact -eq 1 ]
then
logtoboth "> Redact passwords from /etc/sdm/cparams and /etc/sdm/history"
for pwd in "$passworduser" "$passwordroot" "$passwordpi"
do
if [ "$pwd" != "" ]
then
sed -i "s/$pwd/REDACTED/" $SDMPT/etc/sdm/cparams
sed -i "s/$pwd/REDACTED/" $SDMPT/etc/sdm/history
fi
done
fi
declare -x SDMNSPAWN="Burn0"
logtoboth "* Burn Completed"
else
echo $"% IMG '$dimg' is not sdm-enhanced
Logs and configuration updates will not be written"
[ "$b0script" != "" ] && echo " and b0script '$b0script' will not be processed"
[ "$b1script" != "" ] && echo " and b1script '$b1script' will not be processed"
if [ "$hname" != "" ]
then
hnd=$hname
[ "$domain" != "" ] && shn="${hname}.${domain}" || shn=""
logtoboth "> Set hostname '$hnd'"
echo $hnd > $SDMPT/etc/hostname
sed -i "s/127.0.1.1.*raspberrypi/127.0.1.1\t$hname $shn/g" $SDMPT/etc/hosts
fi
fi
}
#
# Print partitions in IMG
#
sdm_ppart() {
echo "* Human-readable partition list"
parted -s $dimg unit B print
echo ""
echo "* Machine-readable partition list"
parted -ms $dimg unit B print
#echo "0: filespec:bytesB:file:512:512:msdos::;"
#echo "1: partnum:startB:endB:sizeB:fstype:::;"
#echo "2 partnum:startB:endB:sizeB:fstype:::;"
}
#
# Shrink IMG file
#
sdm_shrink() {
local gb=$((1024*1024*1024)) gib=$((1000*1000*1000))
[ $dimgdev -eq 1 ] && errexit "? --shrink only operates on IMG files"
loopdev=""
fstype=""
fsize=""
bsize=$(stat --printf %s $dimg)
rc=0
echo "* Start shrink on IMG '$dimg'"
while read line
do
if [[ "$line" =~ "msdos" ]]
then
fsize=$(IFS=":" read fs bytes file n1 n2 fs <<< $line ; echo $bytes)
fsize=${fsize%B}
elif [[ "$line" =~ "ext4" ]]
then
IFS=":;" read partnum partstart partend partsize fstype etc etc2 etc3 <<< $line
partstart=${partstart%B}
partend=${partend%B}
partsize=${partsize%B}
fi
done < <(parted -ms $dimg unit B print)
#
# https://alioth-lists.debian.net/pipermail/parted-devel/2006-December/000573.html
# $l1: BYT; ** error if not BYT
# $l2: filespec:bytesB:file:512:512:msdos::;
# $l3: partnum:startB:endB:sizeB:fstype:::;
# $l4: partnum:startB:endB:sizeB:fstype:::;
#
[ "$fstype" != "ext4" -o "$fsize" == "" ] && errexit "? IMG '$dimg' does not appear to be a RasPiOS IMG with two partitions"
if [ $fsize -ne $bsize ]
then
errexit "? Discrepancy between stat and parted on file size; parted size: $fsize stat size: $bsize"
fi
# Get partition type information for the 2nd partition (ext4)
# ** Is this needed? it will fail miserably later which might be OK
# pline=$(parted -s $dimg unit B print | grep ext4) # Slightly different than parted done above (no -m)
# if [[ "$pline" =~ "ext4" ]]
# then
# IFS=" " read p1 p2 p3 p4 parttype p6 <<< $pline
# [ "$parttype" != "primary" ] && errexit "Partition type '$parttype' not supported"
# else
# errexit "? No ext4 partition found"
# fi
# Create loop device to the partition
# Commented-out loggers and echos for debugging kernel log messages
#logger "Create loop device"
loopdev=$(losetup -f --show -o "$partstart" "$dimg")
# bx is a dummy due to leading ",". Other 2 can be in either order
IFS="," read bx b1 b2 <<< $(tune2fs -l $loopdev | while read aline ;\
do \
# If one we want, strip the text and all spaces, then echo it for consumption outside this subshell
[[ "$aline" =~ "Block count" ]] && (bc=${aline##Block count: } ; bc=${bc// } ; echo -n ",bc${bc}");\
[[ "$aline" =~ "Block size" ]] && (bs=${aline##Block size: } ; bs=${bs// } ; echo -n ",bs${bs}");\
done) ; rc=${PIPESTATUS[0]}
[ $rc -ne 0 ] && errexit "? tune2fs failed with status $rc"
# Set bc=block count, bs=blocksize. Handle both orderings: <nn>bc,<nn>bs or <nn>bs,<nn>bc
[ "${b1#bc}" != "$b1" ] && bc=${b1#bc}
[ "${b2#bs}" != "$b2" ] && bs=${b2#bs}
[ "${b1#bs}" != "$b1" ] && bc=${b1#bs} #In case in other order
[ "${b2#bc}" != "$b2" ] && bs=${b2#bc} #...
[ "$bc" == "" -o "$bs" == "" ] && errexit "? tune2fs failed to read the file system"
#logger "Check the file system"
echo "> Check the file system"
e2fsck -pf $loopdev
rc=$?
[ $rc -ge 4 ] && errexit "? e2fsck reports that file system is corrupt $rc"
#logger "Get new partition size"
oresize=$(resize2fs -P $loopdev)
errifrc $? "? resize2fs problem"
# Strip everything before ": " leaving only the new partition size, then up it a bit
newsize=${oresize##*: }
newsize=$((newsize+8))
# uncomment for debug
#echo "> Shrink data"
#echo " Partition Start: $partstart"
#echo " Partition End: $partend"
#echo " Partition Size: $partsize"
#echo " New size: $newsize"
#echo " bc: $bc"
#echo " bs: $bs"
[ $bc -le $newsize ] && errexit "% Image cannot be shrunk any further"
# Shrink the file system
#logger "Shrink the file system"
echo "> Shrink the file system to $newsize"
resize2fs -p $loopdev $newsize
errifrc $? "? resize2fs shrink exited with status"
# have not made resizepart work yet, so do a rm/mkpart on the partition
#parted -s $dimg resizepart 2 $partnewend
# Shrink the partition by removing and recreating it
#logger "Remove old partition"
echo "> Remove old partition"
parted -s -a minimal $dimg rm $partnum
errifrc $? "? parted rm partition failed with status"
#logger "Make new partition"
echo "> Make new partition"
partnewsize=$((newsize*bs))
partnewend=$((partstart+partnewsize-1))
parttype="primary"
parted -s $dimg unit B mkpart $parttype $partstart $partnewend
errifrc $? "? parted mkpart failed with status"
#
# Shrink the IMG
#
#logger "Shrink the IMG"
endsize=$((partstart+partnewsize))
echo "> Shrink the image by truncating to $endsize"
truncate -s ${endsize%B} $dimg
errifrc $? "? Truncate failed with status "
echo "* Shrink complete"
asize=$(stat --printf %s $dimg)
pgbytes=$(python3 -c "print(\"{:.1f}\".format(round($bsize/$gb, 2)))")
pgibytes=$(python3 -c "print(\"{:.1f}\".format(round($bsize/$gib, 2)))")
ngbytes=$(python3 -c "print(\"{:.1f}\".format(round($asize/$gb, 2)))")
ngibytes=$(python3 -c "print(\"{:.1f}\".format(round($asize/$gib, 2)))")
echo " IMG '$dimg' was ${pgbytes}GB (${pgibytes}GiB) now ${ngbytes}GB (${ngibytes}GiB)"
return
}