Initial arm64 support
[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     PACKAGES_FILE="/etc/debootstrap/packages"
273
274     if [ "$ARCH" = 'arm64' ]; then
275       PACKAGES_FILE="/etc/debootstrap/packages-arm64"
276     fi
277
278     if ! [ -r "${PACKAGES_FILE}" ] ; then
279       echo "Error: ${PACKAGES_FILE} (inside chroot) not found, exiting." >&2
280       exit 1
281     else
282       $APTUPDATE
283
284       # shellcheck disable=SC2086,SC2046
285       DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $(grep -v '^#' "${PACKAGES_FILE}") $GRMLPACKAGES
286     fi
287   fi
288 }
289 # }}}
290
291 # install extra packages {{{
292 extrapackages() {
293     if [ "$EXTRAPACKAGES" = 'yes' ] ; then
294         PACKAGELIST=$(find /etc/debootstrap/extrapackages -type f -name '*.deb')
295         if [ -n "$PACKAGELIST" ]; then
296             # shellcheck disable=SC2086
297             dpkg -i $PACKAGELIST
298             # run apt again to resolve any deps
299             DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL
300         fi
301     fi
302 }
303 # }}}
304
305 # check if the specified Debian package exists
306 package_exists() {
307   output=$(apt-cache show "$1" 2>/dev/null)
308   [ -n "$output" ]
309   return $?
310 }
311
312
313 # determine the kernel version postfix
314 get_kernel_version() {
315   # do not override $KERNEL if set via config file
316   if [ -n "$KERNEL" ] ; then
317     echo "$KERNEL"
318     return 0
319   fi
320
321   local KARCH
322
323   # shellcheck disable=SC2153
324   case "$ARCH" in
325     i386)
326       case "$RELEASE" in
327         lenny|squeeze|wheezy) KARCH='686' ;;
328         # since jessie the linux-image-686 image doesn't exist any longer
329         *) KARCH='686-pae' ;;
330       esac
331       ;;
332     amd64)
333       KARCH='amd64'
334       ;;
335     arm64)
336       KARCH='arm64'
337       ;;
338     *)
339       echo "Only i386, amd64 and arm64 are currently supported" >&2
340       return 1
341   esac
342
343   for KPREFIX in "" "2.6-" ; do  # iterate through the kernel prefixes,
344                                  # currently "" and "2.6-"
345     if package_exists linux-image-${KPREFIX}${KARCH} ; then
346       echo ${KPREFIX}${KARCH}
347       return 0
348     fi
349
350   done
351 }
352
353 # install kernel packages {{{
354 kernel() {
355   if [ -n "$NOKERNEL" ] ; then
356     echo "Skipping installation of kernel packages as requested via --nokernel"
357     return 0
358   fi
359
360   $APTUPDATE
361   KVER=$(get_kernel_version)
362   if [ -n "$KVER" ] ; then
363      # note: install busybox to be able to debug initramfs
364      KERNELPACKAGES="linux-image-$KVER linux-headers-$KVER busybox firmware-linux-free"
365      # only add firmware-linux if we have non-free as a component
366      if expr "$COMPONENTS" : '.*non-free' >/dev/null ; then
367        KERNELPACKAGES="$KERNELPACKAGES firmware-linux"
368      fi
369      # shellcheck disable=SC2086
370      DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $KERNELPACKAGES
371   else
372      echo "Warning: Could not find a kernel for your system. Your system won't be able to boot itself!"
373   fi
374 }
375 # }}}
376
377 # reconfigure packages {{{
378 reconfigure() {
379   if [ -n "$RECONFIGURE" ] ; then
380      for package in $RECONFIGURE ; do
381          if dpkg --list "$package" >/dev/null 2>&1 | grep -q '^ii' ; then
382            DEBIAN_FRONTEND=$DEBIAN_FRONTEND dpkg-reconfigure "$package" || \
383            echo "Warning: $package does not exist, can not reconfigure it."
384          fi
385      done
386   fi
387 }
388 # }}}
389
390 # set password of user root {{{
391 passwords()
392 {
393   if [ -n "$NOPASSWORD" ] ; then
394     echo "Skip setting root password as requested."
395     return 0
396   fi
397
398   echo "Activating shadow passwords."
399   shadowconfig on
400
401   CHPASSWD_OPTION=
402   if chpasswd --help 2>&1 | grep -q -- '-m,' ; then
403      CHPASSWD_OPTION='-m'
404   fi
405
406   if [ -n "$ROOTPASSWORD" ] ; then
407      echo root:"$ROOTPASSWORD" | chpasswd $CHPASSWD_OPTION
408      export ROOTPASSWORD=''
409   else
410     a='1'
411     b='2'
412      echo "Setting password for user root:"
413      while [ "$a" != "$b" ] ; do
414        printf "Enter new UNIX password for user root: "
415        askpass
416        a="$resp"
417        unset resp
418        echo
419        printf "Retype new UNIX password for user root: "
420        askpass
421        b="$resp"
422        unset resp
423        echo
424        if [ "$a" != "$b" ] ; then
425          echo "Sorry, passwords do not match. Retry."
426          a='1'
427          b='2'
428        else
429          echo root:"$a" | chpasswd $CHPASSWD_OPTION
430          unset a
431          unset b
432        fi
433      done
434   fi
435 }
436 # }}}
437
438 # set up /etc/hosts {{{
439 hosts() {
440   if ! [ -f /etc/hosts ] ; then
441      cat > /etc/hosts << EOF
442 127.0.0.1       localhost
443 ::1             localhost ip6-localhost ip6-loopback
444 ff02::1         ip6-allnodes
445 ff02::2         ip6-allrouters
446 EOF
447   fi
448 }
449 # }}}
450
451 # set default locales {{{
452 default_locales() {
453   if [ -n "$DEFAULT_LOCALES" ] ; then
454     if ! [ -x /usr/sbin/update-locale ] ; then
455       echo "Warning: update-locale executable not available (no locales package installed?)"
456       echo "Ignoring request to run update-locale for $DEFAULT_LOCALES therefore"
457       return 0
458     fi
459
460     /usr/sbin/update-locale LANGUAGE="$DEFAULT_LANGUAGE" LANG="$DEFAULT_LOCALES"
461   fi
462 }
463 # }}}
464
465 # adjust timezone {{{
466 timezone() {
467   if [ -n "$TIMEZONE" ] ; then
468     echo "Adjusting /etc/localtime"
469     ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
470
471     echo "Setting /etc/timezone to $TIMEZONE"
472     printf '%s\n' "$TIMEZONE"  > /etc/timezone
473
474   fi
475 }
476 # }}}
477
478 # helper function for fstab() {{{
479 createfstab(){
480   echo "Setting up /etc/fstab"
481   cat > /etc/fstab <<EOF
482 # /etc/fstab - created by grml-debootstrap on $(date)
483 # Accessible filesystems, by reference, are maintained under '/dev/disk/'.
484 # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
485 #
486 # After editing this file, run 'systemctl daemon-reload' to update systemd
487 # units generated from this file.
488 #
489 EOF
490
491   if [ -n "$TARGET_UUID" ] ; then
492     local rootfs_mount_options=""
493
494     if [ -z "${FILESYSTEM}" ] ; then
495       FILESYSTEM="$(blkid -o value -s TYPE /dev/disk/by-uuid/"${TARGET_UUID}")"
496     fi
497
498     case "${FILESYSTEM}" in
499       # errors=remount-ro is supported only by a few file systems
500       ext*|exfat|fat|jfs|nilfs2|vfat)
501         rootfs_mount_options=",errors=remount-ro"
502         ;;
503     esac
504
505     echo "/dev/disk/by-uuid/${TARGET_UUID} /  auto    defaults${rootfs_mount_options} 0   1" >> /etc/fstab
506   else
507     echo "Warning: couldn't identify target UUID for rootfs, your /etc/fstab might be incomplete."
508   fi
509
510 if [ -n "$EFI" ] ; then
511   # shellcheck disable=SC2086
512   echo "UUID=$(blkid -o value -s UUID $EFI)  /boot/efi       vfat    umask=0077      0       1" >> /etc/fstab
513 fi
514
515 cat >> /etc/fstab << EOF
516 proc           /proc        proc    defaults                      0   0
517 /dev/cdrom     /mnt/cdrom0  iso9660 ro,user,noauto                0   0
518 # some other examples:
519 # /dev/sda2       none         swap    sw,pri=0             0   0
520 # /dev/hda1       /Grml        ext3    dev,suid,user,noauto 0  2
521 # //1.2.3.4/pub   /smb/pub     cifs    user,noauto,uid=grml,gid=grml 0 0
522 # linux:/pub      /beer        nfs     defaults             0  0
523 # tmpfs           /tmp         tmpfs   size=300M            0  0
524 # /dev/sda5       none         swap    sw                   0  0
525 EOF
526 }
527 # }}}
528
529 # generate /etc/fstab {{{
530 fstab() {
531   # set up /etc/fstab if file is not present (cdebootstrap)
532   if [ ! -f /etc/fstab  ] ; then
533      createfstab
534   fi
535
536   # set up /etc/fstab if file is UNCONFIGURED (debootstrap)
537   if grep -q UNCONFIGURED /etc/fstab ; then
538      createfstab
539   fi
540 }
541 # }}}
542
543 # ensure we have according filesystem tools available {{{
544 install_fs_tools() {
545   local pkg=""
546
547   # note: this is supposed to be coming either via command lines'
548   # $_opt_filesystem or via createfstab()
549   case "${FILESYSTEM}" in
550     jfs)
551       pkg="jfsutils"
552       ;;
553     xfs)
554       pkg="xfsprogs"
555       ;;
556   esac
557
558   if [ -n "${pkg:-}" ] && ! dpkg --list "${pkg}" 2>/dev/null | grep -q '^ii' ; then
559     echo "Filesystem package ${pkg} not present, installing now"
560     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL "${pkg}"
561   fi
562 }
563 # }}}
564
565 # set up hostname {{{
566 hostname() {
567   if [ -n "$HOSTNAME" ] ; then
568      echo "Setting hostname to ${HOSTNAME}."
569      echo "$HOSTNAME" > /etc/hostname
570
571      # adjust postfix configuration
572      if [ -r /etc/postfix/main.cf ] ; then
573         # adjust hostname related options:
574         sed -i "s/grml/$HOSTNAME/g" /etc/postfix/main.cf
575
576         # listen on loopback interface only:
577         sed -i "s/^inet_interfaces = .*/inet_interfaces = loopback-only/" /etc/postfix/main.cf
578         grep -q inet_interfaces /etc/postfix/main.cf || echo 'inet_interfaces = loopback-only' >> /etc/postfix/main.cf
579      fi
580      if [ -r /etc/mailname ] ; then
581         # adjust /etc/mailname
582         local etc_mail_domain
583         etc_mail_domain=$(/bin/dnsdomainname 2>/dev/null || echo localdomain)
584         case "$HOSTNAME" in
585           *.*)
586             local mailname="$HOSTNAME"
587             ;;
588           *)
589             local mailname="${HOSTNAME}.${etc_mail_domain}"
590             ;;
591         esac
592         echo "Setting mailname to ${mailname}"
593         echo "$mailname" > /etc/mailname
594      fi
595   fi
596 }
597 # }}}
598
599 # generate initrd/initramfs {{{
600 initrd() {
601   # assume the first available kernel as our main kernel
602   # shellcheck disable=SC2012
603   KERNELIMG=$(ls -1 /boot/vmlinuz-* 2>/dev/null | head -1)
604   if [ -z "$KERNELIMG" ] ; then
605      echo 'No kernel image found, skipping initrd stuff.'>&2
606      return
607   fi
608
609   KERNELVER=${KERNELIMG#/boot/vmlinuz-}
610
611   # generate initrd
612   if [ -n "$INITRD" ] ; then
613      echo "Generating initrd."
614      if [ "$INITRD_GENERATOR" = 'dracut' ] ; then
615          DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL dracut
616          dracut --no-hostonly --kver "$KERNELVER" --fstab --add-fstab /etc/fstab --force --reproducible $INITRD_GENERATOR_OPTS
617      else
618          update-initramfs -c -t -k "$KERNELVER" $INITRD_GENERATOR_OPTS
619      fi
620   fi
621 }
622 # }}}
623
624 efi_setup() {
625   if [ -z "$EFI" ] ; then
626     return 0
627   fi
628
629   if ! dpkg --list efibootmgr 2>/dev/null | grep -q '^ii' ; then
630     echo "Notice: efi option set but no efibootmgr package, installing it therefore."
631     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL efibootmgr
632   fi
633
634   mkdir -p /boot/efi
635   echo "Mounting $EFI on /boot/efi"
636   mount "$EFI" /boot/efi || return 1
637
638   # if efivarfs kernel module is loaded, but efivars isn't,
639   # then we need to mount efivarfs for efibootmgr usage
640   if ! ls /sys/firmware/efi/efivars/* &>/dev/null ; then
641     echo "Mounting efivarfs on /sys/firmware/efi/efivars"
642     mount -t efivarfs efivarfs /sys/firmware/efi/efivars
643   fi
644
645   echo "Invoking efibootmgr"
646   efibootmgr || return 1
647 }
648
649 # grub configuration/installation {{{
650
651 # helper function to get relevant /dev/disk/by-id/* entries,
652 # based on GRUB's postinst script
653 available_ids() {
654   local path ids
655
656   [ -d /dev/disk/by-id ] || return
657   ids="$(
658     for path in /dev/disk/by-id/*; do
659       [ -e "${path}" ] || continue
660       printf '%s %s\n' "${path}" "$(readlink -f "${path}")"
661     done | sort -k2 -s -u | cut -d' ' -f1
662   )"
663   echo "${ids}"
664 }
665
666 # helper function to report corresponding /dev/disk/by-id/… for a given device name,
667 # based on GRUB's postinst script
668 device_to_id() {
669   local id
670
671   for id in $(available_ids); do
672     if [ "$(readlink -f "${id}")" = "$(readlink -f "$1")" ]; then
673       echo "${id}"
674       return 0
675     fi
676   done
677
678   # Fall back to the plain device name if there's no by-id link for it.
679   if [ -e "$1" ]; then
680     echo "$1"
681     return 0
682   fi
683   return 1
684 }
685
686 grub_install() {
687
688   if [ -z "$GRUB" ] ; then
689     echo "Notice: \$GRUB not defined, will not install grub inside chroot at this stage."
690     return 0
691   fi
692
693   efi_setup || return 1
694
695   if [ -n "$EFI" ] ; then
696     GRUB_PACKAGE=grub-efi-amd64
697   else
698     GRUB_PACKAGE=grub-pc
699   fi
700
701   # make sure this is pre-defined so we have sane settings for automated
702   # upgrades, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=711019
703   local grub_device
704   grub_device=$(device_to_id "${GRUB}")
705   if [ -z "${grub_device:-}" ] ; then
706      echo "Warning: Could not identify /dev/disk/by-id/... for '${GRUB}', falling back to '${GRUB}'"
707      grub_device="${GRUB}"
708   fi
709
710   echo "Setting ${GRUB_PACKAGE} debconf configuration for install device to $GRUB"
711   echo "${GRUB_PACKAGE} ${GRUB_PACKAGE}/install_devices multiselect ${grub_device}" | debconf-set-selections
712
713   if ! dpkg --list ${GRUB_PACKAGE} 2>/dev/null | grep -q '^ii' ; then
714     echo "Notice: grub option set but no ${GRUB_PACKAGE} package, installing it therefore."
715     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL ${GRUB_PACKAGE}
716   fi
717
718   if ! [ -x "$(command -v grub-install)" ] ; then
719      echo "Error: grub-install not available. (Error while installing grub package?)" >&2
720      return 1
721   fi
722
723   if [ -n "$SELECTED_PARTITIONS" ] ; then # using sw-raid
724      for device in $SELECTED_PARTITIONS ; do
725         GRUB="${device%%[0-9]}"
726         echo "Installing grub on ${GRUB}:"
727         if ! grub-install --no-floppy "$GRUB" ; then
728           echo "Error: failed to execute 'grub-install --no-floppy $GRUB'." >&2
729           exit 1
730         fi
731
732      done
733      rm -f /boot/grub/device.map
734   else
735      echo "Installing grub on ${GRUB}:"
736      case "$RELEASE" in
737        lenny|squeeze|wheezy)
738          local grub_dev
739          grub_dev="$(readlink -f "${GRUB}")"
740          if ! grub-install --no-floppy "${grub_dev}" ; then
741            echo "Error: failed to execute 'grub-install --no-floppy ${grub_dev}'." >&2
742            exit 1
743          fi
744          rm -f /boot/grub/device.map
745          ;;
746        *)
747          echo "(hd0) ${GRUB}" > /boot/grub/device.map
748          if ! grub-install "(hd0)" ; then
749            echo "Error: failed to execute 'grub-install (hd0)'." >&2
750            exit 1
751          fi
752          rm /boot/grub/device.map
753          ;;
754      esac
755   fi
756
757   echo "Adjusting grub configuration for use on ${GRUB}."
758
759   # finally install grub
760   if [ -x /usr/sbin/update-grub ] ; then
761      UPDATEGRUB='/usr/sbin/update-grub'
762   elif [ -x /sbin/update-grub ] ; then
763      UPDATEGRUB='/sbin/update-grub'
764   else
765     echo "Error: update-grub not available, can not execute it." >&2
766     return 1
767   fi
768
769   if [ -n "${BOOT_APPEND}" ] ; then
770     echo "Adding BOOT_APPEND configuration ['${BOOT_APPEND}'] to /etc/default/grub."
771     sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" /etc/default/grub
772   fi
773
774   mountpoint /boot/efi &>/dev/null && umount /boot/efi
775
776   $UPDATEGRUB
777 }
778 # }}}
779
780 # execute all scripts present in /etc/debootstrap/chroot-scripts/ {{{
781 custom_scripts() {
782   [ -d /etc/debootstrap/chroot-scripts/ ] || return 0
783
784   for script in /etc/debootstrap/chroot-scripts/* ; do
785       echo "Executing script $script"
786       $script && echo "done" || echo "failed"
787   done
788 }
789 # }}}
790
791 # make sure we don't have any running processes left {{{
792 services() {
793   for service in ssh mdadm mdadm-raid ; do
794     if [ -x /etc/init.d/"$service" ] ; then
795        /etc/init.d/"$service" stop || true
796     fi
797   done
798 }
799 # }}}
800
801 # unmount /proc and make sure nothing is left {{{
802 finalize() {
803   # make sure we don't leave any sensible data
804   rm -f /etc/debootstrap/variables
805
806   [ -n "$POLICYRCD" ] && rm -f /usr/sbin/policy-rc.d
807
808   umount /sys/firmware/efi/efivars &>/dev/null || true
809
810   umount /sys >/dev/null 2>/dev/null || true
811   umount /proc >/dev/null 2>/dev/null || true
812 }
813 # }}}
814
815 # signal handler {{{
816 signal_handler() {
817   finalize
818   [ -n "$1" ] && EXIT="$1" || EXIT="1"
819   exit "$EXIT"
820 }
821 # }}}
822
823 # set signal handler {{{
824 trap signal_handler HUP INT QUIT TERM
825 # }}}
826
827 # execute the functions {{{
828
829  # always execute install_policy_rcd
830  install_policy_rcd
831
832  for i in chrootmirror grmlrepos backportrepos kernelimg_conf \
833      kernel packages extrapackages reconfigure hosts \
834      default_locales timezone fstab install_fs_tools hostname \
835      initrd grub_install passwords \
836      custom_scripts upgrade_system remove_apt_cache services \
837      remove_chrootmirror; do
838      if stage $i ; then
839        $i && stage $i 'done' || exit 1
840      fi
841   done
842   # always execute the finalize stage:
843   finalize
844 # }}}
845
846 # finally exit the chroot {{{
847   echo "Finished chroot installation, exiting."
848   exit 0
849 # }}}
850
851 ## END OF FILE #################################################################
852 # vim: ai tw=80 expandtab foldmethod=marker