forked from midzelis/zquickinit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzquickinit.sh
More file actions
executable file
·1424 lines (1258 loc) · 44 KB
/
zquickinit.sh
File metadata and controls
executable file
·1424 lines (1258 loc) · 44 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
set -euo pipefail
if [ "${BASH_VERSINFO:-0}" -lt 5 ]; then
echo "Bash version 5 or greater required"
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "On MacOS, use brew to install bash"
echo "Note: brew uses /usr/local/bin on Intel, and /opt/homebrew/bin on Apple"
fi
exit 1
fi
# https://stackoverflow.com/questions/59895/how-do-i-get-the-directory-where-a-bash-script-is-located-from-within-the-script
SOURCE=${BASH_SOURCE[0]:-}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
: "${ZBM:=/zbm}"
: "${KERNEL_CMDLINE:=zfsbootmenu ro loglevel=4 zbm.autosize=0}"
: "${INSTALLER_MODE:=$([ -e /etc/zquickinit ] && echo "1" || echo "0")}"
DIR=$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)
SRC_ROOT=${DIR}
ZBM_ROOT=${SRC_ROOT}/../zfsbootmenu
RECIPES_ROOT=${RECIPES_ROOT:-${SRC_ROOT}/recipes}
RECIPE_BUILDER="${RECIPE_BUILDER:-ghcr.io/midzelis/zquickinit}"
ZQUICKINIT_REPO="${ZQUICKINIT_REPO:-https://github.com/midzelis/zquickinit}"
ZQUICKEFI_URL="${ZQUICKEFI_URL:-${ZQUICKINIT_REPO}/releases/latest}"
# provide default stable, latest ZBM_TAG if not specified
ZBM_TAG="${ZBM_TAG:-v3.0.1}"
# if empty, then unset to get latest release
if [[ -z "$ZBM_TAG" ]]; then
ZBM_TAG=""
fi
# if specified, takes precedence over ZBM_TAG
ZBM_COMMIT_HASH="${ZBM_COMMIT_HASH:-}"
# if ZBM_COMMIT_HASH is specified, unset ZBM_TAG
if [[ -n "$ZBM_COMMIT_HASH" ]]; then
ZBM_TAG=""
fi
INPUT=/input
OUTPUT=/output
ADD_LOADER=
MKINIT_VERBOSE=
KERNEL_BOOT=
ENGINE=
OBJCOPY=
DU=
FIND=
YG=
STAT=
NOASK=0
DEBUG=0
ENTER=0
RELEASE=0
GITHUBACTION=0
SSHONLY=
NOQEMU=
SECRETS=config
DRIVE1=1
DRIVE1_GB=8
DRIVE2=0
DRIVE2_GB=3
NOCONTAINER=0
CLEANUP=()
# shellcheck disable=SC2317
cleanup() {
ret=$?
for c in "${CLEANUP[@]}"; do
if [[ -e "${c}" ]]; then
rm -rf "${c}"
fi
done
exit $ret
}
trap cleanup EXIT INT TERM
tmpdir() {
# shellcheck disable=SC2155
local tmp="$(mktemp -d)" || exit 1
CLEANUP+=("${tmp}")
echo "${tmp}"
}
check() {
if ! command -v "$1" &>/dev/null && [[ $1 = mkinitcpio && $NOCONTAINER == 1 ]]; then
if [ ! -d ../mkinitcpio ]; then
echo "mkinitcpio not found, clone repo to $(pwd)/../mkinitcpio?"
# to build it, you need to do this:
# Package: *
# Pin: release a=stable
# Pin-Priority: 600
# Package: meson
# Pin: release a=testing
# Pin-Priority: 700
# and put deb http://deb.debian.org/debian testing main
# into /etc/apt/sources.list
else
export PATH="/usr/local/bin:$PATH"
return
fi
fi
if [[ $1 == docker || $1 == podman ]]; then
if [ -z "$ENGINE" ] && command -v docker &>/dev/null; then
ENGINE=docker
return 0
elif [ -z "$ENGINE" ] && command -v podman &>/dev/null; then
ENGINE=podman
return 0
fi
if [[ -z "$ENGINE" ]]; then
echo "docker or podman not found."
echo "see https://docs.docker.com/engine/install/ or"
echo "https://podman.io/docs/installation"
exit 1
fi
fi
if [[ $1 == yq ]]; then
if which yq-go >/dev/null 2>&1; then
YG=yq-go
return 0
elif which yq >/dev/null 2>&1; then
YG=yq
return 0
else
echo "yq (or yq-go) is required"
echo "try wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq && chmod +x /usr/bin/yq"
exit 1
fi
fi
if [[ $1 == objcopy && -z "${OBJCOPY}" ]]; then
if [[ "$OSTYPE" == "darwin"* ]]; then
OBJCOPY=$(find /opt/homebrew /usr/local -name gobjcopy -print -quit 2>/dev/null || :)
if [[ -z ${OBJCOPY} ]]; then
echo "$1 not found. usually part of the $2 package"
echo "On MacOS, use brew to install binutils"
echo "Note: brew uses /usr/local/bin on Intel, and /opt/homebrew/bin on Apple"
exit 1
fi
return 0
else
OBJCOPY=objcopy
fi
fi
if [[ $1 == find ]] && [[ -z "${FIND}" ]]; then
if command -v gfind &>/dev/null; then
FIND="gfind"
else
FIND="find"
fi
if [[ ! "$(${FIND} . --version 2>&1 | head -n1)" == *GNU* ]]; then
echo "find must be GNU flavored. Update or install findutils package. "
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "On MacOS, use brew to install findutils"
echo "Note: brew uses /usr/local/bin on Intel, and /opt/homebrew/bin on Apple"
fi
exit 1
fi
fi
if [[ $1 == du ]] && [[ -z "${DU}" ]]; then
if command -v gdu &>/dev/null; then
DU="gdu"
else
DU="du"
fi
if [[ ! "$(${DU} --version 2>&1 | head -n1)" == *GNU* ]]; then
echo "du must be GNU flavored. Update or install coreutils package. "
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "On MacOS, use brew to install coreutils"
echo "Note: brew uses /usr/local/bin on Intel, and /opt/homebrew/bin on Apple"
fi
exit 1
fi
fi
if [[ $1 == stat ]] && [[ -z "${STAT}" ]]; then
if command -v gstat &>/dev/null; then
STAT="gstat"
else
STAT="stat"
fi
if [[ ! "$(${STAT} --version 2>&1 | head -n2)" =~ (GNU|BusyBox) ]]; then
echo "stat must be GNU or BusyBox flavored. Update or install coreutils package."
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "On MacOS, use brew to install coreutils"
echo "Note: brew uses /usr/local/bin on Intel, and /opt/homebrew/bin on Apple"
fi
exit 1
fi
fi
if ! command -v "$1" &>/dev/null; then
echo "$1 not found. usually part of the $2 package"
if [[ $1 == "gum" && -f "/etc/debian_version" ]]; then
echo "To install, try:"
echo 'sudo mkdir -p /etc/apt/keyrings'
echo 'curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg'
echo 'echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list'
echo 'sudo apt update && sudo apt install gum'
fi
exit 1
fi
}
# This will build the main ZquickInit Builder OCI image
# shellcheck disable=SC2317
builder() {
echo "Creating ZQuickinit OCI build image..."
echo
check docker
check yq
local packages=()
# shellcheck disable=SC2016
mapfile -t -O "${#packages[@]}" packages < <($YG eval-all '. as $item ireduce ({}; . *+ $item) | (... | select(type == "!!seq")) |= unique | .xbps-packages[] | .. style=""' "$RECIPES_ROOT"/*/recipe.yaml)
if [[ -z "${ZBM_COMMIT_HASH}" ]]; then
if [[ -z "$ZBM_TAG" ]]; then
ZBM_TAG=$(curl --silent https://api.github.com/repos/zbm-dev/zfsbootmenu/releases/latest | $YG .tag_name)
fi
ZBM_COMMIT_HASH=$(curl --silent "https://api.github.com/repos/zbm-dev/zfsbootmenu/git/ref/tags/${ZBM_TAG}" | $YG .object.sha)
fi
ZQUICKINIT_COMMIT_HASH=$(git rev-parse HEAD)
echo "ZQUICKINIT_COMMIT_HASH: $ZQUICKINIT_COMMIT_HASH"
echo "ZBM_TAG: $ZBM_TAG"
echo "ZBM_COMMIT_HASH: $ZBM_COMMIT_HASH"
echo
echo "Building with Packages: ${packages[*]}"
echo
cmd=("$ENGINE" build .
-t "$RECIPE_BUILDER"
--label org.opencontainers.image.source="${ZQUICKINIT_REPO}"
--build-arg KERNELS=linux6.12
--build-arg "PACKAGES=${packages[*]}"
--build-arg ZBM_COMMIT_HASH="${ZBM_COMMIT_HASH}"
--build-arg ZQUICKINIT_COMMIT_HASH="${ZQUICKINIT_COMMIT_HASH}"
--progress=plain)
((GITHUBACTION == 1)) && cmd+=(--cache-from type=gha)
((GITHUBACTION == 1)) && cmd+=(--cache-to type=gha,mode=max)
cmd+=("$@")
echo "Build command: ${cmd[*]}"
"${cmd[@]}"
$ENGINE image ls "$RECIPE_BUILDER"
}
# shellcheck disable=SC2317
tailscale() {
check docker
mkdir -p state
$ENGINE run -it --hostname zquickinit-bootstrap --user "$(id -u):$(id -g)" -e TS_EXTRA_ARGS=--ssh -e TS_STATE_DIR=/state -v "$(pwd)"/state:/state tailscale/tailscale
mkdir -p config/var/lib/tailscale
mv -v state/tailscaled.state config/var/lib/tailscale
rm -rfv state
}
# This command is designed to be ONLY run from inside the running container
# shellcheck disable=SC2317
make_zquick_initramfs() {
check gum gum
check mkinitcpio mkinitcpio
check stat stat
gum style --bold --border double --align center \
--width 50 --margin "1 2" --padding "0 2" "Welcome to ZQuickInit make initramfs"
[[ -z $RUNNING_IN_CONTAINER ]] && echo _internal-run must be run from inside container && exit 1
if [[ ! -d "${INPUT}" ]]; then
local hash
echo "Downloading zquickinit"
rm -rf "${INPUT}"
git clone --quiet --depth 1 "${ZQUICKINIT_REPO}" "${INPUT}"
hash=$(cat /etc/zquickinit-commit-hash || echo '')
if [[ -n "${hash}" ]]; then
(cd "${INPUT}" && git fetch --depth 1 origin "$hash" && git checkout FETCH_HEAD)
fi
fi
[[ -x /etc/zquickinit-commit-hash ]] && (cd "${INPUT}" && git config --global --add safe.directory "${INPUT}" && /etc/zquickinit-commit-hash && git rev-parse HEAD >/etc/zquickinit-commit-hash && echo "ZQuickInit (${ZQUICKINIT_REPO}) commit hash: $(git rev-parse --short HEAD) ($(git rev-parse HEAD))")
if [[ ! -f "${ZBM}/bin/generate-zbm" ]]; then
echo "Downloading latest zfsbootmenu"
rm -rf "${ZBM}"
git clone --quiet --depth 1 https://github.com/zbm-dev/zfsbootmenu.git "${ZBM}"
hash=$(cat /etc/zbm-commit-hash || echo '')
if [[ -n "${hash}" ]]; then
(cd "${ZBM}" && git fetch --depth 1 origin "$hash" && git checkout FETCH_HEAD)
fi
fi
[[ -x /etc/zquickinit-commit-hash ]] && (cd "${ZBM}" && git config --global --add safe.directory "${ZBM}" && git rev-parse HEAD >/etc/zbm-commit-hash && echo "ZBM (https://github.com/zbm-dev/zfsbootmenu) commit hash: $(git rev-parse --short HEAD) ($(git rev-parse HEAD))")
hook_dirs=()
system_hooks=(strip kms autodetect base modconf block filesystems keyboard)
recipes=()
for dir in "${INPUT}"/recipes/*/initcpio; do
[[ ! -d $dir ]] && continue
hook_dirs+=("${dir#"/recipes"}")
name="${dir%/*}"
name="${name##*/}"
recipes+=("${name}")
done
# zquick_core must always happen at the begining, so remove it and add it back later
# shellcheck disable=SC2206
recipes=(${recipes[@]/zquick_core/})
# zquick_end must always happen at the end, so remove it and add it back later
# shellcheck disable=SC2206
recipes=(${recipes[@]/zquick_end/})
zquickinit="${INPUT}"
zquickinit_config="${zquickinit}"
if [[ -n "${SECRETS}" ]]; then
zquickinit_config="${zquickinit}"/"${SECRETS}"
mkdir -p "${zquickinit_config}"
fi
enabled_recipes=
enabled_systemhooks=
if [[ -f "${zquickinit_config}/etc/zquickinit.conf" ]]; then
enabled_recipes=$(sed -rn '/^enabled_recipes=/s/.*=(.*)/\1/p' "${zquickinit_config}/etc/zquickinit.conf")
enabled_systemhooks=$(sed -rn '/^enabled_systemhooks=/s/.*=(.*)/\1/p' "${zquickinit_config}/etc/zquickinit.conf")
else
enabled_recipes=$(
IFS=,
echo "${recipes[*]}"
)
enabled_systemhooks=$(
IFS=,
echo "${system_hooks[*]}"
)
fi
move_strip=
if ((NOASK == 0)); then
check yq
help=
for recipe in "${INPUT}"/recipes/*/recipe.yaml; do
[[ ! -r $recipe ]] && continue
name="${recipe%/*}"
name="${name##*/}"
[[ $name == "zquick_core" ]] && continue
help+=" - \`$name\` - $($YG e '.help ' "$recipe")\n"
done
gum style --bold --border double --align center \
--width 50 --margin "1 2" --padding "0 2" "Welcome to zquickinit" "(interactive mode)"
help_text=$(
cat <<-EOF
# Which recipes do you want to include in this build?
$(printf "%b" "$help")
<br>
EOF
)
gum format "${help_text}" " "
# shellcheck disable=SC2207,SC2048,SC2086
chosen_recipes=($(gum choose --height=20 --no-limit --selected="${enabled_recipes}" ${recipes[*]}))
text=()
text+=("# Which mkcpio system hooks would you like to include?")
text+=("See [Common Hooks](https://wiki.archlinux.org/title/mkinitcpio#Common_hooks) for more info. ")
text+=("")
((NOCONTAINER == 0)) && text+=("Note: mkcpio hook 'autodetect' won't work as expected when running within a container.")
gum format "${text[@]}" ""
# shellcheck disable=SC2207,SC2048,SC2086
chosen_systemhooks=($(gum choose --no-limit --selected="${enabled_systemhooks}" ${system_hooks[*]}))
mkdir -p "${zquickinit_config}/etc"
touch "${zquickinit_config}/etc/zquickinit.conf"
entry="enabled_systemhooks=$(
IFS=,
echo "${chosen_systemhooks[*]}"
)"
sed -i -r "/^enabled_systemhooks/{h;s/.*\$/${entry}/};\${x;/^$/{s//${entry}/;H};x}" "${zquickinit_config}/etc/zquickinit.conf"
entry="enabled_recipes=$(
IFS=,
echo "${chosen_recipes[*]}"
)"
sed -i -r "/^enabled_recipes/{h;s/.*\$/${entry}/};\${x;/^$/{s//${entry}/;H};x}" "${zquickinit_config}/etc/zquickinit.conf"
# Add RECIPE_BUILDER, ZQUICKINIT_REPO, and ZQUICKEFI_URL
entry="RECIPE_BUILDER=${RECIPE_BUILDER}"
sed -i -r "/^RECIPE_BUILDER/{h;s|.*$|${entry}|};\${x;/^$/{s||${entry}|;H};x}" "${zquickinit_config}/etc/zquickinit.conf"
entry="ZQUICKINIT_REPO=${ZQUICKINIT_REPO}"
sed -i -r "/^ZQUICKINIT_REPO/{h;s|.*$|${entry}|};\${x;/^$/{s||${entry}|;H};x}" "${zquickinit_config}/etc/zquickinit.conf"
entry="ZQUICKEFI_URL=${ZQUICKEFI_URL}"
sed -i -r "/^ZQUICKEFI_URL/{h;s|.*$|${entry}|};\${x;/^$/{s||${entry}|;H};x}" "${zquickinit_config}/etc/zquickinit.conf"
# run zquick_core setup explicitly, since its hidden from recipe list
env zquickinit_config="${zquickinit_config}" "${INPUT}/recipes/zquick_core/setup.sh"
for recipe in "${chosen_recipes[@]}"; do
[[ ! -x "${INPUT}"/recipes/${recipe}/setup.sh ]] && continue
env zquickinit_config="${zquickinit_config}" "${INPUT}/recipes/${recipe}/setup.sh"
done
else
IFS=',' read -r -a chosen_recipes <<<"${enabled_recipes}"
IFS=',' read -r -a chosen_systemhooks <<<"${enabled_systemhooks}"
echo "Enabled System Hooks: $(
IFS=,
echo "${chosen_systemhooks[*]}"
)"
echo "Enabled Recipes: $(
IFS=,
echo "${chosen_recipes[*]}"
)"
echo
if [[ $NOCONTAINER -eq 0 ]] && [[ "${chosen_systemhooks[*]}" =~ "autodetect" ]]; then
echo "NOTICE!! Removing autodetect hook"
echo
chosen_systemhooks=("${chosen_systemhooks[@]/autodetect/}")
fi
if [[ $RELEASE == 1 ]] && [[ "${chosen_systemhooks[*]}" =~ "zquick_qemu" ]]; then
echo "NOTICE!!! Removing zquick_qemu"
echo
chosen_recipes=("${chosen_recipes[@]/zquick_qemu/}")
fi
fi
hooks=()
# first system hooks
hooks+=("${chosen_systemhooks[@]}")
# then zfsbootmenu
hooks+=("zfsbootmenu")
# zquick_core recipe ia, and always added
hooks+=(zquick_core)
# then recipes
hooks+=("${chosen_recipes[@]}")
# If autodetect, ensure it goes first
if [[ "${hooks[*]}" =~ "autodetect" ]]; then
# Remove "autodetect" from the array
hooks=("${hooks[@]/autodetect/}")
# Prepend "autodetect" to the array
hooks=("autodetect" "${hooks[@]}")
fi
# Check if "strip" is in the array
if [[ " ${hooks[*]} " =~ "strip" ]]; then
# Remove "strip" from the array
hooks=("${hooks[@]/strip/}")
# Append "strip" to the array
hooks+=("strip")
fi
# zquick_end goes last
hooks+=("zquick_end")
build_time=$(date -u +"%Y-%m-%d_%H%M%S")
build_tmp="${OUTPUT}"/tmp
mkdir -p "${build_tmp}"
rm -rf "${build_tmp:?}"/*
echo "Using hooks: ${hooks[*]}"
echo
cat >"${build_tmp}/mkinitcpio.conf" <<-EOF
MODULES=()
BINARIES=()
FILES=()
HOOKS=(${hooks[@]})
COMPRESSION=(zstd)
COMPRESSION_OPTIONS=(-9 --long)
RELEASE=$RELEASE
zquickinit_root="$zquickinit"
zquickinit_config="$zquickinit"
if [[ -n "${SECRETS}" ]]; then
zquickinit_config="$zquickinit"/"${SECRETS}"
fi
function find_recipe {
local i=\${1:-1} size=\${#BASH_SOURCE[@]}
for ((; i < size-1; i++)) ;do
local file=\${BASH_SOURCE[\$i]:-}
if [[ \$file == $zquickinit/recipes/* ]]; then
echo \${file##*/}
break;
fi
done
}
zquick_add_secret() {
if [[ $RELEASE = "1" ]]; then return 0; fi
local filename="\${1##*/}"
local dirname="\${1%/*}"
local file=
if [[ -n "${SECRETS}" ]]; then
# [[ -f "${zquickinit}/${SECRETS}/\$filename" ]] && file="${zquickinit}/${SECRETS}/\$filename"
[[ -f "${zquickinit}/${SECRETS}\$1" ]] && file="${zquickinit}/${SECRETS}\$1"
else
# shellcheck disable=SC2154
for path in "\$dirname" "$zquickinit"; do
[[ -f "\$path/\$filename" ]] && file="\$path/\$filename" && break
done
fi
if [ ! -r "\$file" ]; then
msg2 "\$2 (\$filename) not found during build time"
return 1
else
msg "adding \$2 (\$file) to image"
add_file "\$file" \$1 \$3
fi
}
z_add_full_dir() {
# Add a directory and all its contents, recursively, to the initcpio image.
# No parsing is performed and the contents of the directory is added as is.
# \$1: path to directory
# \$2: glob pattern to filter file additions (optional)
# \$3: path prefix that will be stripped off from the image path (optional)
local f='' filter="\${2:-*}" strip_prefix="\$3"
if [[ -n "\$1" && -d "\$1" ]]; then
add_dir "\${1#"\${strip_prefix}"}"
for f in "\$1"/*; do
if [[ -L "\$f" ]]; then
# Explicit glob matching
# shellcheck disable=SC2053
if [[ "\$f" == \$filter ]]; then
add_symlink "\${f#"\${strip_prefix}"}" "\$(readlink "\$f")"
fi
elif [[ -d "\$f" ]]; then
z_add_full_dir "\$f" "\$filter" "\$strip_prefix"
elif [[ -f "\$f" ]]; then
# Explicit glob matching
# shellcheck disable=SC2053
if [[ "\$f" == \$filter ]]; then
add_file "\$f" "\${f#"\${strip_prefix}"}"
fi
fi
done
fi
}
zquick_add_fs() {
local recipe="\$(find_recipe)"
[[ -n "\${recipe}" ]] && \
z_add_full_dir "$zquickinit"/recipes/"\${recipe}"/fs "*" "$zquickinit"/recipes/"\${recipe}"/fs || \
warning "Could not find recipe, not adding filesystem."
}
zfsbootmenu_module_root="${ZBM}"/zfsbootmenu
zfsbootmenu_early_setup=()
zfsbootmenu_setup=()
zfsbootmenu_teardown=()
EOF
echo "${KERNEL_CMDLINE}" >"${build_tmp}/cmdline"
cat >"${build_tmp}/os-release" <<-EOF
NAME="ZFSQuickInit"
ID="ZFSQuickInit"
ID_LIKE="void"
PRETTY_NAME="ZFSQuickInit (built on $build_time)"
ANSI_COLOR="0;38;2;71;128;97"
EOF
hook_dirs+=("${ZBM}/initcpio")
if [[ -d "/usr/lib/initcpio" ]]; then
hook_dirs+=("/usr/lib/initcpio")
fi
if [[ -d "/usr/local/lib/x86_64-linux-gnu/initcpio" ]]; then
hook_dirs+=("/usr/local/lib/x86_64-linux-gnu/initcpio")
fi
hookdirs+=("${hook_dirs[@]/#/--hookdir }")
output_img="${OUTPUT}/zquickinit-$build_time.img"
output_uki="${OUTPUT}/zquickinit-$build_time.efi"
kernel="$(find "/lib/modules" -maxdepth 1 -type d | grep "/lib/modules/" | sort -V | tail -n 1 || true)"
if [[ -z "${kernel}" ]]; then
echo "Could not find kernel in /lib/modules"
exit 1
fi
kernel="${kernel##*/}"
if [[ -e "/boot/vmlinuz-$kernel" && ! -r "/boot/vmlinuz-$kernel" ]]; then
echo "/boot/vmlinuz-$kernel is not readable by your user, using sudo to copy image"
uid=$(id -u)
gid=$(id -g)
sudo cp "/boot/vmlinuz-$kernel" "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel"
sudo chown "${uid}:${gid}" "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel"
else
cp "/boot/vmlinuz-$kernel" "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel"
fi
echo mkinitcpio --config "${build_tmp}/mkinitcpio.conf" ${hookdirs[*]} \
--kernel "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel" "$MKINIT_VERBOSE" \
--osrelease "${build_tmp}/os-release" \
--cmdline "${build_tmp}/cmdline" \
--generate "${output_img}" \
--no-ukify \
-U "${output_uki}"
mkinitcpio --config "${build_tmp}/mkinitcpio.conf" ${hookdirs[*]} \
--kernel "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel" "$MKINIT_VERBOSE" \
--osrelease "${build_tmp}/os-release" \
--cmdline "${build_tmp}/cmdline" \
--generate "${output_img}" \
--no-ukify \
-U "${output_uki}" || :
rm -rf "${build_tmp}"
(
cd "${OUTPUT}"
rm -rf zquickinit.efi
ln -s zquickinit-$build_time.efi zquickinit.efi
)
chmod o+rw -R "${OUTPUT}"/*
chmod g+rw -R "${OUTPUT}"/*
env LC_ALL=en_US.UTF-8 printf "Kernel size: \t\t%'.0f bytes\n" "$(${STAT} -c '%s' "${OUTPUT}/zquickinit-$build_time.vmlinuz-$kernel")"
env LC_ALL=en_US.UTF-8 printf "initramfs size: \t%'.0f bytes\n" "$(${STAT} -c '%s' "$output_img")"
env LC_ALL=en_US.UTF-8 printf "EFI size: \t\t%'.0f bytes\n" "$(${STAT} -c '%s' "$output_uki")"
find "${OUTPUT}" -name 'zquickinit*.img' | sort -r | tail -n +4 | xargs -r rm
find "${OUTPUT}" -name 'zquickinit*.efi' | sort -r | tail -n +4 | xargs -r rm
find "${OUTPUT}" -name 'zquickinit*.vmlinuz-*' | sort -r | tail -n +4 | xargs -r rm
}
initramfs() {
if ((NOCONTAINER == 1)); then
INPUT=$(pwd)
OUTPUT=$(pwd)/output
RUNNING_IN_CONTAINER=1
mkdir -p ./tmp/zbm
ZBM="./tmp/zbm"
make_zquick_initramfs
return $?
fi
check docker
echo
echo "Launching $ENGINE..."
cmd=("$ENGINE" run --rm --user "$(id -u):$(id -g)")
((NOASK == 0)) && cmd+=(-it)
cmd+=(-e "RECIPE_BUILDER=$RECIPE_BUILDER")
cmd+=(-e "ZQUICKINIT_REPO=$ZQUICKINIT_REPO")
cmd+=(-e "ZQUICKEFI_URL=$ZQUICKEFI_URL")
[[ -f "$SRC_ROOT/zquickinit.sh" ]] && cmd+=(-v "$SRC_ROOT/zquickinit.sh:/zquickinit.sh:ro") && echo "bind-mount: zquickinit.sh (read-only)"
[[ -d "$RECIPES_ROOT" ]] && cmd+=(-v "$SRC_ROOT:/input:rw") && echo "bind-mount: $RECIPES_ROOT to /input (read-write)"
[[ -d "$ZBM_ROOT" ]] && cmd+=(-v "$ZBM_ROOT:/zbm:ro") && echo "bind-mount: $(readlink -f "${ZBM_ROOT}") to /zbm (read-only)"
echo "bind-mount: $SRC_ROOT/output to /output (read-write)"
mkdir -p "$SRC_ROOT/output"
[[ -d "$SRC_ROOT/output" ]] && cmd+=(-v "$SRC_ROOT/output:/output")
((ENTER == 1)) && cmd+=(--entrypoint=/bin/bash -i)
cmd+=("$RECIPE_BUILDER")
((ENTER == 0)) && cmd+=(make_zquick_initramfs)
((ENTER == 0 && NOASK == 1)) && cmd+=(--no-ask)
((DEBUG == 1)) && cmd+=(--debug)
((RELEASE == 1)) && cmd+=(--release)
[[ $ENTER == 0 && -n "$SECRETS" ]] && cmd+=(--secrets "$SECRETS")
[[ -n "$MKINIT_VERBOSE" ]] && cmd+=("$MKINIT_VERBOSE")
echo
"${cmd[@]}"
}
getefi() {
source=$(${FIND} . -type f -name 'zquickinit*.efi' -printf '%f\t%p\n' | sort -k1 | cut -d$'\t' -f2 | tail -n1)
if [[ -r "$source" ]]; then
echo "Found EFI: ${source}"
else
echo "No image found, finding latest release..."
local version='' download=''
version=$(curl --silent -qI "${ZQUICKEFI_URL}" | awk -F '/' '/^location/ {print substr($NF, 1, length($NF)-1)}')
download="${ZQUICKINIT_REPO}/releases/download/$version/zquickinit.efi"
source="${tmp}/zquickinit-${version}.efi"
echo "Downloading from ${download} to ${source}..."
curl -o "$source" --progress-bar -L "${download}"
fi
}
make_inject() {
check bsdtar "libarchive-tools"
check objcopy binutils
check truncate coreutils
check stat coreutils
check find findutils
[[ -z $RUNNING_IN_CONTAINER ]] && echo "make_inject must be run from inside container" && exit 1
local source="$1"
local target="$2"
local tmp=$(tmpdir)
inject_secret() {
local filename='' file='' dir=''
filename="${1##*/}"
if [[ -n "${INSTALLER_MODE:-}" ]]; then
dtmp="${1%/*}"
if [[ "$SECRETS" == /* ]]; then
dir=$SECRETS$dtmp
else
dir=$SRC_ROOT/$SECRETS$dtmp
fi
else
dir="."
fi
# shellcheck disable=SC2154
for path in "$dir" "$1"; do
[[ -f "$path/$filename" ]] && file="$path/$filename" && break
done
if [ ! -r "$file" ]; then
echo "$2 ($filename) not found"
return 1
else
echo "INJECTING $2 ($file) to image @ $1"
mkdir -p "$(dirname "${tmp}/$1")"
cp "${file}" "${tmp}/$1"
if [ -n "${3-}" ]; then
chmod "${3}" "${tmp}/$1"
fi
fi
return 0
}
echo "Injecting secrets into ZFSQuickInit EFI image inside container"
if [[ ! -r "$source" ]]; then
echo "Source EFI file not found: $source"
exit 1
fi
local injected=0
inject_secret "/etc/zquickinit.conf" "zquickinit config" && injected=1
inject_secret "/etc/tailscale/tailscaled.conf" "tailscale config" 644 && injected=1
inject_secret "/var/lib/tailscale/tailscaled.state" "tailscale node identity" 600 && injected=1
inject_secret "/root/.ssh/authorized_keys" "sshd authorized_keys for root" 600 && injected=1
inject_secret "/etc/ssh/ssh_host_rsa_key" "sshd host rsa key" 600 && injected=1
inject_secret "/etc/ssh/ssh_host_ecdsa_key" "sshd host ecdsa key" 600 && injected=1
inject_secret "/etc/ssh/ssh_host_ed25519_key" "sshd host ed25519 key" 600 && injected=1
inject_secret "/etc/ssh/ssh_host_rsa_key.pub" "sshd host rsa pub key" 644 && injected=1
inject_secret "/etc/ssh/ssh_host_ecdsa_key.pub" "sshd host ecdsa pub key" 644 && injected=1
inject_secret "/etc/ssh/ssh_host_ed25519_key.pub" "sshd host ed25519 pub key" 644 && injected=1
inject_secret "/etc/ssh/sshd_config" "sshd configuration" 644 && injected=1
inject_secret "/etc/hosts" "hosts file" 644 && injected=1
inject_secret "/etc/hostname" "hostname" 644 && injected=1
inject_secret "/etc/network/configure" "network configuration" 644 && injected=1
echo "Done injecting secrets and configuration"
echo
if ((injected == 1)); then
echo "Secrets were injected"
echo "Copying original EFI ${source} to output location ${target}..."
cp "${source}" "${target}"
local initrd="${tmp}/zquickinit.img.zst"
echo "Extracting initramfs from EFI ${source} to ${initrd}"
$OBJCOPY -O binary --only-section=.initrd "${source}" "${initrd}"
# To append an additional initrd segment, the new archive must aligned to a
# 4-byte boundary: https://unix.stackexchange.com/a/737219
initrd_size=$(${STAT} -c '%s' "${initrd}")
initrd_size=$(((initrd_size + 3) / 4 * 4))
truncate -s "${initrd_size}" "${initrd}"
echo "Appending secrets to initramfs ${initrd}"
if command -v bsdtar &>/dev/null; then
# shellcheck disable=SC2094
${FIND} "${tmp}" -not -path "${initrd}" -not -path "${source}" -print |
bsdtar -P --format=newc -c -f - -T - -n "-s#${tmp}##" | zstd >>"${initrd}"
elif command -v pax &>/dev/null; then
# shellcheck disable=SC2094
${FIND} "${tmp}" -not -path "${initrd}" -not -path "${source}" -print |
pax -x sv4cpio -wd "-s#${tmp}##" | zstd >>"${initrd}"
else
echo "You must have pax or bsdtar installed"
exit 1
fi
echo "Replacing initramfs with new initramfs ${initrd} in ${target}..."
$OBJCOPY --remove-section .initrd "${target}"
efi_last_section=$(objdump -h "${target}" | tail -2 | head -1)
efi_size=0x$(echo "$efi_last_section" | awk '{print $3}')
efi_offs=0x$(echo "$efi_last_section" | awk '{print $4}')
next=$((efi_size + efi_offs))
$OBJCOPY --add-section .initrd="${initrd}" \
--change-section-vma .initrd="$(printf 0x%x $next)" "${target}"
else
echo "No secrets to inject."
echo "Copying ${source} to ${target}..."
cp "${source}" "${target}"
echo "Created ${target}"
fi
# Output the injection status for the containerized path
echo "INJECTED_STATUS=$injected"
# Return the status (0 for success, non-zero for failure)
return 0
}
inject() {
echo "1 = ${1:-}, 2 = ${2:-}"
local source='' target='' target_base='' target_extension=''
if [[ -n "${ADD_LOADER}" && "${ADD_LOADER}" != 'download' ]]; then
source=${1:-}
else
source=${2:-}
fi
echo "Injecting secrets into ZFSQuickInit EFI image using container"
# Define tmp for getefi
local tmp=$(tmpdir)
if [[ ! -r "$source" ]]; then
echo "No source_efi specified - searching for image..."
check curl curl
check find findutils
getefi
fi
if [[ -n "${ADD_LOADER}" ]]; then
# Using --add-loader is only supported when being invoked from zbootstrap
# It is assumed that the EFI partition is mounted at /efi
target="/efi/EFI/${source##*/}"
else
target=${1:-${source##*/}}
fi
echo "source = ${source}, target = ${target}"
[[ -e "${target}" ]] && echo "${target} already exists." && exit 1
version=
if [[ ${target} = *-* ]]; then
version=${target#*-}
version=${version%.*}
fi
# Store the base name and extension for later renaming
target_base="${target%.*}"
target_extension="${target##*.}"
# Determine the directory containing the source file
local source_dir="${source%/*}"
local source_filename="${source##*/}"
local injected=0
if ((NOCONTAINER == 1)); then
# Run injection directly on the host
echo "Running injection directly on host (NOCONTAINER=1)"
# Determine the secrets directory
local secrets_path="$SRC_ROOT/$SECRETS"
if [[ "$SECRETS" == /* ]]; then
secrets_path="$SECRETS"
fi
if [[ ! -d "$secrets_path" ]]; then
echo "Secrets directory not found: $secrets_path"
exit 1
fi
# Mimic the container environment
INPUT="$SRC_ROOT"
OUTPUT="$SRC_ROOT/output"
RUNNING_IN_CONTAINER=1
# Call the injection logic directly (use a temporary target, we'll rename later)
local tmp_target="$tmp/inject_target.efi"
local output_log="$tmp/inject_output.log"
# Stream the output in real-time and save to a file for parsing
if ! make_inject "$source" "$tmp_target" 2>&1 | tee "$output_log"; then
echo "Injection failed. Output is above."
exit 1
fi
# Check if secrets were injected (based on the output)
if grep -q "INJECTED_STATUS=1" "$output_log" 2>/dev/null; then
injected=1
fi
# Rename the target if secrets were injected
if ((injected == 1)); then
echo "Secrets were injected, appending '_injected' to name"
target="${target_base}_injected.${target_extension}"
fi
# Move the temporary target to the final location
if [[ -f "$tmp_target" ]]; then
mv "$tmp_target" "$target"
else
echo "Injection failed: temporary target file not found"
cat "$output_log"
exit 1
fi
else
# Run injection inside the container
check docker
echo "Injecting secrets using container"
# Prepare to run injection in the container
local container_source="/source_input/$source_filename"
local container_target="/output/target.efi"
local container_secrets="/input/$SECRETS"
# Ensure the output directory exists
mkdir -p "$SRC_ROOT/output"
# Run the injection inside the container and capture output
echo "Launching $ENGINE for secret injection..."
cmd=("$ENGINE" run --rm)
((NOASK == 0)) && cmd+=(-it)
# Mount the directory containing the source file as /source_input
cmd+=(-v "$source_dir:/source_input:ro")
echo "bind-mount: $source_dir to /source_input (read-only)"
# Mount the entire SRC_ROOT as /input
cmd+=(-v "$SRC_ROOT:/input:rw")
echo "bind-mount: $SRC_ROOT to /input (read-write)"
# Mount the output directory
cmd+=(-v "$SRC_ROOT/output:/output:rw")
echo "bind-mount: $SRC_ROOT/output to /output (read-write)"
# Mount the script itself if needed
[[ -f "$SRC_ROOT/zquickinit.sh" ]] && cmd+=(-v "$SRC_ROOT/zquickinit.sh:/zquickinit.sh:ro") && echo "bind-mount: zquickinit.sh (read-only)"
((ENTER == 1)) && cmd+=(--entrypoint=/bin/bash -i)
cmd+=("$RECIPE_BUILDER")
((ENTER == 0)) && cmd+=(make_inject)
[[ $ENTER == 0 && -n "$SECRETS" ]] && cmd+=(--secrets "$container_secrets")
((ENTER == 0)) && cmd+=("$container_source" "$container_target")
# Stream the output in real-time and save to a file for parsing
local output_log="$tmp/container_output.log"
if ! "${cmd[@]}" 2>&1 | tee "$output_log"; then
echo "Container execution failed. Container output is above."
exit 1
fi
# Check if secrets were injected (parse the INJECTED_STATUS from the saved output)
if grep -q "INJECTED_STATUS=1" "$output_log" 2>/dev/null; then
injected=1
fi
# Rename the target if secrets were injected
if ((injected == 1)); then
echo "Secrets were injected, appending '_injected' to name"
target="${target_base}_injected.${target_extension}"
fi
# Move the output file to the target location
local container_output_file="$SRC_ROOT/output/target.efi"
if [[ -f "$container_output_file" ]]; then
mv "$container_output_file" "$target"
else
echo "Injection failed: target file not found in container output"
cat "$tmp/container_output.log"
exit 1
fi
fi