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