Merge remote-tracking branch 'origin/pr/242'
[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   # add security.debian.org:
105   case "$RELEASE" in
106     unstable|sid) ;;  # no security pool available
107     jessie|stretch|buster)
108       echo "Adding security.debian.org to sources.list."
109       echo "deb http://security.debian.org ${RELEASE}/updates $COMPONENTS" >> /etc/apt/sources.list
110       ;;
111     *)
112       # bullseye and newer releases use a different repository layout, see
113       # https://lists.debian.org/debian-devel-announce/2019/07/msg00004.html
114       echo "Adding security.debian.org/debian-security to sources.list."
115       echo "deb http://security.debian.org/debian-security ${RELEASE}-security $COMPONENTS" >> /etc/apt/sources.list
116       ;;
117   esac
118 }
119 # }}}
120
121 # remove local chroot mirror {{{
122 remove_chrootmirror() {
123   if [ "$KEEP_SRC_LIST" = "yes" ] ; then
124     echo "KEEP_SRC_LIST has been enabled, skipping remove_chrootmirror stage."
125     return
126   fi
127
128   if [ -n "$ISO" ] ; then
129     echo "Removing ISO (${ISO}) from sources.list."
130     TMP_ISO="${ISO//\//\\\/}"
131     sed -i "/deb $TMP_ISO $RELEASE $COMPONENTS/ D" /etc/apt/sources.list
132   else
133     if [ -n "$MIRROR" ] && echo "$MIRROR" | grep -q 'file:' ; then
134       echo "Removing local mirror (${MIRROR}) from sources.list."
135       TMP_MIRROR="${MIRROR//\//\\\/}"
136       sed -i "/deb $TMP_MIRROR $RELEASE $COMPONENTS/ D" /etc/apt/sources.list
137       echo "Adding fallback mirror entry (${FALLBACK_MIRROR}) to sources.list instead."
138       echo "deb $FALLBACK_MIRROR $RELEASE $COMPONENTS" >> /etc/apt/sources.list
139     fi
140   fi
141 }
142 # }}}
143
144 # set up grml repository {{{
145 grmlrepos() {
146   if [ -z "$GRMLREPOS" ] ; then
147     return 0
148   fi
149
150   # user might have provided their own apt sources configuration
151   if [ -r /etc/apt/sources.list.d/grml.list ] ; then
152     echo "File /etc/apt/sources.list.d/grml.list exists already, not modifying."
153   else
154     echo "Setting up /etc/apt/sources.list.d/grml.list."
155     cat > /etc/apt/sources.list.d/grml.list << EOF
156 # grml: stable repository:
157   deb     [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-stable main
158   deb-src [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-stable main
159
160 # grml: testing/development repository:
161   deb     [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-testing main
162   deb-src [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-testing main
163 EOF
164   fi
165
166   # make sure we install packages from Grml's pool only if not available from Debian
167   if [ -r /etc/apt/preferences.d/grml.pref ] ; then
168     echo "File /etc/apt/preferences.d/grml.pref exists already, not modifying."
169   else
170     echo "Setting up /etc/apt/preferences.d/grml.pref."
171     cat > /etc/apt/preferences.d/grml.pref << EOF
172 Explanation: use Grml repository only after Debian ones
173 Package: *
174 Pin: origin deb.grml.org
175 Pin-Priority: 100
176 EOF
177   fi
178
179   apt-get update -o Acquire::AllowInsecureRepositories=1
180   apt-get -y --allow-unauthenticated install grml-debian-keyring
181   apt-get update
182
183   if [ "$(dpkg-query -f "\${db:Status-Status} \${db:Status-Eflag}" -W grml-debian-keyring 2>/dev/null)" != 'installed ok' ]; then
184     echo "Error: installation of grml-debian-keyring failed." >&2
185     exit 1
186   fi
187 }
188 # }}}
189
190 # feature to provide Debian backports repos {{{
191 backportrepos() {
192   if [ -n "$BACKPORTREPOS" ] ; then
193     cat >> /etc/apt/sources.list.d/backports.list << EOF
194 # debian backports: ${RELEASE}-backports repository:
195 deb     ${MIRROR} ${RELEASE}-backports main
196 deb-src ${MIRROR} ${RELEASE}-backports main
197 EOF
198   fi
199 }
200 # }}}
201
202 # set up kernel-img.conf {{{
203 kernelimg_conf() {
204   if ! [ -r /etc/kernel-img.conf ] ; then
205      echo "Setting up /etc/kernel-img.conf"
206      cat > /etc/kernel-img.conf << EOF
207 # Kernel Image management overrides
208 # See kernel-img.conf(5) for details
209 do_initrd = Yes
210 do_symlinks = Yes
211 EOF
212   fi
213 }
214 # }}}
215
216 # make sure services do not start up {{{
217 install_policy_rcd() {
218   if ! [ -r /usr/sbin/policy-rc.d ] ; then
219      export POLICYRCD=1
220      cat > /usr/sbin/policy-rc.d << EOF
221 #!/bin/sh
222 exit 101
223 EOF
224      chmod 775 /usr/sbin/policy-rc.d
225   fi
226 }
227 # }}}
228
229 # make sure we have an up2date system {{{
230 upgrade_system() {
231   if [ "$UPGRADE_SYSTEM" = "yes" ] ; then
232     echo "Running update + upgrade"
233     $APTUPDATE
234     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTUPGRADE
235   else
236     echo "Not running update + upgrade as \$UPDATE_AND_UPGRADE is not set to 'yes'."
237   fi
238 }
239
240 # }}}
241 # remove now useless apt cache {{{
242 remove_apt_cache() {
243   if [ "$RM_APTCACHE" = 'yes' ] ; then
244     echo "Cleaning apt cache."
245     # shellcheck disable=SC2086
246     apt-get clean $DPKG_OPTIONS
247   else
248     echo "Not cleaning apt cache as \$RM_APTCACHE is unset."
249   fi
250 }
251 # }}}
252
253 # install additional packages {{{
254 packages() {
255   # Pre-seed the debconf database with answers. Each question will be marked
256   # as seen to prevent debconf from asking the question interactively.
257   [ -f /etc/debootstrap/debconf-selections ] && {
258     echo "Preseeding the debconf database, some lines might be skipped..."
259     debconf-set-selections < /etc/debootstrap/debconf-selections
260   }
261
262   if [ "$PACKAGES" = 'yes' ] ; then
263     PACKAGES_FILE="/etc/debootstrap/packages"
264
265     if [ "$ARCH" = 'arm64' ]; then
266       PACKAGES_FILE="/etc/debootstrap/packages-arm64"
267     fi
268
269     if ! [ -r "${PACKAGES_FILE}" ] ; then
270       echo "Error: ${PACKAGES_FILE} (inside chroot) not found, exiting." >&2
271       exit 1
272     else
273       $APTUPDATE
274
275       # shellcheck disable=SC2086,SC2046
276       DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $(grep -v '^#' "${PACKAGES_FILE}") $GRMLPACKAGES
277     fi
278   fi
279 }
280 # }}}
281
282 # install extra packages {{{
283 extrapackages() {
284     if [ "$EXTRAPACKAGES" = 'yes' ] ; then
285         PACKAGELIST=$(find /etc/debootstrap/extrapackages -type f -name '*.deb')
286         if [ -n "$PACKAGELIST" ]; then
287             # shellcheck disable=SC2086
288             dpkg -i $PACKAGELIST
289             # run apt again to resolve any deps
290             DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL
291         fi
292     fi
293 }
294 # }}}
295
296 # check if the specified Debian package exists
297 package_exists() {
298   output=$(apt-cache show "$1" 2>/dev/null)
299   [ -n "$output" ]
300   return $?
301 }
302
303
304 # determine the kernel version postfix
305 get_kernel_version() {
306   # do not override $KERNEL if set via config file
307   if [ -n "$KERNEL" ] ; then
308     echo "$KERNEL"
309     return 0
310   fi
311
312   local KARCH
313
314   # shellcheck disable=SC2153
315   case "$ARCH" in
316     i386)
317       KARCH='686-pae'
318       ;;
319     amd64)
320       KARCH='amd64'
321       ;;
322     arm64)
323       KARCH='arm64'
324       ;;
325     *)
326       echo "Only i386, amd64 and arm64 are currently supported" >&2
327       return 1
328   esac
329
330   local KPACKAGE
331   KPACKAGE=linux-image-"${KPREFIX}${KARCH}"
332   if package_exists "$KPACKAGE"; then
333     echo "${KPREFIX}${KARCH}"
334     return 0
335   fi
336
337   echo "Expected kernel package $KPACKAGE not found" >&2
338   return 1
339 }
340
341 # install kernel packages {{{
342 kernel() {
343   if [ -n "$NOKERNEL" ] ; then
344     echo "Skipping installation of kernel packages as requested via --nokernel"
345     return 0
346   fi
347
348   $APTUPDATE
349   KVER=$(get_kernel_version)
350   if [ -n "$KVER" ] ; then
351      # note: install busybox to be able to debug initramfs
352      KERNELPACKAGES="linux-image-$KVER linux-headers-$KVER busybox firmware-linux-free"
353      # only add firmware-linux if we have non-free as a component
354      if expr "$COMPONENTS" : '.*non-free' >/dev/null ; then
355        KERNELPACKAGES="$KERNELPACKAGES firmware-linux"
356      fi
357      # shellcheck disable=SC2086
358      DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $KERNELPACKAGES
359   else
360      echo "Warning: Could not find a kernel for your system. Your system won't be able to boot itself!"
361   fi
362 }
363 # }}}
364
365 # reconfigure packages {{{
366 reconfigure() {
367   if [ -n "$RECONFIGURE" ] ; then
368      for package in $RECONFIGURE ; do
369          if dpkg --list "$package" >/dev/null 2>&1 | grep -q '^ii' ; then
370            DEBIAN_FRONTEND=$DEBIAN_FRONTEND dpkg-reconfigure "$package" || \
371            echo "Warning: $package does not exist, can not reconfigure it."
372          fi
373      done
374   fi
375 }
376 # }}}
377
378 # set password of user root {{{
379 passwords()
380 {
381   if [ -n "$NOPASSWORD" ] ; then
382     echo "Skip setting root password as requested."
383     return 0
384   fi
385
386   echo "Activating shadow passwords."
387   shadowconfig on
388
389   CHPASSWD_OPTION=
390   if chpasswd --help 2>&1 | grep -q -- '-m,' ; then
391      CHPASSWD_OPTION='-m'
392   fi
393
394   if [ -n "$ROOTPASSWORD" ] ; then
395      echo root:"$ROOTPASSWORD" | chpasswd $CHPASSWD_OPTION
396      export ROOTPASSWORD=''
397   else
398     a='1'
399     b='2'
400      echo "Setting password for user root:"
401      while [ "$a" != "$b" ] ; do
402        printf "Enter new UNIX password for user root: "
403        askpass
404        a="$resp"
405        unset resp
406        echo
407        printf "Retype new UNIX password for user root: "
408        askpass
409        b="$resp"
410        unset resp
411        echo
412        if [ "$a" != "$b" ] ; then
413          echo "Sorry, passwords do not match. Retry."
414          a='1'
415          b='2'
416        else
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          DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL dracut
604          dracut --no-hostonly --kver "$KERNELVER" --fstab --add-fstab /etc/fstab --force --reproducible $INITRD_GENERATOR_OPTS
605      else
606          update-initramfs -c -t -k "$KERNELVER" $INITRD_GENERATOR_OPTS
607      fi
608   fi
609 }
610 # }}}
611
612 efi_setup() {
613   if [ -z "$EFI" ] ; then
614     return 0
615   fi
616
617   if ! dpkg --list efibootmgr 2>/dev/null | grep -q '^ii' ; then
618     echo "Notice: efi option set but no efibootmgr package, installing it therefore."
619     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL efibootmgr
620   fi
621
622   mkdir -p /boot/efi
623   echo "Mounting $EFI on /boot/efi"
624   mount "$EFI" /boot/efi || return 1
625
626   # if efivarfs kernel module is loaded, but efivars isn't,
627   # then we need to mount efivarfs for efibootmgr usage
628   if ! ls /sys/firmware/efi/efivars/* &>/dev/null ; then
629     echo "Mounting efivarfs on /sys/firmware/efi/efivars"
630     mount -t efivarfs efivarfs /sys/firmware/efi/efivars
631   fi
632
633   echo "Invoking efibootmgr"
634   efibootmgr || return 1
635 }
636
637 # grub configuration/installation {{{
638
639 # helper function to get relevant /dev/disk/by-id/* entries,
640 # based on GRUB's postinst script
641 available_ids() {
642   local path ids
643
644   [ -d /dev/disk/by-id ] || return
645   ids="$(
646     for path in /dev/disk/by-id/*; do
647       [ -e "${path}" ] || continue
648       printf '%s %s\n' "${path}" "$(readlink -f "${path}")"
649     done | sort -k2 -s -u | cut -d' ' -f1
650   )"
651   echo "${ids}"
652 }
653
654 # helper function to report corresponding /dev/disk/by-id/ for a given device name,
655 # based on GRUB's postinst script
656 device_to_id() {
657   local id
658
659   for id in $(available_ids); do
660     if [ "$(readlink -f "${id}")" = "$(readlink -f "$1")" ]; then
661       echo "${id}"
662       return 0
663     fi
664   done
665
666   # Fall back to the plain device name if there's no by-id link for it.
667   if [ -e "$1" ]; then
668     echo "$1"
669     return 0
670   fi
671   return 1
672 }
673
674 grub_install() {
675
676   if [ -z "$GRUB" ] ; then
677     echo "Notice: \$GRUB not defined, will not install grub inside chroot at this stage."
678     return 0
679   fi
680
681   efi_setup || return 1
682
683   if [ -n "$EFI" ] ; then
684     GRUB_PACKAGE=grub-efi-amd64
685   else
686     GRUB_PACKAGE=grub-pc
687   fi
688
689   # make sure this is pre-defined so we have sane settings for automated
690   # upgrades, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=711019
691   local grub_device
692   grub_device=$(device_to_id "${GRUB}")
693   if [ -z "${grub_device:-}" ] ; then
694      echo "Warning: Could not identify /dev/disk/by-id/... for '${GRUB}', falling back to '${GRUB}'"
695      grub_device="${GRUB}"
696   fi
697
698   echo "Setting ${GRUB_PACKAGE} debconf configuration for install device to $GRUB"
699   echo "${GRUB_PACKAGE} ${GRUB_PACKAGE}/install_devices multiselect ${grub_device}" | debconf-set-selections
700
701   if ! dpkg --list ${GRUB_PACKAGE} 2>/dev/null | grep -q '^ii' ; then
702     echo "Notice: grub option set but no ${GRUB_PACKAGE} package, installing it therefore."
703     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL ${GRUB_PACKAGE}
704   fi
705
706   if ! [ -x "$(command -v grub-install)" ] ; then
707      echo "Error: grub-install not available. (Error while installing grub package?)" >&2
708      return 1
709   fi
710   if ! [ -x "$(command -v update-grub)" ] ; then
711      echo "Error: update-grub not available. (Error while installing grub package?)" >&2
712      return 1
713   fi
714
715   if [ -n "$SELECTED_PARTITIONS" ] ; then # using sw-raid
716      for device in $SELECTED_PARTITIONS ; do
717         GRUB="${device%%[0-9]}"
718         echo "Installing grub on ${GRUB}:"
719         if ! grub-install --no-floppy "$GRUB" ; then
720           echo "Error: failed to execute 'grub-install --no-floppy $GRUB'." >&2
721           exit 1
722         fi
723
724      done
725      rm -f /boot/grub/device.map
726   else
727     echo "Installing grub on ${GRUB}:"
728     echo "(hd0) ${GRUB}" > /boot/grub/device.map
729     if ! grub-install "(hd0)" ; then
730       echo "Error: failed to execute 'grub-install (hd0)'." >&2
731       exit 1
732     fi
733     rm /boot/grub/device.map
734   fi
735
736   echo "Adjusting grub configuration for use on ${GRUB}."
737
738   if [ -n "${BOOT_APPEND}" ] ; then
739     echo "Adding BOOT_APPEND configuration ['${BOOT_APPEND}'] to /etc/default/grub."
740     sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" /etc/default/grub
741   fi
742
743   mountpoint /boot/efi &>/dev/null && umount /boot/efi
744
745   # finally install grub. Existence of update-grub is checked above.
746   update-grub
747 }
748 # }}}
749
750 # execute all scripts present in /etc/debootstrap/chroot-scripts/ {{{
751 custom_scripts() {
752   [ -d /etc/debootstrap/chroot-scripts/ ] || return 0
753
754   for script in /etc/debootstrap/chroot-scripts/* ; do
755       echo "Executing script $script"
756       $script && echo "done" || echo "failed"
757   done
758 }
759 # }}}
760
761 # make sure we don't have any running processes left {{{
762 services() {
763   for service in ssh mdadm mdadm-raid ; do
764     if [ -x /etc/init.d/"$service" ] ; then
765        /etc/init.d/"$service" stop || true
766     fi
767   done
768 }
769 # }}}
770
771 # unmount /proc and make sure nothing is left {{{
772 finalize() {
773   # make sure we don't leave any sensible data
774   rm -f /etc/debootstrap/variables
775
776   [ -n "$POLICYRCD" ] && rm -f /usr/sbin/policy-rc.d
777
778   umount /sys/firmware/efi/efivars &>/dev/null || true
779
780   umount /sys >/dev/null 2>/dev/null || true
781   umount /proc >/dev/null 2>/dev/null || true
782 }
783 # }}}
784
785 # signal handler {{{
786 signal_handler() {
787   finalize
788   [ -n "$1" ] && EXIT="$1" || EXIT="1"
789   exit "$EXIT"
790 }
791 # }}}
792
793 # set signal handler {{{
794 trap signal_handler HUP INT QUIT TERM
795 # }}}
796
797 # execute the functions {{{
798
799  # always execute install_policy_rcd
800  install_policy_rcd
801
802  for i in chrootmirror grmlrepos backportrepos kernelimg_conf \
803      kernel packages extrapackages reconfigure hosts \
804      default_locales timezone fstab install_fs_tools hostname \
805      initrd grub_install passwords \
806      custom_scripts upgrade_system remove_apt_cache services \
807      remove_chrootmirror; do
808      if stage $i ; then
809        $i && stage $i 'done' || exit 1
810      fi
811   done
812   # always execute the finalize stage:
813   finalize
814 # }}}
815
816 # finally exit the chroot {{{
817   echo "Finished chroot installation, exiting."
818   exit 0
819 # }}}
820
821 ## END OF FILE #################################################################
822 # vim: ai tw=80 expandtab foldmethod=marker