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