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