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