Debian Codegraph @

chroot-script

raw
1 #!/bin/bash
2 # Filename: /etc/debootstrap/chroot-script
3 # Purpose: script executed in chroot when installing Debian via grml-debootstrap
4 # Authors: grml-team (grml.org), (c) Michael Prokop <[email protected]>
5 # Bug-Reports: see https://grml.org/bugs/
6 # License: This file is licensed under the GPL v2.
7 ################################################################################
8 # GRML_CHROOT_SCRIPT_MARKER - do not remove this line unless you want to keep
9 # this script as /bin/chroot-script on your new installed system
10 ################################################################################
11 # shellcheck disable=SC2317 # shellcheck has trouble understanding the code flow in this file
12
13 # error_handler {{{
14 # shellcheck disable=SC2329
15 error_handler() {
16 last_exit_code="$?"
17 last_bash_command="$BASH_COMMAND"
18 echo "Unexpected non-zero exit code $last_exit_code in ${BASH_SOURCE[*]} at line ${BASH_LINENO[*]} detected!
19 last bash command: $last_bash_command"
20 exit 1
21 }
22
23 set -e
24 set -E
25 set -o pipefail
26 trap "error_handler" ERR
27 # }}}
28
29 bash -n /etc/debootstrap/config
30 # shellcheck source=config
31 . /etc/debootstrap/config || exit 1
32 bash -n /etc/debootstrap/variables
33 # shellcheck source=tests/shellcheck-stub-debootstrap-variables
34 . /etc/debootstrap/variables || exit 1
35
36 [ -r /proc/1 ] || mount -t proc none /proc
37 [ -r /sys/kernel ] || mount -t sysfs none /sys
38
39 if [ -n "$RPIFIRM" ]; then
40 mkdir --parents /boot/firmware
41 mount "$RPIFIRM" /boot/firmware
42 fi
43
44 # variable checks {{{
45
46 # use aptitude only if it's available
47 if [ -x /usr/bin/aptitude ] ; then
48 APTUPDATE="aptitude update $DPKG_OPTIONS"
49 APTINSTALL="aptitude -y --without-recommends install $DPKG_OPTIONS"
50 APTUPGRADE="aptitude -y safe-upgrade $DPKG_OPTIONS"
51 else
52 APTINSTALL="apt-get -y --no-install-recommends install $DPKG_OPTIONS"
53 APTUPDATE="apt-get update $DPKG_OPTIONS"
54 APTUPGRADE="apt-get -y upgrade $DPKG_OPTIONS"
55 fi
56
57 if [ -z "$STAGES" ] ; then
58 STAGES='/etc/debootstrap/stages'
59 [ -d "$STAGES" ] || mkdir -p "$STAGES"
60 fi
61 # }}}
62
63 # helper functions {{{
64 stage() {
65 if [ -n "$2" ] ; then
66 echo "$2" > "$STAGES/$1"
67 return 0
68 elif grep -q 'done' "$STAGES/$1" 2>/dev/null ; then
69 echo " [*] Notice: stage $1 has been executed already, skipping execution therefore.">&2
70 return 1
71 fi
72 echo " Executing stage ${1}"
73 return 0
74 }
75
76 # shellcheck disable=SC2329
77 askpass() {
78 # read -s emulation for dash. result is in $resp.
79 set -o noglob
80 [ -t 0 ] && stty -echo
81 read -r resp
82 [ -t 0 ] && stty echo
83 set +o noglob
84 }
85 # }}}
86
87 # mark existing packages as automatically installed {{{
88 # shellcheck disable=SC2329
89 markauto() {
90 # Mark most leaf packages as automatically installed.
91 # Later in the systems life, apt autoremove will remove them if possible.
92 apt-mark auto '~i !~M ?not(?priority(required)) ?not(?priority(important)) ?not(?priority(standard))'
93 }
94 # }}}
95
96 # write a deb822 sources stanza to a file {{{
97 writesource() {
98 local file types uris suites components signed_by
99
100 file="${1:-}"
101 types="${2:-}"
102 uris="${3:-}"
103 suites="${4:-}"
104 components="${5:-}"
105 signed_by="${6:-}"
106
107 mkdir -p "$(dirname "${file}")"
108
109 if [ -f "$file" ]; then
110 ## stanzas need a space between them and the previous stanza
111 echo '' >> "$file"
112 fi
113
114 echo "Types: $types" >> "$file"
115 echo "URIs: $uris" >> "$file"
116 echo "Suites: $suites" >> "$file"
117 echo "Components: $components" >> "$file"
118 if [ -n "$signed_by" ]; then
119 echo "Signed-By: $signed_by" >> "$file"
120 fi
121 }
122 # }}}
123
124 # define chroot mirror {{{
125 # shellcheck disable=SC2329
126 chrootmirror() {
127 if [ "$KEEP_SRC_LIST" = "yes" ] ; then
128 echo "KEEP_SRC_LIST has been enabled, skipping chrootmirror stage."
129 return
130 fi
131
132 if [ -z "$COMPONENTS" ] ; then
133 COMPONENTS='main'
134 fi
135 echo "Using repository components $COMPONENTS"
136
137 if [ -n "$MIRROR" ] ; then
138 echo "Deleting obsolete sources.list"
139 rm -f /etc/apt/sources.list
140
141 if grep -q 'file:' <<< "$MIRROR" ; then
142 echo "Adjusting sources.list.d/local.sources for mirror (${MIRROR})."
143 writesource '/etc/apt/sources.list.d/local.sources' 'deb' "$MIRROR" "$RELEASE" "$COMPONENTS" '/usr/share/keyrings/debian-archive-keyring.gpg'
144 else
145 echo "Adjusting sources.list.d/debian.sources for mirror (${MIRROR})."
146 writesource '/etc/apt/sources.list.d/debian.sources' 'deb' "$MIRROR" "$RELEASE" "$COMPONENTS" '/usr/share/keyrings/debian-archive-keyring.gpg'
147 fi
148 fi
149
150 # add security.debian.org:
151 case "$RELEASE" in
152 unstable|sid) ;; # no security pool available
153 *)
154 # https://lists.debian.org/debian-devel-announce/2019/07/msg00004.html
155 echo "Adding security.debian.org/debian-security to sources.list.d/debian.sources."
156 writesource '/etc/apt/sources.list.d/debian.sources' 'deb' 'http://security.debian.org/debian-security' "${RELEASE}-security" "$COMPONENTS" '/usr/share/keyrings/debian-archive-keyring.gpg'
157 ;;
158 esac
159 }
160 # }}}
161
162 # remove local chroot mirror {{{
163 # shellcheck disable=SC2329
164 remove_chrootmirror() {
165 if [ "$KEEP_SRC_LIST" = "yes" ] ; then
166 echo "KEEP_SRC_LIST has been enabled, skipping remove_chrootmirror stage."
167 return
168 fi
169
170 if [ -n "$MIRROR" ] && echo "$MIRROR" | grep -q 'file:' ; then
171 echo "Removing local.sources."
172 rm /etc/apt/sources.list.d/local.sources
173 echo "Adding fallback mirror entry (${FALLBACK_MIRROR}) to sources.list.d/debian.sources instead."
174 writesource '/etc/apt/sources.list.d/debian.sources' 'deb' "$FALLBACK_MIRROR" "$RELEASE" "$COMPONENTS" '/usr/share/keyrings/debian-archive-keyring.gpg'
175 fi
176 }
177 # }}}
178
179 # set up grml repository {{{
180 # shellcheck disable=SC2329
181 grmlrepos() {
182 if [ -z "$GRMLREPOS" ] ; then
183 return 0
184 fi
185
186 # user might have provided their own apt sources configuration
187 if [ -r /etc/apt/sources.list.d/grml.sources ] ; then
188 echo "File /etc/apt/sources.list.d/grml.sources exists already, not modifying."
189 else
190 echo "Setting up /etc/apt/sources.list.d/grml.sources."
191 echo '# grml: stable repository:' >> /etc/apt/sources.list.d/grml.sources
192 writesource '/etc/apt/sources.list.d/grml.sources' 'deb deb-src' 'https://deb.grml.org' 'grml-stable' 'main' '/usr/share/keyrings/grml-archive-keyring.gpg'
193 echo '' >> /etc/apt/sources.list.d/grml.sources
194 echo '# grml: testing/development repository:' >> /etc/apt/sources.list.d/grml.sources
195 writesource '/etc/apt/sources.list.d/grml.sources' 'deb deb-src' 'https://deb.grml.org' 'grml-testing' 'main' '/usr/share/keyrings/grml-archive-keyring.gpg'
196 fi
197
198 # make sure we install packages from Grml's pool only if not available from Debian
199 if [ -r /etc/apt/preferences.d/grml.pref ] ; then
200 echo "File /etc/apt/preferences.d/grml.pref exists already, not modifying."
201 else
202 echo "Setting up /etc/apt/preferences.d/grml.pref."
203 cat > /etc/apt/preferences.d/grml.pref << EOF
204 Explanation: use Grml repository only after Debian ones
205 Package: *
206 Pin: origin deb.grml.org
207 Pin-Priority: 100
208 EOF
209 fi
210
211 apt-get update -o Acquire::AllowInsecureRepositories=1
212 apt-get -y --allow-unauthenticated install grml-keyring
213 apt-get update
214
215 if [ "$(dpkg-query -f "\${db:Status-Status} \${db:Status-Eflag}" -W grml-keyring 2>/dev/null)" != 'installed ok' ]; then
216 echo "Error: installation of grml-keyring failed." >&2
217 exit 1
218 fi
219 }
220 # }}}
221
222 # feature to provide Debian backports repos {{{
223 # shellcheck disable=SC2329
224 backportrepos() {
225 if [ -n "$BACKPORTREPOS" ] ; then
226 echo "# debian backports: ${RELEASE}-backports repository:" >> /etc/apt/sources.list.d/backports.sources
227 writesource '/etc/apt/sources.list.d/backports.sources' 'deb deb-src' "$MIRROR" "${RELEASE}-backports" 'main' '/usr/share/keyrings/debian-archive-keyring.gpg'
228 fi
229 }
230 # }}}
231
232 # set up kernel-img.conf {{{
233 # shellcheck disable=SC2329
234 kernelimg_conf() {
235 if ! [ -r /etc/kernel-img.conf ] ; then
236 echo "Setting up /etc/kernel-img.conf"
237 cat > /etc/kernel-img.conf << EOF
238 # Kernel Image management overrides
239 # See kernel-img.conf(5) for details
240 do_initrd = Yes
241 do_symlinks = Yes
242 EOF
243 fi
244 }
245 # }}}
246
247 # make sure services do not start up {{{
248 # shellcheck disable=SC2329
249 install_policy_rcd() {
250 if ! [ -r /usr/sbin/policy-rc.d ] ; then
251 export POLICYRCD=1
252 cat > /usr/sbin/policy-rc.d << EOF
253 #!/bin/sh
254 # Installed by grml-debootstrap chroot-script.
255 exit 101
256 EOF
257 chmod 775 /usr/sbin/policy-rc.d
258 fi
259 }
260 # }}}
261
262 # make sure we have an up2date system {{{
263 # shellcheck disable=SC2329
264 upgrade_system() {
265 if [ "$UPGRADE_SYSTEM" = "yes" ] ; then
266 echo "Running update + upgrade"
267 $APTUPDATE
268 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTUPGRADE
269 else
270 echo "Not running update + upgrade as \$UPDATE_AND_UPGRADE is not set to 'yes'."
271 fi
272 }
273
274 # }}}
275
276 # remove now useless apt cache {{{
277 # shellcheck disable=SC2329
278 remove_apt_cache() {
279 if [ "$RM_APTCACHE" = 'yes' ] ; then
280 echo "Cleaning apt cache."
281 # shellcheck disable=SC2086
282 apt-get clean $DPKG_OPTIONS
283 else
284 echo "Not cleaning apt cache as \$RM_APTCACHE is unset."
285 fi
286 }
287 # }}}
288
289 # install additional packages {{{
290 # shellcheck disable=SC2329
291 packages() {
292 # Pre-seed the debconf database with answers. Each question will be marked
293 # as seen to prevent debconf from asking the question interactively.
294 [ -f /etc/debootstrap/debconf-selections ] && {
295 echo "Preseeding the debconf database, some lines might be skipped..."
296 debconf-set-selections < /etc/debootstrap/debconf-selections
297 }
298
299 if [ "$PACKAGES" = 'yes' ] ; then
300 PACKAGES_FILE="/etc/debootstrap/packages"
301
302 if ! [ -r "${PACKAGES_FILE}" ] ; then
303 echo "Error: ${PACKAGES_FILE} (inside chroot) not found, exiting." >&2
304 exit 1
305 else
306 $APTUPDATE
307
308 # shellcheck disable=SC2086,SC2046
309 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $(grep -v '^#' "${PACKAGES_FILE}") $GRMLPACKAGES
310 fi
311 fi
312 }
313 # }}}
314
315 # install extra packages {{{
316 # shellcheck disable=SC2329
317 extrapackages() {
318 if [ "$EXTRAPACKAGES" = 'yes' ] ; then
319 PACKAGELIST=$(find /etc/debootstrap/extrapackages -type f -name '*.deb')
320 if [ -n "$PACKAGELIST" ]; then
321 # shellcheck disable=SC2086
322 dpkg -i $PACKAGELIST
323 # run apt again to resolve any deps
324 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL
325 fi
326 fi
327 }
328 # }}}
329
330 # check if the specified Debian package exists
331 # shellcheck disable=SC2329
332 package_exists() {
333 output=$(apt-cache show "$1" 2>/dev/null)
334 [ -n "$output" ]
335 return $?
336 }
337
338 # determine the kernel version postfix
339 # shellcheck disable=SC2329
340 get_kernel_version() {
341 # do not override $KERNEL if set via config file
342 if [ -n "$KERNEL" ] ; then
343 echo "$KERNEL"
344 return 0
345 fi
346
347 local kpackage
348 local ksuffix
349 ksuffix="${KPREFIX}$(dpkg --print-architecture)"
350 kpackage=linux-image-"${ksuffix}"
351 if package_exists "${kpackage}"; then
352 echo "${ksuffix}"
353 return 0
354 fi
355
356 echo "Automatically determined kernel package named ${kpackage} not found" >&2
357 return 1
358 }
359
360 # install kernel packages {{{
361 # shellcheck disable=SC2329
362 kernel() {
363 if [ -n "$NOKERNEL" ] ; then
364 echo "Skipping installation of kernel packages as requested via --nokernel"
365 return 0
366 fi
367
368 $APTUPDATE
369 KVER=$(get_kernel_version)
370 if [ -n "$KVER" ] ; then
371 KERNELPACKAGES="linux-image-$KVER linux-headers-$KVER firmware-linux-free $INITRD_GENERATOR"
372 # only add firmware-linux if we have non-free as a component
373 if expr "$COMPONENTS" : '.*non-free' >/dev/null ; then
374 KERNELPACKAGES="$KERNELPACKAGES firmware-linux"
375 fi
376 if [ -n "$RPI" ] ; then
377 KERNELPACKAGES="$KERNELPACKAGES raspi-firmware"
378 fi
379 # shellcheck disable=SC2086
380 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $KERNELPACKAGES
381 else
382 echo "Warning: Could not find a kernel for your system. Your system won't be able to boot itself!"
383 fi
384 }
385 # }}}
386
387 # fix kernel command line for Raspberry Pi {{{
388 rpi_cmdline() {
389 if [ -z "$RPI" ]; then
390 return 0
391 fi
392
393 local cmdline
394 cmdline="$(cat /boot/firmware/cmdline.txt)"
395 cmdline="$(sed "s/root=[^ ]*/root=UUID=${TARGET_UUID}/" <<< "$cmdline")"
396 echo "$cmdline" > /boot/firmware/cmdline.txt
397 }
398 # }}}
399
400 # reconfigure packages {{{
401 # shellcheck disable=SC2329
402 reconfigure() {
403 if [ -n "$RECONFIGURE" ] ; then
404 for package in $RECONFIGURE ; do
405 if dpkg --list "$package" >/dev/null 2>&1 | grep -q '^ii' ; then
406 DEBIAN_FRONTEND=$DEBIAN_FRONTEND dpkg-reconfigure "$package" || \
407 echo "Warning: $package does not exist, can not reconfigure it."
408 fi
409 done
410 fi
411 }
412 # }}}
413
414 # set password of user root {{{
415 # shellcheck disable=SC2329
416 passwords()
417 {
418 if [ -n "$NOPASSWORD" ] ; then
419 echo "Skip setting root password as requested."
420 return 0
421 fi
422
423 CHPASSWD_OPTION=
424 if chpasswd --help 2>&1 | grep -q -- '-m,' ; then
425 CHPASSWD_OPTION='-m'
426 fi
427
428 if [ -n "$ROOTPASSWORD" ] ; then
429 # shellcheck disable=SC2086
430 echo root:"$ROOTPASSWORD" | chpasswd $CHPASSWD_OPTION
431 export ROOTPASSWORD=''
432 else
433 a='1'
434 b='2'
435 echo "Setting password for user root:"
436 while [ "$a" != "$b" ] ; do
437 printf "Enter new UNIX password for user root: "
438 askpass
439 a="$resp"
440 unset resp
441 echo
442 printf "Retype new UNIX password for user root: "
443 askpass
444 b="$resp"
445 unset resp
446 echo
447 if [ "$a" != "$b" ] ; then
448 echo "Sorry, passwords do not match. Retry."
449 a='1'
450 b='2'
451 else
452 # shellcheck disable=SC2086
453 echo root:"$a" | chpasswd $CHPASSWD_OPTION
454 unset a
455 unset b
456 fi
457 done
458 fi
459 }
460 # }}}
461
462 # set up /etc/hosts {{{
463 # shellcheck disable=SC2329
464 hosts() {
465 if ! [ -f /etc/hosts ] ; then
466 cat > /etc/hosts << EOF
467 127.0.0.1 localhost
468 ::1 localhost ip6-localhost ip6-loopback
469 ff02::1 ip6-allnodes
470 ff02::2 ip6-allrouters
471 EOF
472 fi
473 }
474 # }}}
475
476 # set default locales {{{
477 # shellcheck disable=SC2329
478 default_locales() {
479 if [ -n "$DEFAULT_LOCALES" ] ; then
480 if ! [ -x /usr/sbin/update-locale ] ; then
481 echo "Warning: update-locale executable not available (no locales package installed?)"
482 echo "Ignoring request to run update-locale for $DEFAULT_LOCALES therefore"
483 return 0
484 fi
485
486 /usr/sbin/update-locale LANGUAGE="$DEFAULT_LANGUAGE" LANG="$DEFAULT_LOCALES"
487 fi
488 }
489 # }}}
490
491 # adjust timezone {{{
492 # shellcheck disable=SC2329
493 timezone() {
494 if [ -n "$TIMEZONE" ] ; then
495 echo "Adjusting /etc/localtime"
496 ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
497
498 if [ -e /etc/timezone ] ; then
499 # not necessary for trixie or newer, see tzdata 2024b-6 changelog.
500 # https://salsa.debian.org/glibc-team/tzdata/-/commit/c071fbc167ad306394b576879d515e6ecbe5a734
501 echo "Setting /etc/timezone to $TIMEZONE"
502 printf '%s\n' "$TIMEZONE" > /etc/timezone
503 fi
504 fi
505 }
506 # }}}
507
508 # helper function for fstab() {{{
509 # shellcheck disable=SC2329
510 createfstab(){
511 echo "Setting up /etc/fstab"
512 cat > /etc/fstab <<EOF
513 # /etc/fstab - created by grml-debootstrap on $(date)
514 # Accessible filesystems, by reference, are maintained under '/dev/disk/'.
515 # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
516 #
517 # After editing this file, run 'systemctl daemon-reload' to update systemd
518 # units generated from this file.
519 #
520 EOF
521
522 if [ -n "$TARGET_UUID" ] ; then
523 local rootfs_mount_options=""
524
525 if [ -z "${FILESYSTEM}" ] ; then
526 FILESYSTEM="$(blkid -o value -s TYPE /dev/disk/by-uuid/"${TARGET_UUID}")" || true
527 fi
528
529 case "${FILESYSTEM}" in
530 # errors=remount-ro is supported only by a few file systems
531 ext*|exfat|fat|jfs|nilfs2|vfat)
532 rootfs_mount_options=",errors=remount-ro"
533 ;;
534 esac
535
536 echo "/dev/disk/by-uuid/${TARGET_UUID} / auto defaults${rootfs_mount_options} 0 1" >> /etc/fstab
537 else
538 echo "Warning: couldn't identify target UUID for rootfs, your /etc/fstab might be incomplete."
539 fi
540
541 if [ -n "$EFI" ] ; then
542 UUID_EFI="$(blkid -o value -s UUID "$EFI")"
543 echo "UUID=$UUID_EFI /boot/efi vfat umask=0077 0 1" >> /etc/fstab
544 fi
545
546 if [ -n "$RPIFIRM" ] ; then
547 UUID_RPIFIRM="$(blkid -o value -s UUID "$RPIFIRM")"
548 echo "UUID=$UUID_RPIFIRM /boot/firmware vfat umask=0077 0 1" >> /etc/fstab
549 fi
550
551 cat >> /etc/fstab << EOF
552 proc /proc proc defaults 0 0
553 /dev/cdrom /mnt/cdrom0 iso9660 ro,user,noauto 0 0
554 # some other examples:
555 # /dev/sda2 none swap sw,pri=0 0 0
556 # /dev/hda1 /Grml ext3 dev,suid,user,noauto 0 2
557 # //1.2.3.4/pub /smb/pub cifs user,noauto,uid=grml,gid=grml 0 0
558 # linux:/pub /beer nfs defaults 0 0
559 # tmpfs /tmp tmpfs size=300M 0 0
560 # /dev/sda5 none swap sw 0 0
561 EOF
562 }
563 # }}}
564
565 # generate /etc/fstab {{{
566 # shellcheck disable=SC2329
567 fstab() {
568 # set up /etc/fstab if file is UNCONFIGURED (debootstrap, mmdebstrap)
569 if grep -q UNCONFIGURED /etc/fstab ; then
570 createfstab
571 fi
572 }
573 # }}}
574
575 # ensure we have according filesystem tools available {{{
576 # shellcheck disable=SC2329
577 install_fs_tools() {
578 local pkg=""
579
580 # note: this is supposed to be coming either via command lines'
581 # $_opt_filesystem or via createfstab()
582 case "${FILESYSTEM}" in
583 jfs)
584 pkg="jfsutils"
585 ;;
586 xfs)
587 pkg="xfsprogs"
588 ;;
589 esac
590
591 if [ -n "${pkg:-}" ] && ! dpkg --list "${pkg}" 2>/dev/null | grep -q '^ii' ; then
592 echo "Filesystem package ${pkg} not present, installing now"
593 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL "${pkg}"
594 fi
595 }
596 # }}}
597
598 # set up hostname {{{
599 # shellcheck disable=SC2329
600 hostname() {
601 if [ -n "$HOSTNAME" ] ; then
602 echo "Setting hostname to ${HOSTNAME}."
603 echo "$HOSTNAME" > /etc/hostname
604
605 # adjust postfix configuration
606 if [ -r /etc/postfix/main.cf ] ; then
607 # adjust hostname related options:
608 sed -i "s/grml/$HOSTNAME/g" /etc/postfix/main.cf
609
610 # listen on loopback interface only:
611 sed -i "s/^inet_interfaces = .*/inet_interfaces = loopback-only/" /etc/postfix/main.cf
612 grep -q inet_interfaces /etc/postfix/main.cf || echo 'inet_interfaces = loopback-only' >> /etc/postfix/main.cf
613 fi
614 if [ -r /etc/mailname ] ; then
615 # adjust /etc/mailname
616 local etc_mail_domain
617 etc_mail_domain=$(/bin/dnsdomainname 2>/dev/null || echo localdomain)
618 case "$HOSTNAME" in
619 *.*)
620 local mailname="$HOSTNAME"
621 ;;
622 *)
623 local mailname="${HOSTNAME}.${etc_mail_domain}"
624 ;;
625 esac
626 echo "Setting mailname to ${mailname}"
627 echo "$mailname" > /etc/mailname
628 fi
629 fi
630 }
631 # }}}
632
633 # generate initrd/initramfs {{{
634 # shellcheck disable=SC2329
635 initrd() {
636 # assume the first available kernel as our main kernel
637 # shellcheck disable=SC2012
638 KERNELIMG=$(ls -1 /boot/vmlinuz-* 2>/dev/null | head -1)
639 if [ -z "$KERNELIMG" ] ; then
640 echo 'No kernel image found, skipping initrd stuff.'>&2
641 return
642 fi
643
644 KERNELVER=${KERNELIMG#/boot/vmlinuz-}
645
646 # generate initrd
647 if [ "$INITRD" = "yes" ] ; then
648 echo "Generating initrd."
649 if [ "$INITRD_GENERATOR" = 'dracut' ] ; then
650 # shellcheck disable=SC2086
651 dracut --no-hostonly --kver "$KERNELVER" --fstab --add-fstab /etc/fstab --force --reproducible $INITRD_GENERATOR_OPTS
652 else
653 # shellcheck disable=SC2086
654 update-initramfs -c -t -k "$KERNELVER" $INITRD_GENERATOR_OPTS
655 fi
656 fi
657 }
658 # }}}
659
660 # shellcheck disable=SC2329
661 efi_setup() {
662 if [ -z "$EFI" ] ; then
663 return 0
664 fi
665
666 if ! dpkg --list efibootmgr 2>/dev/null | grep -q '^ii' ; then
667 echo "Notice: efi option set but no efibootmgr package, installing it therefore."
668 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL efibootmgr
669 fi
670
671 mkdir -p /boot/efi
672 echo "Mounting $EFI on /boot/efi"
673 mount "$EFI" /boot/efi
674
675 # if efivarfs kernel module is loaded, but efivars isn't,
676 # then we need to mount efivarfs for efibootmgr usage
677 if ! ls /sys/firmware/efi/efivars/* &>/dev/null ; then
678 echo "Mounting efivarfs on /sys/firmware/efi/efivars"
679 mount -t efivarfs efivarfs /sys/firmware/efi/efivars || true
680 fi
681
682 echo "Invoking efibootmgr"
683 efibootmgr || true
684 }
685
686 # grub configuration/installation {{{
687
688 # helper function to get relevant /dev/disk/by-id/* entries,
689 # based on GRUB's postinst script
690 # shellcheck disable=SC2329
691 available_ids() {
692 local path ids
693
694 [ -d /dev/disk/by-id ] || return
695 ids="$(
696 for path in /dev/disk/by-id/*; do
697 [ -e "${path}" ] || continue
698 printf '%s %s\n' "${path}" "$(readlink -f "${path}")"
699 done | sort -k2 -s -u | cut -d' ' -f1
700 )"
701 echo "${ids}"
702 }
703
704 # helper function to report corresponding /dev/disk/by-id/ for a given device name,
705 # based on GRUB's postinst script
706 # shellcheck disable=SC2329
707 device_to_id() {
708 local id
709
710 for id in $(available_ids); do
711 if [ "$(readlink -f "${id}")" = "$(readlink -f "$1")" ]; then
712 echo "${id}"
713 return 0
714 fi
715 done
716
717 # Fall back to the plain device name if there's no by-id link for it.
718 if [ -e "$1" ]; then
719 echo "$1"
720 return 0
721 fi
722
723 echo "ERROR: Device '$1' does not exist!"
724 return 1
725 }
726
727 # shellcheck disable=SC2329
728 is_grub_bios_compatible() {
729 # Check if the disk uses an MSDOS partition table, these are always compatible
730 if [[ "$(blkid "$GRUB")" =~ 'PTTYPE="dos"' ]]; then
731 return 0
732 # Look for a BIOS boot partition otherwise
733 else
734 SEARCH_STR="$GRUB"
735 if [[ "$SEARCH_STR" =~ ^/dev/loop ]]; then
736 SEARCH_STR="${SEARCH_STR//\/dev\//}" # loopX
737 SEARCH_STR="/dev/mapper/${SEARCH_STR}" # /dev/mapper/loopX
738 # Note that /dev/mapper/loopX won't actually exist, but
739 # /dev/mapper/loopXpY will, so this works for the regex check in the
740 # while loop below.
741 fi
742 while read -r line; do
743 if [[ "$line" =~ ^${SEARCH_STR}.*21686148-6449-6e6f-744e-656564454649$ ]]; then
744 return 0
745 fi
746 done < <(lsblk -pnlo NAME,PARTTYPE)
747 fi
748 return 1
749 }
750
751 # shellcheck disable=SC2329
752 run_grub_install() {
753 grub_install_cmd=( 'grub-install' "$@" )
754 if ! "${grub_install_cmd[@]}" ; then
755 echo "Error: failed to execute '${grub_install_cmd[*]}'." >&2
756 exit 1
757 fi
758 }
759
760 # shellcheck disable=SC2329
761 grub_install() {
762 if [ -z "$GRUB" ] ; then
763 echo "Notice: \$GRUB not defined, will not install grub inside chroot at this stage."
764 return 0
765 fi
766 MAIN_GRUB_PACKAGE=""
767 GRUB_SECBOOT_PACKAGES=()
768
769 case "$ARCH" in
770 amd64)
771 if is_grub_bios_compatible && [ -n "$EFI" ]; then
772 MAIN_GRUB_PACKAGE="grub-cloud-amd64"
773 GRUB_SECBOOT_PACKAGES=( "grub-efi-amd64-signed" "shim-signed" )
774 elif [ -n "$EFI" ]; then
775 MAIN_GRUB_PACKAGE="grub-efi-amd64"
776 GRUB_SECBOOT_PACKAGES=( "grub-efi-amd64-signed" "shim-signed" )
777 else
778 MAIN_GRUB_PACKAGE="grub-pc"
779 fi
780 ;;
781 arm64)
782 if [ -n "$EFI" ]; then
783 MAIN_GRUB_PACKAGE="grub-efi-arm64"
784 GRUB_SECBOOT_PACKAGES=( "grub-efi-arm64-signed" "shim-signed" )
785 fi
786 ;;
787 esac
788
789 if [ -z "$MAIN_GRUB_PACKAGE" ]; then
790 echo "Notice: No applicable bootloaders found, will not install grub inside chroot at this stage."
791 return 0
792 fi
793
794 efi_setup
795
796 # make sure this is pre-defined so we have sane settings for automated
797 # upgrades, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=711019
798 local grub_device
799 grub_device=$(device_to_id "${GRUB}")
800 if [ -z "${grub_device:-}" ] ; then
801 echo "Warning: Could not identify /dev/disk/by-id/... for '${GRUB}', falling back to '${GRUB}'"
802 grub_device="${GRUB}"
803 fi
804
805 if [ -n "$MAIN_GRUB_PACKAGE" ] && ! [[ "$MAIN_GRUB_PACKAGE" =~ ^grub-cloud ]]; then
806 echo "Setting grub debconf configuration for install device to $GRUB"
807 echo "${MAIN_GRUB_PACKAGE} ${MAIN_GRUB_PACKAGE}/install_devices multiselect ${grub_device}" | debconf-set-selections
808 fi
809
810 echo "Installing automatically-determined grub packages ${MAIN_GRUB_PACKAGE}" "${GRUB_SECBOOT_PACKAGES[@]}"
811 DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL "${MAIN_GRUB_PACKAGE}" "${GRUB_SECBOOT_PACKAGES[@]}"
812
813 if ! [ -x "$(command -v grub-install)" ] ; then
814 echo "Error: grub-install not available. (Error while installing grub package?)" >&2
815 return 1
816 fi
817 if ! [ -x "$(command -v update-grub)" ] ; then
818 echo "Error: update-grub not available. (Error while installing grub package?)" >&2
819 return 1
820 fi
821
822 local grub_targets=""
823 if [ -n "$SELECTED_PARTITIONS" ]; then
824 # sw-raid
825 local device
826 for device in $SELECTED_PARTITIONS ; do
827 local grub_target="${device%%[0-9]}"
828 grub_targets="${grub_targets} ${grub_target}"
829 done
830 else
831 grub_targets="${GRUB}"
832 fi
833
834 local device
835 for device in $grub_targets ; do
836 echo "Installing grub on ${device}:"
837 if [ -n "$EFI" ]; then
838 case "${ARCH}" in
839 amd64) run_grub_install --no-floppy --target=x86_64-efi --force-extra-removable "${device}";;
840 arm64) run_grub_install --no-floppy --target=arm64-efi --force-extra-removable "${device}";;
841 esac
842 fi
843 if [ "$MAIN_GRUB_PACKAGE" = 'grub-cloud-amd64' ] || [ -z "$EFI" ]; then
844 run_grub_install --no-floppy --target=i386-pc "${device}"
845 fi
846 done
847 rm -f /boot/grub/device.map # avoid confusion with sw-raid
848
849 if [ -n "${BOOT_APPEND}" ] ; then
850 echo "Adding BOOT_APPEND configuration ['${BOOT_APPEND}'] to /etc/default/grub."
851 sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" /etc/default/grub
852 fi
853
854 # create (/update) grub configuration
855 if ! update-grub ; then
856 echo "Error: update-grub failed." >&2
857 return 1
858 fi
859
860 if mountpoint -q /boot/efi ; then
861 umount /boot/efi
862 fi
863
864 return 0
865 }
866 # }}}
867
868 # execute all scripts present in /etc/debootstrap/chroot-scripts/ {{{
869 # shellcheck disable=SC2329
870 custom_scripts() {
871 [ -d /etc/debootstrap/chroot-scripts/ ] || return 0
872
873 for script in /etc/debootstrap/chroot-scripts/* ; do
874 echo "Executing script $script"
875 $script && echo "done" || echo "failed"
876 done
877 }
878 # }}}
879
880 # make sure we don't have any running processes left {{{
881 # shellcheck disable=SC2329
882 services() {
883 for service in ssh mdadm mdadm-raid ; do
884 if [ -x /etc/init.d/"$service" ] ; then
885 /etc/init.d/"$service" stop || true
886 fi
887 done
888 }
889 # }}}
890
891 # unmount /proc and make sure nothing is left {{{
892 # shellcheck disable=SC2329
893 finalize() {
894 # make sure we don't leave any sensible data
895 rm -f /etc/debootstrap/variables
896
897 [ -n "$POLICYRCD" ] && rm -f /usr/sbin/policy-rc.d
898
899 umount /sys/firmware/efi/efivars &>/dev/null || true
900
901 umount /sys >/dev/null 2>/dev/null || true
902 umount /proc >/dev/null 2>/dev/null || true
903
904 umount /boot/firmware >/dev/null 2>/dev/null || true
905 }
906 # }}}
907
908 # signal handler {{{
909 # shellcheck disable=SC2329
910 signal_handler() {
911 finalize
912 [ -n "$1" ] && EXIT="$1" || EXIT="1"
913 exit "$EXIT"
914 }
915 # }}}
916
917 # set signal handler {{{
918 trap signal_handler HUP INT QUIT TERM
919 # }}}
920
921 # execute the functions {{{
922
923 # always execute install_policy_rcd
924 install_policy_rcd
925
926 for i in markauto chrootmirror grmlrepos backportrepos kernelimg_conf \
927 kernel packages extrapackages reconfigure hosts \
928 default_locales timezone fstab install_fs_tools hostname \
929 initrd grub_install passwords \
930 custom_scripts upgrade_system rpi_cmdline remove_apt_cache services \
931 remove_chrootmirror; do
932 if stage "$i" ; then
933 "$i"
934 stage "$i" 'done'
935 fi
936 done
937 # always execute the finalize stage:
938 finalize
939 # }}}
940
941 # finally exit the chroot {{{
942 echo "Finished chroot installation, exiting."
943 exit 0
944 # }}}
945
946 ## END OF FILE #################################################################
947 # vim: ai tw=80 expandtab foldmethod=marker