Use bookworm as new default release + update release list
[grml-debootstrap.git] / grml-debootstrap
1 #!/bin/bash
2 # Filename:      grml-debootstrap
3 # Purpose:       wrapper around debootstrap for installing plain Debian via Grml
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
9 # error_handler {{{
10 [ -n "$REPORT_TRAP_ERR" ] || REPORT_TRAP_ERR='no'
11 [ -n "$FAIL_TRAP_ERR" ] || FAIL_TRAP_ERR='no'
12
13 error_handler() {
14    last_exit_code="$?"
15    last_bash_command="$BASH_COMMAND"
16    if [ "$REPORT_TRAP_ERR" = "yes" ]; then
17       echo "Unexpected non-zero exit code $last_exit_code in ${BASH_SOURCE[*]} at line ${BASH_LINENO[*]} detected!
18 last bash command: $last_bash_command"
19    fi
20    if [ ! "$FAIL_TRAP_ERR" = "yes" ]; then
21       return
22    fi
23    ## Check if "bailout" function is available.
24    ## This is not the case in chroot-script.
25    if command -v bailout >/dev/null 2>&1; then
26       bailout 1
27    else
28       echo 'FAIL_TRAP_ERR is set to "yes", exit 1.'
29       exit 1
30    fi
31 }
32
33 if [ "$REPORT_TRAP_ERR" = "yes" ] || [ "$FAIL_TRAP_ERR" = "yes" ]; then
34    set -E
35    set -o pipefail
36    trap "error_handler" ERR
37    export -f "error_handler"
38 fi
39 # }}}
40
41 # variables {{{
42 PN="$(basename "$0")"
43 if [[ -d "$(dirname "$(command -v "$0")")"/.git ]]; then
44   VERSION="$(git --git-dir $(dirname "$(command -v "$0")")/.git describe | sed 's|^v||')"
45 else
46   VERSION="$(dpkg-query --show --showformat='${Version}' "$PN")"
47 fi
48 VERSION="${VERSION:-unknown}"
49 MNTPOINT="/mnt/debootstrap.$$"
50
51 # defaults
52 [ -n "$CHROOT_SCRIPTS" ] || CHROOT_SCRIPTS='yes'
53 [ -n "$CONFFILES" ] || CONFFILES='/etc/debootstrap'
54 [ -n "$DEBCONF" ] || DEBCONF='yes'
55 [ -n "$DEBIAN_FRONTEND" ] || DEBIAN_FRONTEND='noninteractive'
56 [ -n "$DEBOOTSTRAP" ] || DEBOOTSTRAP='debootstrap'
57 [ -n "$DEFAULT_LANGUAGE" ] || DEFAULT_LANGUAGE='en_US:en'
58 [ -n "$DEFAULT_LOCALES" ] || DEFAULT_LOCALES='en_US.UTF-8'
59 [ -n "$DISK_IDENTIFIER" ] || DISK_IDENTIFIER='26ada0c0-1165-4098-884d-aafd2220c2c6'
60 [ -n "$EXTRAPACKAGES" ] || EXTRAPACKAGES='yes'
61 [ -n "$FALLBACK_MIRROR" ] || FALLBACK_MIRROR='http://deb.debian.org/debian'
62 [ -n "$FIXED_DISK_IDENTIFIERS" ] || FIXED_DISK_IDENTIFIERS="no"
63 [ -n "$FORCE" ] || FORCE=''
64 [ -n "$HOSTNAME" ] || HOSTNAME='grml'
65 [ -n "$INITRD" ] || INITRD='yes'
66 [ -n "$INITRD_GENERATOR" ] || INITRD_GENERATOR='initramfs-tools'
67 [ -n "$INITRD_GENERATOR_OPTS" ] || INITRD_GENERATOR_OPTS=''
68 [ -n "$INSTALL_NOTES" ] || INSTALL_NOTES='/etc/debootstrap/install_notes'
69 [ -n "$LOCALES" ] || LOCALES='yes'
70 [ -n "$MIRROR" ] || MIRROR="$FALLBACK_MIRROR"
71 [ -n "$MKFS" ] || MKFS='mkfs.ext4'
72 [ -n "$MKFS_OPTS" ] || MKFS_OPTS=''
73 [ -n "$PACKAGES" ] || PACKAGES='yes'
74 [ -n "$POST_SCRIPTS" ] || POST_SCRIPTS='yes'
75 [ -n "$PRE_SCRIPTS" ] || PRE_SCRIPTS='yes'
76 [ -n "$RECONFIGURE" ] || RECONFIGURE='console-data'
77 [ -n "$RELEASE" ] || RELEASE='bookworm'
78 [ -n "$RM_APTCACHE" ] || RM_APTCACHE='yes'
79 [ -n "$SCRIPTS" ] || SCRIPTS='no' # deprecated, replaced by POST_SCRIPTS
80 [ -n "$SECURE" ] || SECURE='yes'
81 [ -n "$TIMEZONE" ] || TIMEZONE='Europe/Vienna'
82 [ -n "$TUNE2FS" ] || TUNE2FS='tune2fs -c0 -i0'
83 [ -n "$UPGRADE_SYSTEM" ] || UPGRADE_SYSTEM='yes'
84 [ -n "$VMSIZE" ] || VMSIZE="2G"
85 [ -n "$GRUB_INSTALL" ] || GRUB_INSTALL='yes'
86
87 # inside the chroot system locales might not be available, so use minimum:
88 export LANG=C
89 export LC_ALL=C
90 export LANGUAGE=C
91
92 # make sure interactive mode is only executed when
93 # using an empty configuration file or option --interactive
94 INTERACTIVE=''
95 # }}}
96
97 # help text {{{
98 usage() {
99   echo "$PN - wrapper around debootstrap for installing Debian
100
101 Usage: $PN [options]
102
103 Bootstrap options:
104
105   -m, --mirror <URL>     Mirror which should be used for apt-get/aptitude.
106   -i, --iso <mnt>        Mountpoint where a Debian ISO is mounted to, for use
107                          instead of fetching packages from a mirror.
108   -r, --release <name>   Release of new Debian system (default: bullseye).
109   -t, --target <target>  Target partition (/dev/...) or directory where the
110                          system should be installed to.
111   -p, --mntpoint <mnt>   Mountpoint used for mounting the target system,
112                          has no effect if -t is given and represents a directory.
113       --debopt <params>  Extra parameters passed to the debootstrap command.
114       --interactive      Use interactive mode (frontend).
115       --nodebootstrap    Skip debootstrap, only do configuration to the target.
116       --grub <device>    Target for grub installation. Usage example: /dev/sda
117       --efi <device>     Target for EFI installation. Usage example: /dev/sda1
118       --arch <arch>      Set target architecture, use for installing i386 on amd64.
119       --filesystem <fs>  Filesystem that should be used when target is a partition
120                          or Virtual Machine (see --vmfile).
121       --force            Do not prompt for user acknowledgement.
122
123 Options for Virtual Machine deployment:
124
125       --vm               Set up a Virtual Machine on an existing block device
126                          instead of plainly installing to a partition or
127                          directory. Needs to be combined with --target.
128                          Example: --vm --target /dev/mapper/your-vm-disk
129       --vmfile           Like --vm, but install into a regular file (created by
130                          'qemu-img create -f raw ...') instead.
131                          Example: --vmfile --target /mnt/sda1/qemu.img
132       --vmsize <size>    Use specified size for size of VM file (default: 2G).
133                          Syntax as supported by qemu-img, like: --vmsize 3G
134
135 Configuration options:
136
137   -c, --config <file>      Use specified configuration file, defaults to
138                              /etc/debootstrap/config
139   -d, --confdir <path>     Place of config files for debootstrap, defaults
140                              to /etc/debootstrap
141       --packages <file>    Install packages defined in specified list file
142                              instead of using /etc/debootstrap/packages.
143       --nopackages         Skip installation of packages defined in
144                              /etc/debootstrap/packages
145       --nokernel           Skip installation of default kernel images.
146       --nointerfaces       Do not copy /etc/network/interfaces from host system
147                            to target system.
148                            (This option is automatically enabled when using --vmfile.)
149       --defaultinterfaces  Install a default /etc/network/interfaces file (enabling
150                            DHCP for eth0) instead of taking over config from host system.
151       --debconf <file>     Pre-seed packages using specified pre-seed db file.
152       --grmlrepos          Enable Grml's Debian repository (deb.grml.org).
153       --backportrepos      Enable Debian's backports repository (backports.debian.org).
154       --keep_src_list      Do not overwrite user provided apt sources.list.
155       --contrib            Enable 'contrib' in COMPONENTS (defaults to 'main' only).
156       --non-free           Enable non-free / non-free-firmware in COMPONENTS (defaults to 'main' only).
157       --hostname <name>    Hostname of Debian system.
158       --nopassword         Do not prompt for the root password.
159       --password <pwd>     Use specified password as password for user root.
160       --sshcopyauth        Use ${HOME}/.ssh/authorized_keys to authorise root login on the target system.
161       --sshcopyid          Use locally available public keys to authorise root login on the target system.
162       --bootappend <line>  Add specified appendline to kernel whilst booting.
163       --chroot-scripts <d> Execute chroot scripts from specified directory.
164       --pre-scripts <dir>  Execute scripts from specified directory (before chroot-scripts).
165       --scripts <dir>      Execute scripts from specified directory (after chroot-scripts).
166       --remove-configs     Delete grml-debootstrap configuration files from installed system.
167
168 Other options:
169
170   -v, --verbose            Increase verbosity.
171       --debug              Execute in very verbose way.
172   -h, --help               Print this usage information and exit.
173   -V, --version            Show summary of options and exit.
174
175 Usage examples can be found in the grml-debootstrap manpage.
176 Send bugreports to the grml-team: bugs (at) grml.org || https://grml.org/bugs/
177 "
178 }
179
180 if [ "$1" = '-h' ] || [ "$1" = '-help' ] || [ "$1" = "--help" ] ; then
181    usage
182    echo 'Please notice that this script requires root permissions!'
183    exit 0
184 fi
185 # }}}
186
187 # early helper functions {{{
188 # skip colors when running within a dumb terminal
189 if [ "${TERM}" = "dumb" ] ; then
190   GOOD=
191   BAD=
192   WARN=
193   NORMAL=
194 else
195   GOOD='\e[32;01m'
196   BAD='\e[31;01m'
197   WARN='\e[33;01m'
198   NORMAL='\e[0m'
199 fi
200
201 einfo() {
202   einfon "$1\\n"
203   return 0
204 }
205
206 einfon() {
207   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
208   printf " %s*%s $*" "${GOOD}" "${NORMAL}"
209   LAST_E_CMD=einfon
210   return 0
211 }
212
213 ewarn() {
214   printf " %s*%s $*\\n" "${WARN}" "${NORMAL}"
215   return 0
216 }
217
218 eerror() {
219   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
220   printf " %s*%s $*\\n" "${BAD}" "${NORMAL}" >&2
221   LAST_E_CMD=eerror
222   return 0
223 }
224
225 eend() {
226   local retval="${1:-0}"
227   shift
228   if [ "$retval" -gt 0 ]; then
229     printf " %s-> Failed (rc=%s)%s\\n" "${BAD}" "${retval}" "${NORMAL}"
230   fi
231   return "$retval"
232 }
233
234 check4root(){
235   if [ "$(id -u 2>/dev/null)" != 0 ] ; then
236     echo 1>&2 "Error: please run this script with uid 0 (root)." ; return 1
237   fi
238 }
239
240 check4progs(){
241   local RC=''
242   for arg in "$@" ; do
243     command -v "$arg" >/dev/null 2>&1 || RC="$arg"
244   done
245   if [ -n "$RC" ] ; then
246      echo "$RC not installed"
247      return 1
248   fi
249 }
250 # }}}
251
252 # helper functions {{{
253 cleanup() {
254   if [ -n "$CHROOT_VARIABLES" ] ; then
255     einfo "Removing ${CHROOT_VARIABLES}" ; rm "$CHROOT_VARIABLES" ; eend $?
256   fi
257
258   if [ -n "$STAGES" ] ; then
259     einfo "Removing ${STAGES}" ; rmdir "$STAGES" ; eend $?
260   fi
261
262   # Remove temporary mountpoint again
263   if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
264     rmdir "$MNTPOINT" 2>/dev/null
265   fi
266
267   # make sure $TARGET is not mounted when exiting grml-debootstrap
268   if [ -n "$MNTPOINT" ] ; then
269     if grep -q "$MNTPOINT" /proc/mounts ; then
270       # make sure nothing is left inside chroot so we can unmount it
271       for service in ssh mdadm ; do
272         if [ -x "${MNTPOINT}/etc/init.d/${service}" ] ; then
273           chroot "$MNTPOINT" "/etc/init.d/${service}" stop
274         fi
275       done
276
277       [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount -a >/dev/null 2>&1
278
279       # ugly, but make sure we really don't leave anything (/proc /proc and
280       # /dev /dev are intended, trying to work around timing issues, see #657023)
281       for ARG in /run/udev /sys /proc /proc /dev/pts /dev/pts /dev /dev ; do
282         [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount $ARG >/dev/null 2>&1
283         umount "$MNTPOINT"/$ARG >/dev/null 2>&1
284       done
285
286       if [ -n "$ISODIR" ] ; then
287         [ -d "$MNTPOINT/$ISODIR" ] && umount "$MNTPOINT/$ISODIR" >/dev/null 2>&1
288       fi
289
290       if [ -n "$DIRECTORY" ] ; then
291         einfo "Not unmounting $MNTPOINT as you requested me to install into a directory of your own choice." ; eend 0
292       else
293         einfo "Unmounting $MNTPOINT"
294         umount "$MNTPOINT"
295         eend $?
296       fi
297
298       if [ -n "$STAGES" ] ; then
299         echo -n "Removing stages directory ${STAGES}: "
300         rm -rf "$STAGES" && echo 'done'
301       fi
302
303       # remove directory only if we used the default with process id inside the name
304       if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
305         einfo "Removing directory ${MNTPOINT}"
306         rmdir "$MNTPOINT"
307         eend $?
308       fi
309     fi
310   fi
311
312   if [ -n "${ORIG_TARGET}" ] ; then
313     einfo "Removing loopback mount of file ${ORIG_TARGET}."
314     kpartx -d "${ORIG_TARGET}"
315     # Workaround for a bug in kpartx which doesn't clean up properly,
316     # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
317     if dmsetup ls | grep -q "^${LOOP_PART} "; then
318       kpartx -d "/dev/${LOOP_DISK}" >/dev/null
319     fi
320     eend $?
321   fi
322 }
323
324 # we want to exit smoothly and clean:
325 bailout(){
326
327   cleanup
328
329   [ -n "$1" ] && EXIT="$1" || EXIT="1"
330   [ -n "$2" ] && einfo "Notice: remove $STAGES/$2 to reexecute the stage"
331
332   exit "$EXIT"
333 }
334 trap bailout HUP INT QUIT TERM
335
336 # we want to execute all the functions only once, simple check for it:
337 stage() {
338   if [ -n "$2" ] ; then
339      echo "$2" > "${STAGES}/${1}"
340      return 0
341   elif grep -q 'done' "${STAGES}/${1}" 2>/dev/null ; then
342      ewarn "Notice: stage $1 has been executed already, skipping execution therefore." ; eend 0
343      ewarn "  To reexecute it clean up the according directory inside $STAGES" ; eend 0
344      return 1
345   fi
346 }
347 # }}}
348
349 # source main configuration file {{{
350 if [ -r /etc/debootstrap/config ] ; then
351   # shellcheck disable=SC1091
352   . /etc/debootstrap/config
353 fi
354 # }}}
355
356 # cmdline handling {{{
357 CMDLINE_OPTS=mirror:,iso:,release:,target:,mntpoint:,debopt:,defaultinterfaces,interactive,nodebootstrap,nointerfaces,nokernel,nopackages,filesystem:,config:,confdir:,packages:,chroot-scripts:,scripts:,post-scripts:,pre-scripts:,debconf:,vm,vmfile,vmsize:,keep_src_list,hostname:,password:,nopassword,grmlrepos,backportrepos,bootappend:,grub:,efi:,arch:,insecure,verbose,help,version,force,debug,contrib,non-free,remove-configs,sshcopyid,sshcopyauth
358
359 _opt_temp=$(getopt --name grml-debootstrap -o +m:i:r:t:p:c:d:vhV --long \
360   $CMDLINE_OPTS -- "$@")
361
362 if [ $? != 0 ]; then
363   eerror "Try 'grml-debootstrap --help' for more information."; eend 1; exit 1
364 fi
365 eval set -- "$_opt_temp"
366
367 while :; do
368   case "$1" in
369
370   # == Bootstrap options
371   --mirror|-m)         # Mirror which should be used for apt-get/aptitude
372     shift; _opt_mirror="$1"
373     ;;
374   --iso|-i)            # Mountpoint where a Debian ISO is mounted to
375     shift; _opt_iso="$1"
376     ;;
377   --release|-r)        # Release of new Debian system
378     shift; _opt_release="$1"
379     ;;
380   --target|-t)         # Target partition (/dev/...) or directory
381     shift; _opt_target="$1"
382     ;;
383   --vm)                # Virtual machine image (no file)
384     _opt_vm="T"
385     ;;
386   --vmfile)            # Virtual machine file
387     _opt_vmfile="T"
388     ;;
389   --vmsize)            # size of Virtual machine file
390     shift; _opt_vmsize="$1"
391     ;;
392   --mntpoint|-p)       # Mountpoint used for mounting the target system
393     shift; _opt_mntpoint="$1"
394     ;;
395   --debopt)            # Extra parameters passed to the debootstrap command
396     shift; _opt_debopt="$1"
397     ;;
398   --filesystem)        # Filesystem that should be used
399     shift; _opt_filesystem="$1" ; FILESYSTEM="${_opt_filesystem}"
400     ;;
401   --interactive)       # Use interactive mode (frontend)
402     _opt_interactive=T
403     ;;
404   --nodebootstrap)     # Skip debootstrap, only do configuration to the target
405     _opt_nodebootstrap=T
406     ;;
407   --nopackages)        # Skip installation of packages defined in /etc/debootstrap/packages
408     _opt_nopackages=T
409     ;;
410   --arch)              # Target architecutre
411     shift; _opt_arch="$1"
412     ;;
413   # just for backwards compatibility
414   --insecure)
415     _opt_insecure=T
416     ;;
417   #
418
419   # == Configuration options
420   --config|-c)         # Use specified configuration file, defaults to /etc/debootstrap
421     shift; _opt_config="$1"
422     ;;
423   --confdir|-d)        # Place of config files for debootstrap, defaults to /etc/debootstrap
424     shift; _opt_confdir="$1"
425     ;;
426   --packages)          # Install packages defined in specified file
427     shift; _opt_packages="$1"
428     _opt_packages_set=T
429     ;;
430   --debconf)           # Pre-seed packages using specified file
431     shift; _opt_debconf="$1"
432     _opt_debconf_set=T
433     ;;
434   --pre-scripts)       # Execute scripts from specified directory (before chroot-scripts).
435     shift; _opt_pre_scripts="$1"
436     _opt_pre_scripts_set=T
437     ;;
438   --scripts)           # Execute scripts from specified directory [NOTE: deprecated, replaced via --post-scripts]
439     shift; _opt_scripts="$1"
440     _opt_scripts_set=T
441     ;;
442   --post-scripts)       # Execute scripts from specified directory
443     shift; _opt_post_scripts="$1"
444     _opt_post_scripts_set=T
445     ;;
446   --chroot-scripts)   # Execute chroot scripts from specified directory
447     shift; _opt_chroot_scripts="$1"
448     _opt_chroot_scripts_set=T
449     ;;
450   --keep_src_list)     # Do not overwrite user provided apt sources.list
451     _opt_keep_src_list=T
452     ;;
453   --hostname)          # Hostname of Debian system
454     shift; _opt_hostname="$1"
455     ;;
456   --password)          # Use specified password as password for user root
457     shift; _opt_password="$1"
458     ;;
459   --defaultinterfaces) # Install default /etc/network/interfaces
460     _opt_defaultinterfaces=T
461     ;;
462   --nointerfaces)      # Skip installation of /etc/network/interfaces
463     _opt_nointerfaces=T
464     ;;
465   --nokernel)          # Skip installation of default kernel images
466     _opt_nokernel=T
467     ;;
468   --nopassword)        # Skip password dialog
469     _opt_nopassword=T
470     ;;
471   --sshcopyid)         # Use locally available public keys to authorise root login on the target system
472     _opt_sshcopyid=T
473     ;;
474   --sshcopyauth)       # Use .ssh/authorized_keys to authorise root login on the target system
475     _opt_sshcopyauth=T
476     ;;
477   --grmlrepos)         # Enable Grml repository
478     _opt_grmlrepos=T
479     ;;
480   --backportrepos)     # Enable Debian backports repository
481     _opt_backportrepos=T
482     ;;
483   --bootappend)        # Add specified appendline to kernel whilst booting
484     shift; _opt_bootappend="$1"
485     ;;
486   --grub)              # Target for grub installation. Use grub syntax for specifying
487     shift; _opt_grub="$1"
488     ;;
489   --efi)               # Target for EFI boot installation
490     shift; _opt_efi="$1"
491     ;;
492   --contrib)           # Add 'contrib' to list of components
493     _opt_contrib=T
494     ;;
495   --non-free)          # Add 'non-free' to list of components
496     _opt_non_free=T
497     ;;
498   --remove-configs)    # Drop config files from installed system
499     _opt_remove_configs=T
500     ;;
501
502   # == Other options
503   --verbose|-v)        # Increase verbosity
504     if [ "$_opt_verbose" ]; then
505       _opt_verbose=$( _opt_verbose + 1 )
506     else
507       _opt_verbose=1
508     fi
509     ;;
510   --debug)             # Execute in debug mode
511     _opt_debug=T
512     ;;
513   --help|-h)           # Print usage information and exit
514     _opt_help=T
515     ;;
516   --version|-V)        # Show version information and exit
517     _opt_version=T
518     ;;
519   --force)             # Do not prompt for user input
520     _opt_force=T
521     ;;
522   --)
523     shift; break
524     ;;
525   *)
526     eerror "Internal getopt error!"; eend 1 ; exit 1
527     ;;
528   esac
529   shift
530 done
531
532 # == business-logic of command line parameter-processing
533
534 # source configuration file in <confdir> if supplied. {{{
535 [ "$_opt_confdir" ] && {
536   CONFFILES=$_opt_confdir
537   einfo "Using config files under $CONFFILES/."
538   if ! [ -r "$CONFFILES/config" ] ; then
539     eerror "Error: config file $CONFFILES/config not found."; eend 1; bailout 1
540   fi
541   # shellcheck disable=SC1091 source=config
542   if ! . "$CONFFILES/config" ; then
543     eerror "Error reading config file $CONFFILES/config" ; eend 1 ; bailout 1
544   fi
545   # restore the command line parameter value
546   CONFFILES=$_opt_confdir
547 }
548 # }}}
549
550 [ "$_opt_mirror" ]              && MIRROR=$_opt_mirror
551 [ "$_opt_iso" ]                 && ISO=$_opt_iso
552 [ "$_opt_release" ]             && RELEASE=$_opt_release
553 [ "$_opt_target" ]              && TARGET=$_opt_target
554 [ "$_opt_vm" ]                  && VIRTUAL=1
555 [ "$_opt_vmfile" ]              && VMFILE=1 && VIRTUAL=1
556 [ "$_opt_vmsize" ]              && VMSIZE=$_opt_vmsize
557 [ "$_opt_mntpoint" ]            && MNTPOINT=$_opt_mntpoint
558 [ "$_opt_debopt" ]              && DEBOOTSTRAP_OPT=$_opt_debopt
559 [ "$_opt_interactive" ]         && INTERACTIVE=1
560 [ "$_opt_config" ]              && CONFIGFILE=$_opt_config
561 [ "$_opt_filesystem" ]          && MKFS="mkfs.$_opt_filesystem"
562 [ "$_opt_packages_set" ]        && PACKAGES='yes'
563 [ "$_opt_nopackages" ]          && PACKAGES=''
564 [ "$_opt_debconf_set" ]         && DEBCONF='yes'
565 [ "$_opt_post_scripts_set" ]    && POST_SCRIPTS='yes'
566 [ "$_opt_pre_scripts_set" ]     && PRE_SCRIPTS='yes'
567 [ "$_opt_chroot_scripts_set" ]  && CHROOT_SCRIPTS='yes'
568 [ "$_opt_keep_src_list" ]       && KEEP_SRC_LIST='yes'
569 [ "$_opt_grmlrepos" ]           && GRMLREPOS='yes'
570 [ "$_opt_backportrepos" ]       && BACKPORTREPOS='yes'
571 [ "$_opt_hostname" ]            && HOSTNAME=$_opt_hostname
572 [ "$_opt_password" ]            && ROOTPASSWORD=$_opt_password
573 [ "$_opt_nopassword" ]          && NOPASSWORD='yes'
574 [ "$_opt_defaultinterfaces" ]   && USE_DEFAULT_INTERFACES="true"
575 [ "$_opt_nointerfaces" ]        && NOINTERFACES="true"
576 [ "$_opt_nokernel" ]            && NOKERNEL="true"
577 [ "$_opt_sshcopyid" ]           && SSHCOPYID="true"
578 [ "$_opt_sshcopyauth" ]         && SSHCOPYAUTH="true"
579 [ "$_opt_bootappend" ]          && BOOT_APPEND=$_opt_bootappend
580 [ "$_opt_grub" ]                && GRUB=$_opt_grub
581 [ "$_opt_efi" ]                 && EFI=$_opt_efi
582 [ "$_opt_arch" ]                && ARCH=$_opt_arch
583 [ "$_opt_insecure" ]            && echo "Warning: --insecure is deprecated, continuing anyway."
584 [ "$_opt_force" ]               && FORCE=$_opt_force
585 [ "$_opt_verbose" ]             && VERBOSE="-v"
586 [ "$_opt_debug" ]               && DEBUG="true"
587 [ "$_opt_remove_configs" ]      && REMOVE_CONFIGS="yes"
588
589 # make sure main is always included
590 [ -z "$COMPONENTS" ]            && COMPONENTS="main"
591 [ "$_opt_contrib" ]             && COMPONENTS="$COMPONENTS contrib"
592
593 case "${RELEASE}" in
594   lenny|squeeze|wheezy|jessie|stretch|buster|bullseye)
595     [ "$_opt_non_free" ] && COMPONENTS="$COMPONENTS non-free"
596     ;;
597   *)
598     [ "$_opt_non_free" ] && COMPONENTS="$COMPONENTS non-free-firmware non-free"
599     ;;
600 esac
601
602 # command line option checks
603 if [ "$_opt_scripts_set" ] ; then
604   ewarn "Deprecation NOTE: --scripts option is deprecated, please switch to --post-scripts instead."
605   SCRIPTS='yes' # deprecated since grml-debootstrap >=0.71
606 fi
607
608 if [ "$_opt_grub" ] && [ "$_opt_vmfile" ] ; then
609   eerror "The --grub option is incompatible with --vmfile, please drop it from your command line."
610   eerror "The --grub option is unneeded as GRUB will be installed automatically."
611   eend 1
612   bailout 1
613 fi
614
615 if [ "${_opt_sshcopyid}" ] && [ "${_opt_sshcopyauth}" ] ; then
616   eerror "The --sshcopyid option is incompatible with --sshcopyauth, please drop either of them from your command line."
617   eend 1
618   bailout 1
619 fi
620
621 if [ -n "$ISO" ] && [[ "$DEBOOTSTRAP" =~ mmdebstrap$ ]] ; then
622   eerror "The ISO option is incompatible with usage of mmdebstrap for bootstrapping."
623   eerror "Either drop the --iso ... option or use plain debootstrap instead."
624   eend 1
625   bailout 1
626 fi
627
628 if [ "$DEBUG" = "true" ] ; then
629   set -x
630 fi
631
632 [ "$_opt_help" ] && {
633   usage ; eend 0
634   eend 0
635   exit 0
636 }
637
638 [ "$_opt_version" ] && {
639   einfo "$PN - version $VERSION"
640   einfo "Report bugs via https://github.com/grml/grml-debootstrap/ or https://grml.org/bugs/"
641   eend 0
642   exit 0
643 }
644 # }}}
645
646 # check for root permissions {{{
647 if ! check4root ; then
648    echo "For usage instructions please execute '$PN --help'."
649    bailout 1
650 fi
651 # }}}
652
653 # make sure we have what we need {{{
654 check4progs "${DEBOOTSTRAP}" || bailout 1
655
656 if [ -n "$VIRTUAL" ] ; then
657   check4progs kpartx parted qemu-img || bailout 1
658 fi
659 # }}}
660
661 # source specified configuration file {{{
662 if [ -n "$CONFIGFILE" ] ; then
663   einfo "Reading specified config file $CONFIGFILE."
664   # shellcheck disable=SC1091 source=config
665   if ! . "$CONFIGFILE" ; then
666     eerror "Error reading config file $CONFIGFILE" ; eend 1 ; bailout 1
667   fi
668 fi
669 # }}}
670
671 # backwards compatibility checks {{{
672 if [ -n "$GROOT" ] ; then
673    eerror "Error: you seem to have \$GROOT configured."
674    eerror "This variable is no longer supported, please visit the"
675    eerror "grml-debootstrap documentation for details."
676    eend 1
677    bailout 1
678 fi
679
680 if echo "$GRUB" | grep -q '^hd' ; then
681    eerror "Error: this syntax for the grub configuration variable is no longer supported."
682    eerror "Please do not use hd... any longer but /dev/sdX instead."
683    eend 1
684    bailout 1
685 fi
686 # }}}
687
688 # welcome screen {{{
689 welcome_dialog()
690 {
691    dialog --title "$PN" --yesno "Welcome to the interactive configuration of ${PN}.
692 Do you want to continue installing Debian using this frontend?" 0 0 || bailout 0
693 }
694 # }}}
695
696 # ask for target {{{
697 prompt_for_target()
698 {
699   AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
700                sed 's/*//' | \
701                grep -v 'Extended$' | \
702                gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}'; ls /dev/md[0-9]* 2>/dev/null || true);
703
704   if [ -z "$AVAILABLE_PARTITIONS" ] ; then
705      dialog --title "$PN" --trim \
706      --msgbox "Sorry, no partitions found. Please configure your
707      harddisks (see /proc/partitions) using a tool like fdisk,
708      cfdisk, gpart, gparted,..." 0 0
709      bailout 1
710   fi
711
712   PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
713                      fs="$(blkid -s TYPE -o value "$i" 2>/dev/null)"
714                      [ -n "$fs" ] || fs='[no_filesystem_yet]'
715                      echo "$i" "$fs"
716                      unset fs
717                    done)
718
719   # shellcheck disable=SC2086
720   TARGET=$(dialog --title "$PN" --single-quoted --stdout \
721          --menu "Please select the target partition:" 0 0 0 \
722          $PARTITION_LIST)
723   [ $? -eq 0 ] || bailout 1
724 }
725 # }}}
726
727 # ask for bootmanager {{{
728 prompt_for_bootmanager()
729 {
730   ADDITIONAL_PARAMS=""
731
732   if echo "$TARGET" | grep -q "/dev/md" ; then
733      MBRPART="all disks of Software RAID $TARGET"
734   else
735      # figure out whole disk device
736      found=
737      for device in /dev/disk/by-id/*
738      do
739         [ "$(readlink -f "$device")" = "${TARGET}" ] || continue
740         found=1
741         break
742      done
743      # shellcheck disable=SC2001
744      [ -n "$found" ] && MBRDISK=$(echo "${device}" | sed -e 's/-part[0-9][0-9]*$//')
745      if [ -e "$MBRDISK" ]; then
746         MBRDISK=$(readlink -f "$MBRDISK")
747      else
748         # fall back to old behaviour
749         # shellcheck disable=SC2001
750         MBRDISK=$(echo "${TARGET}" | sed -e 's/[0-9][0-9]*$//')
751      fi
752
753      MBRPART="MBR of $MBRDISK"
754   fi
755
756   for device in cciss/c0d0 sda hda; do
757     if [ "/dev/$device" != "${MBRDISK}" ]; then
758       grep -q $device /proc/partitions && \
759       ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS:$device:install bootmanager grub into MBR of /dev/$device"
760     fi
761   done
762   ADDITIONAL_PARAMS=${ADDITIONAL_PARAMS#:}
763
764   OIFS="$IFS"; IFS=:
765
766   # shellcheck disable=SC2086
767   GETMBR=$(dialog --stdout --title "$PN" --default-item mbr \
768           --menu "Where do you want to install the bootmanager grub?" 0 0 0 \
769             mbr       "install bootmanager into $MBRPART" \
770             nowhere   "do not install bootmanager at all" \
771           ${ADDITIONAL_PARAMS})
772   [ $? -eq 0 ] || bailout 3
773   IFS="$OIFS"
774
775   case "$GETMBR" in
776     mbr)
777       # /dev/md0: has to be installed in MBR of /dev/md0 and not in /dev/md:
778       if echo "$TARGET" | grep -q "/dev/md" ; then
779         GRUB="$TARGET"
780       else
781         GRUB="$MBRDISK"
782       fi
783       ;;
784     hda)
785       GRUB="/dev/hda"
786       ;;
787     sda)
788       GRUB="/dev/sda"
789       ;;
790     nowhere)
791       GRUB=''
792       ;;
793   esac
794 }
795 # }}}
796
797 # ask for Debian release {{{
798 prompt_for_release()
799 {
800   [ -n "$RELEASE" ] && DEFAULT_RELEASE="$RELEASE" || DEFAULT_RELEASE='bullseye'
801   RELEASE="$(dialog --stdout --title "${PN}" --default-item $DEFAULT_RELEASE --menu \
802             "Please enter the Debian release you would like to use for installation:" \
803             0 50 8 \
804             buster   Debian/10 \
805             bullseye Debian/11 \
806             bookworm Debian/12 \
807             sid      Debian/unstable)"
808   [ $? -eq 0 ] || bailout
809 }
810 # }}}
811
812 # ask for hostname {{{
813 prompt_for_hostname()
814 {
815   HOSTNAME="$(dialog --stdout --title "${PN}" --inputbox \
816             "Please enter the hostname you would like to use for installation:" \
817             0 0 "$HOSTNAME")"
818   [ $? -eq 0 ] || bailout
819 }
820 # }}}
821
822 # ask for password {{{
823 prompt_for_password()
824 {
825   if [ "$_opt_nopassword" ] ; then
826     einfo "Skip asking for root password as requested."
827     return 0
828   fi
829
830   ROOTPW1='PW1'
831   ROOTPW2='PW2'
832   while [ "$ROOTPW1" != "$ROOTPW2" ]; do
833     ROOTPW1=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
834     "Please enter the password for the root account:" 10 60)
835     [ $? -eq 0 ] || bailout
836
837     ROOTPW2=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
838     "Please enter the password for the root account again for \
839     confirmation:" 10 60)
840     [ $? -eq 0 ] || bailout
841
842     if [ "$ROOTPW1" != "$ROOTPW2" ]; then
843       dialog --stdout --title "${PN}" --ok-label \
844         "Retry" --msgbox "Passwords do not match!" 10 60
845     fi
846   done
847   ROOTPASSWORD="$ROOTPW1"
848 }
849 # }}}
850
851 # ask for Debian mirror {{{
852 prompt_for_mirror()
853 {
854   [ -n "$ISO" ] && DEFAULT_MIRROR='local' || DEFAULT_MIRROR='net'
855
856   CHOOSE_MIRROR=$(dialog --stdout --title "$PN" --default-item $DEFAULT_MIRROR \
857           --menu "Where do you want to install from?" 0 0 0 \
858             net   "install via network (downloading from mirror)" \
859             local "install from local directory/mirror"
860           )
861   [ $? -eq 0 ] || bailout
862
863   if [ "$CHOOSE_MIRROR" = 'net' ] ; then
864      [ -n "$MIRROR" ] || MIRROR='http://deb.debian.org/debian'
865      MIRROR="$(dialog --stdout --title "${PN}" --inputbox \
866                "Please enter Debian mirror you would like to use for installing packages." \
867                0 0 $MIRROR)"
868      [ $? -eq 0 ] || bailout
869   else # CHOOSE_MIRROR == local
870      [ -n "$ISO" ] || ISO='/mnt/mirror'
871      ISO="$(dialog --stdout --title "${PN}" --inputbox \
872                "Please enter directory name you would like to use for installing packages." \
873                0 0 $ISO)"
874      [ $? -eq 0 ] || bailout
875   fi
876 }
877 # }}}
878
879 # software raid setup {{{
880 config_swraid_setup()
881 {
882 TMPFILE=$(mktemp)
883
884 # Currently we support only raid1:
885 RAIDLEVEL='raid1'
886
887 MD_LIST=$(for i in $(seq 0 9) ; do
888             awk '{print $4}' /proc/partitions | grep -q "md$i" || \
889             echo "/dev/md$i /dev/md$i"
890           done)
891
892 # shellcheck disable=SC2086
893 TARGET=$(dialog --stdout --title "$PN" --default-item /dev/md0 \
894 --menu "Which device do you want to use for ${RAIDLEVEL}?
895
896 Notice: activated devices will not be listed for security reasons. Anyway, please make sure the selected device is not in use already!" 0 0 0 \
897 $MD_LIST)
898 [ $? -eq 0 ] || bailout 20
899
900 AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
901              sed 's/*//' | \
902              grep -v 'Extended$' | \
903              gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}')
904 [ -n "$AVAILABLE_PARTITIONS" ] || echo "Fatal error: no partitions available?"
905 PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
906                      echo "$i $(blkid -s TYPE -o value "$i" 2>/dev/null || echo '[no_filesystem_yet]') off"
907                  done)
908
909 # shellcheck disable=SC2086
910 dialog --title "$PN" --separate-output \
911        --checklist "Please select the partitions you would like to use for your $RAIDLEVEL on ${TARGET}:" 0 0 0 \
912        $PARTITION_LIST 2>"$TMPFILE"
913 [ $? -eq 0 ] || bailout
914 SELECTED_PARTITIONS="$(cat "$TMPFILE")"
915
916 NUM_PARTITIONS=0
917 while IFS= read -r i; do
918   NUM_PARTITIONS=$(( NUM_PARTITIONS + 1 ))
919 done < "$TMPFILE"
920
921 # force metadata version 0.90 for lenny so old grub can boot from this array.
922 METADATA_VERSION=""
923 if [ "$RELEASE" = "lenny" ]; then
924    METADATA_VERSION="-e0"
925 fi
926
927 ERRORFILE=$(mktemp)
928 # shellcheck disable=SC2086
929 yes | mdadm --create "${TARGET}" --level="${RAIDLEVEL}" \
930       --raid-devices="${NUM_PARTITIONS}" ${METADATA_VERSION} ${SELECTED_PARTITIONS} >/dev/null 2>$ERRORFILE
931 RC=$?
932 if [ "$RC" = 0 ] ; then
933    dialog --title "$PN" --msgbox \
934    "Creating $TARGET was successful." 0 0
935    rm -f "$TMPFILE" "$ERRORFILE"
936 else
937    dialog --title "$PN" --msgbox \
938    "There was an error setting up $TARGET:
939
940 $(cat "$ERRORFILE")
941
942 Exiting." 0 0
943    rm -f "$TMPFILE" "$ERRORFILE"
944    bailout 1
945 fi
946
947 }
948
949 prompt_for_swraid()
950 {
951 if dialog --stdout --title "$PN" \
952           --defaultno --yesno "Do you want to configure Software RAID?
953
954 Please notice that only RAID level 1 is supported by ${PN} currently. Configuration will take place using mdadm." 0 0 ; then
955   config_swraid_setup
956 fi
957 }
958 # }}}
959
960 # user should recheck his configuration {{{
961 # support full automatic installation:
962 checkforrun() {
963    dialog --timeout 10 --title "$PN" \
964           --yesno "Do you want to stop at this stage?
965
966 Notice: you are running ${PN} in non-interactive mode.
967 ${PN} will install Debian ${RELEASE} on ${TARGET}.
968 Last chance to quit. Timeout of 10 seconds running....
969
970 Do you want to stop now?" 0 0 2>/dev/null
971 }
972 # }}}
973
974 # format efi partition {{{
975 format_efi_partition() {
976   if [ -z "$EFI" ] ; then
977     return 0
978   fi
979
980   if ! [ -b "$EFI" ] ; then
981     eerror "Specified efi argument [$EFI] not a valid block device."
982     bailout 1
983   fi
984
985   if fsck.vfat -bn "$EFI" >/dev/null; then
986     einfo "EFI partition $EFI seems to have a FAT filesystem, not modifying." ; eend 0
987   else
988     einfo "EFI partition $EFI doesn't seem to be formatted, creating filesystem."
989     mkfs.fat -F32 -n "EFI" "$EFI"
990     RC=$?
991     if [ $RC -eq 0 ] ; then
992       eend 0
993     else
994       eerror "Error while creating filesystem on ${EFI}."
995       eend 1
996       bailout 1
997     fi
998   fi
999 }
1000 # }}}
1001
1002 # check for EFI support or try to enable it {{{
1003 efi_support() {
1004   local efivars_loaded=false
1005   # this is for kernels versions before v3.10, which didn't provide efivarfs yet
1006   if modprobe efivars &>/dev/null ; then
1007     efivars_loaded=true
1008   fi
1009   # kernel versions v3.10 and newer usually provide efivarfs
1010   if modprobe efivarfs &>/dev/null ; then
1011     efivars_loaded=true
1012   fi
1013
1014   if [ -d /sys/firmware/efi ] ; then
1015     einfo "EFI support detected." ; eend 0
1016     return 0
1017   fi
1018
1019   if ! [ -d /sys/firmware/efi ] && [ "${efivars_loaded:-}" = "true" ] ; then
1020     einfo "EFI support detected, but system seems to be running in BIOS mode."
1021   fi
1022
1023   return 1
1024 }
1025 # }}}
1026
1027 # make sure the user is aware of the used configuration {{{
1028 checkconfiguration()
1029 {
1030
1031 if efi_support ; then
1032   if [ -z "$_opt_efi" ] ; then
1033     ewarn "EFI support detected but no --efi option given, please consider enabling it." ; eend 0
1034   fi
1035 else
1036   if [ -n "$_opt_efi" ] ; then
1037      eerror "EFI option used but no EFI support detected." ; eend 0
1038      bailout 1
1039   fi
1040 fi
1041
1042 if [ -n "$AUTOINSTALL" ] ; then
1043    if checkforrun ; then
1044       eerror "Exiting as requested" ; eend 0
1045       bailout 1
1046    fi
1047 elif [ -n "$INTERACTIVE" ] ; then
1048
1049    INFOTEXT="Please recheck configuration before execution:
1050    "
1051    [ -n "$TARGET" ]  && INFOTEXT="$INFOTEXT
1052    Target:          $TARGET"
1053    [ -n "$GRUB" ]    && INFOTEXT="$INFOTEXT
1054    Install grub:    $GRUB"
1055    [ -n "$EFI" ]    && INFOTEXT="$INFOTEXT
1056    Install efi:     $EFI"
1057    [ -n "$RELEASE" ] && INFOTEXT="$INFOTEXT
1058    Using release:   $RELEASE"
1059    [ -n "$HOSTNAME" ] && INFOTEXT="$INFOTEXT
1060    Using hostname:  $HOSTNAME"
1061    [ -n "$MIRROR" ]  && INFOTEXT="$INFOTEXT
1062    Using mirror:    $MIRROR"
1063    [ -n "$ISO" ]  && INFOTEXT="$INFOTEXT
1064    Using ISO:       $ISO"
1065    [ -n "$ARCH" ]  && INFOTEXT="$INFOTEXT
1066    Using arch:      $ARCH"
1067    [ -n "$CONFFILES" ] && INFOTEXT="$INFOTEXT
1068    Config files:    $CONFFILES"
1069
1070    INFOTEXT="$INFOTEXT
1071
1072 Is this ok for you? Notice: selecting 'No' will exit ${PN}."
1073
1074    dialog --title "$PN" --no-collapse \
1075           --yesno "$INFOTEXT" 0 0
1076    [ $? -eq 0 ] || bailout 0
1077
1078 else # if not running automatic installation display configuration and prompt for execution:
1079    einfo "$PN [${VERSION}] - Please recheck configuration before execution:"
1080    echo
1081    echo "   Target:          $TARGET"
1082
1083    # do not display if MNTPOINT is the default one
1084    case "$MNTPOINT" in /mnt/debootstrap*) ;; *) echo "   Mount point:     $MNTPOINT" ;; esac
1085
1086    if [ -n "$VIRTUAL" ] ; then
1087       echo "   Install grub:    yes"
1088    else
1089      [ -n "$GRUB" ]     && echo "   Install grub:    $GRUB" || echo "   Install grub:    no"
1090      [ -n "$EFI" ]      && echo "   Install efi:     $EFI"  || echo "   Install efi:     no"
1091    fi
1092
1093    [ -n "$RELEASE" ]   && echo "   Using release:   $RELEASE"
1094    [ -n "$HOSTNAME" ]  && echo "   Using hostname:  $HOSTNAME"
1095    [ -n "$MIRROR" ]    && echo "   Using mirror:    $MIRROR"
1096    [ -n "$ISO" ]       && echo "   Using ISO:       $ISO"
1097    [ -n "$ARCH" ]      && echo "   Using arch:      $ARCH"
1098    [ -n "$CONFFILES" ] && echo "   Config files:    $CONFFILES"
1099    if [ -n "$VIRTUAL" ] ; then
1100       echo "   Deploying as Virtual Machine."
1101       if [ -n "$VMSIZE" ] && [ -n "$VMFILE" ]; then
1102          echo "   Using Virtual Disk file with size of ${VMSIZE}."
1103       fi
1104    fi
1105
1106    if [ ! -t 0 ] && [ -z "$ROOTPASSWORD" ] && [ -z "$NOPASSWORD" ] ; then
1107       echo
1108       echo "   You do not have a TTY allocated, your password will be shown in"
1109       echo "   plaintext on the terminal! If you are using SSH, try its -t option!"
1110    fi
1111
1112    echo
1113    echo "   Important! Continuing will delete all data from ${TARGET}!"
1114
1115    if [ -n "$FORCE" ] ; then
1116      einfo "Skip user acknowledgement as requested via --force option."
1117    else
1118      echo
1119      einfon "Is this ok for you? [y/N] "
1120      read -r a
1121      if ! [ "$a" = 'y' ] || [ "$a" = 'Y' ] ; then
1122         eerror "Exiting as requested." ; eend 1
1123         bailout 1
1124      fi
1125    fi
1126 fi
1127 }
1128 # }}}
1129
1130 # interactive mode {{{
1131 interactive_mode()
1132 {
1133   check4progs dialog || bailout 1
1134
1135   welcome_dialog
1136
1137   prompt_for_release
1138
1139   prompt_for_swraid
1140
1141   prompt_for_target
1142
1143   prompt_for_bootmanager
1144
1145   prompt_for_hostname
1146
1147   prompt_for_password
1148
1149   prompt_for_mirror
1150 }
1151
1152 # run interactive mode if we didn't get the according configuration yet
1153 if [ -z "$TARGET" ] || [ -n "$INTERACTIVE" ] ; then
1154    # only target might be unset, so make sure the INTERACTIVE flag is set as well
1155    INTERACTIVE=1
1156    interactive_mode
1157 fi
1158 # }}}
1159
1160 # architecture setup {{{
1161 if [ -n "$ARCH" ] ; then
1162    ARCHCMD="--arch $ARCH"
1163    ARCHINFO=" (${ARCH})"
1164 else
1165    ARCH="$(dpkg --print-architecture)"
1166    ARCHCMD="--arch $ARCH"
1167    ARCHINFO=" (${ARCH})"
1168 fi
1169
1170 if [ -z "${ARCH:-}" ] ; then
1171   eerror 'Architecture neither set (environment variable ARCH), nor could be automatically identified (using dpkg).'
1172   eerror 'Consider setting the --arch ... option.' ; eend 1
1173   bailout 1
1174 fi
1175 # }}}
1176
1177 # It is not possible to build amd64 on i686. {{{
1178 CURRENT_ARCH="$(uname -m)"
1179 if [ "$CURRENT_ARCH" != "x86_64" ] ; then
1180    if [ "$ARCH" = "amd64" ] ; then
1181       eerror "It is not possible to build amd64 on $CURRENT_ARCH. Consider installing and booting the 'linux-image-amd64' kernel or using '--arch i386' instead." ; eend 1
1182       bailout 1
1183    fi
1184 fi
1185 # }}}
1186
1187 # Support for generic release codenames is unavailable. {{{
1188 if [ "$RELEASE" = "stable" ] || [ "$RELEASE" = "testing" ] ; then
1189    eerror "Generic release codenames (stable, testing) are unsupported. \
1190 Please use specific codenames such as bullseye or bookworm." ; eend 1
1191    bailout 1
1192 fi
1193 # }}}
1194
1195 checkconfiguration
1196
1197 # finally make sure at least $TARGET is set [the partition for the new system] {{{
1198 if [ -n "$TARGET" ] ; then
1199    SHORT_TARGET="${TARGET##*/}"
1200 else
1201    eerror "Please adjust $CONFFILES/config or..."
1202    eerror "... use the interactive version for configuration before running ${0}" ; eend 1
1203    bailout 1
1204 fi
1205 # }}}
1206
1207 # stages setup {{{
1208 if [ -z "$STAGES" ] ; then
1209    STAGES="/var/cache/grml-debootstrap/stages_${SHORT_TARGET}"
1210    [ -d "$STAGES" ] || mkdir -p "$STAGES"
1211 fi
1212
1213 if [ -r "$STAGES"/grml-debootstrap ] ; then
1214    if grep -q 'done' "${STAGES}/grml-debootstrap" ; then
1215       eerror "Error: grml-debootstrap has been executed already, won't continue therefore."
1216       eerror "If you want to re-execute grml-debootstrap just manually remove ${STAGES}" ; eend 1
1217    fi
1218 fi
1219 # }}}
1220
1221 # partition handling {{{
1222 PARTITION=''
1223 DIRECTORY=''
1224
1225 set_target_directory(){
1226     # assume we are installing into a directory, don't run mkfs and grub related stuff therefore
1227     DIRECTORY=1
1228     MNTPOINT="$TARGET"
1229     MKFS=''
1230     TUNE2FS=''
1231     FSCK=''
1232     # make sure we normalise the path to an absolute directory name so something like:
1233     #  mkdir -p foo/a bar/a; (cd foo; grml-debootstrap -t a)&; (cd bar; grml-debootstrap -t a)&; wait
1234     # works
1235     TARGET="$(readlink -f "$TARGET")"
1236 }
1237
1238 if [ -b "$TARGET" ] || [ -n "$VIRTUAL" ] ; then
1239     PARTITION=1
1240 else
1241     # $TARGET was not detected as block device, but we do not want to create target directory in /dev/
1242     if [[ $TARGET == "/dev/"* ]]; then
1243       eerror "Error: Will not create target directory $TARGET in /dev."
1244       eerror "  Please check the partition(s) of the blockdevice."; eend 1
1245       bailout 1
1246     fi
1247     set_target_directory
1248 fi
1249 # }}}
1250
1251 # make sure we have the right syntax when using an iso image {{{
1252 if [ -n "$ISO" ] ; then
1253    case $ISO in
1254       file*) # do nothing
1255       ;;
1256       *)
1257       ISO=file:$ISO
1258       ;;
1259    esac
1260 fi
1261 ISODIR=${ISO##file:}
1262 ISODIR=${ISODIR%%/}
1263 # }}}
1264
1265 # Debian ISOs do not contain signed Release files {{{
1266 if [ -n "$ISO" ] ; then
1267     DEBOOTSTRAP_OPT="$DEBOOTSTRAP_OPT --no-check-gpg"
1268 fi
1269 # }}}
1270
1271 # create filesystem {{{
1272 mkfs() {
1273   if [ -n "$DIRECTORY" ] ; then
1274      einfo "Running grml-debootstrap on a directory, skipping mkfs stage."
1275      return 0
1276   fi
1277
1278   if grep -q "$TARGET" /proc/mounts ; then
1279     eerror "$TARGET already mounted, exiting to avoid possible damage. (Manually unmount $TARGET)" ; eend 1
1280     bailout 1
1281   fi
1282
1283   # mkfs.ext* might prompt with "/dev/sdX# contains a ext* file system
1284   # created on ... Proceed anyway? (y,n)" which we want to skip in force mode
1285   if [ -n "$MKFS" ] && [ -n "$FORCE" ] ; then
1286     case "$MKFS" in
1287       mkfs.ext*)
1288         einfo "Enabling force option (-F) for mkfs.ext* tool as requested via --force switch."
1289         MKFS_OPTS="$MKFS_OPTS -F"
1290         eend 0
1291
1292         ;;
1293     esac
1294   fi
1295
1296   # starting with e2fsprogs 1.43~WIP.2015.05.18-1 mkfs.ext4 enables the metadata_csum feature
1297   # by default, which requires a recent version of tune2fs on the target system then,
1298   # so disable this feature for older Debian releases where it's known to be unsupported
1299   if [ -n "$MKFS" ] && [ "$MKFS" = "mkfs.ext4" ] ; then
1300     case "$RELEASE" in
1301       lenny|squeeze|wheezy|jessie)
1302         # assume a more recent version if we can't identify the version via dpkg-query
1303         local e2fsprogs_version
1304         e2fsprogs_version="$(dpkg-query --show --showformat='${Version}' e2fsprogs 2>/dev/null || echo 1.44)"
1305         if [ -n "$e2fsprogs_version" ] && dpkg --compare-versions "$e2fsprogs_version" ge '1.43~WIP.2015.05.18-1' ; then
1306           einfo "Disabling metadata_csum feature for $MKFS as $RELEASE doesn't support it."
1307           MKFS_OPTS="$MKFS_OPTS -O ^metadata_csum"
1308           eend 0
1309         fi
1310         ;;
1311     esac
1312   fi
1313
1314   if [ -n "$MKFS" ] ; then
1315     einfo "Running $MKFS $MKFS_OPTS on $TARGET"
1316     # shellcheck disable=SC2086
1317     "$MKFS" $MKFS_OPTS "$TARGET" ; RC=$?
1318
1319     if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1320       if ! echo "$MKFS" | grep -q "mkfs.ext" ; then
1321         eerror "Not changing disk uuid for $TARGET because $MKFS doesn't seem to match for ext{2,3,4} file system"
1322         eend 1
1323         bailout 1
1324       else
1325         einfo "Changing disk uuid for $TARGET to fixed (non-random) value $DISK_IDENTIFIER using tune2fs"
1326         tune2fs "$TARGET" -U "$DISK_IDENTIFIER"
1327         eend $?
1328       fi
1329     fi
1330
1331     # make sure /dev/disk/by-uuid/... is up2date, otherwise grub
1332     # will fail to detect the uuid in the chroot
1333     if [ -n "$VIRTUAL" ] ; then
1334       einfo "Virtual environment doesn't require blockdev --rereadpt, skipping therefore"
1335     elif echo "$TARGET" | grep -q "/dev/md" ; then
1336       blockdev --rereadpt "${TARGET}"
1337     else
1338       # if we deploy to /dev/sdX# then let's see if /dev/sdX exists
1339       local main_device="${TARGET%%[0-9]*}"
1340       # sanity check to not try to e.g. access /dev/loop if we get /dev/loop0
1341       if [ -f "/sys/block/$(basename "${main_device}")/$(basename "${TARGET}")/dev" ] ; then
1342         blockdev --rereadpt "$main_device"
1343       else
1344         einfo "No underlying block device for $TARGET identified, skipping blockdev --rereadpt."
1345       fi
1346     fi
1347     # give the system 2 seconds, otherwise we might run into
1348     # race conditions :-/
1349     sleep 2
1350
1351     eend $RC
1352   fi
1353 }
1354 # }}}
1355
1356 # retrieve ID_FS_UUID {{{
1357 identify_target_uuid() {
1358   local device="$1"
1359
1360   if ! [ -b "$device" ] ; then
1361     return 1
1362   fi
1363
1364   eval "$(blkid -o udev "$1" 2>/dev/null)"
1365
1366   if [ -n "$ID_FS_UUID" ] ; then
1367     echo "$ID_FS_UUID"
1368   else
1369     return 1
1370   fi
1371 }
1372 # }}}
1373
1374 # identify TARGET_UUID {{{
1375 mountpoint_to_blockdevice() {
1376   TARGET_UUID=''
1377
1378   TARGET_UUID=$(identify_target_uuid "$TARGET" 2>/dev/null || true)
1379   if [ -n "$TARGET_UUID" ] ; then
1380     einfo "Identified UUID $TARGET_UUID for $TARGET"
1381     return 0
1382   fi
1383
1384   # $TARGET might be a mountpoint and not a blockdevice, search for according entry
1385   for file in /sys/block/*/*/dev ; do
1386     if grep -q "^$(mountpoint -d "${TARGET}")$" "$file" ; then
1387       local dev
1388       dev="${file%/dev}"
1389       dev="/dev/${dev##*/}"
1390       TARGET_UUID=$(identify_target_uuid "$dev" 2>/dev/null || true)
1391
1392       if [ -n "$TARGET_UUID" ] ; then
1393         einfo "Identified UUID $TARGET_UUID for $TARGET (via $file)"
1394         return 0
1395       fi
1396     fi
1397   done
1398 }
1399 # }}}
1400
1401 # modify filesystem settings {{{
1402 tunefs() {
1403   if [ -n "$TUNE2FS" ] && echo "$MKFS" | grep -q "mkfs.ext" ; then
1404      einfo "Disabling automatic filesystem check on $TARGET via tune2fs"
1405      $TUNE2FS "$TARGET"
1406      eend $?
1407   fi
1408 }
1409 # }}}
1410
1411 # mount the new partition or if it's a directory do nothing at all {{{
1412 mount_target() {
1413   if [ -n "$DIRECTORY" ] ; then
1414      einfo "Running grml-debootstrap on a directory, nothing to mount."
1415   else
1416      if grep -q "$TARGET" /proc/mounts ; then
1417         ewarn "$TARGET already mounted, continuing anyway." ; eend 0
1418      else
1419        if ! [ -d "${MNTPOINT}" ] ; then
1420           [ -n "$VIRTUAL" ] || mkdir -p "${MNTPOINT}"
1421        fi
1422        einfo "Mounting $TARGET to $MNTPOINT"
1423        mkdir -p "$MNTPOINT"
1424        mount -o rw,suid,dev "$TARGET" "$MNTPOINT"
1425        eend $?
1426      fi
1427   fi
1428   if [ -n "$ISODIR" ] ; then
1429      einfo "Mounting Debian image loopback to $MNTPOINT/$ISODIR."
1430      mkdir -p "$MNTPOINT/$ISODIR"
1431      mount --bind "$ISODIR" "$MNTPOINT/$ISODIR"
1432      eend $?
1433   fi
1434 }
1435 # }}}
1436
1437 # prepare VM image for usage with debootstrap {{{
1438 prepare_vm() {
1439   if [ -z "$VIRTUAL" ] ; then
1440      return 0 # be quiet by intention
1441   fi
1442
1443   if [ -b "$TARGET" ] && [ -n "$VMFILE" ] ; then
1444      eerror "Error: specified virtual disk target ($TARGET) is an existing block device."
1445      eend 1
1446      bailout 1
1447   fi
1448   if [ ! -b "$TARGET" ] && [ -z "$VMFILE" ] ; then
1449      eerror "Error: specified virtual disk target ($TARGET) does not exist yet."
1450      eend 1
1451      bailout 1
1452   fi
1453
1454   # make sure loop module is present and a usable loop device exists
1455   modprobe -q loop
1456   if ! losetup -f >/dev/null 2>&1; then
1457     eerror "Error finding usable loop device" ; eend 1
1458     bailout 1
1459   fi
1460
1461   # if dm-mod isn't available then kpartx will fail with
1462   # "Is device-mapper driver missing from kernel? [...]"
1463   modprobe -q dm-mod
1464   if ! grep -q 'device-mapper' /proc/misc >/dev/null 2>&1 ; then
1465     eerror "Device-mapper support missing in kernel." ; eend 1
1466     bailout 1
1467   fi
1468
1469   ORIG_TARGET="$TARGET" # store for later reuse
1470
1471   if [ -n "$VMFILE" ]; then
1472     qemu-img create -f raw "${TARGET}" "${VMSIZE}"
1473   fi
1474   parted -s "${TARGET}" 'mklabel msdos'
1475   if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1476     einfo "Adjusting disk signature to a fixed (non-random) value"
1477     MBRTMPFILE=$(mktemp)
1478     dd if="${TARGET}" of="${MBRTMPFILE}" bs=512 count=1
1479     echo -en "\\x41\\x41\\x41\\x41" | dd of="${MBRTMPFILE}" conv=notrunc seek=440 bs=1
1480     dd if="${MBRTMPFILE}" of="${TARGET}" conv=notrunc
1481     eend $?
1482   fi
1483   parted -s "${TARGET}" 'mkpart primary ext4 4MiB 100%'
1484   parted -s "${TARGET}" 'set 1 boot on'
1485
1486   DEVINFO=$(kpartx -asv "$TARGET") # e.g. 'add map loop0p1 (254:5): 0 20477 linear 7:0 3'
1487   if [ -z "${DEVINFO}" ] ; then
1488     eerror "Error setting up loopback device." ; eend 1
1489     bailout 1
1490   fi
1491
1492   # hopefully this always works as expected
1493   LOOP_PART="${DEVINFO##add map }" # 'loop0p1 (254:5): 0 20477 linear 7:0 3'
1494   LOOP_PART="${LOOP_PART// */}"    # 'loop0p1'
1495   LOOP_DISK="${LOOP_PART%p*}"      # 'loop0'
1496   export TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop1p1'
1497
1498   if [ -z "$TARGET" ] ; then
1499      eerror "Error: target could not be set to according /dev/mapper/* device." ; eend 1
1500      bailout 1
1501   fi
1502 }
1503 # }}}
1504
1505 # make VM image bootable {{{
1506 grub_install() {
1507   if [ -z "${VIRTUAL}" ] ; then
1508      return 0
1509   fi
1510   if [ "${GRUB_INSTALL}" != "yes" ] ; then
1511     einfo "Not installing GRUB as requested via \$GRUB_INSTALL=$GRUB_INSTALL"
1512     return 0
1513   fi
1514
1515   if ! mount "${TARGET}" "${MNTPOINT}" ; then
1516     eerror "Error: Mounting ${TARGET} failed, can not continue." ; eend 1
1517     bailout 1
1518   fi
1519
1520   mount -t proc none "${MNTPOINT}"/proc
1521   mount -t sysfs none "${MNTPOINT}"/sys
1522   mount -t devtmpfs udev "${MNTPOINT}"/dev
1523   mount -t devpts devpts "${MNTPOINT}"/dev/pts
1524
1525 # Has chroot-script installed GRUB to MBR using grub-install (successfully), already?
1526 # chroot-script skips installation for unset ${GRUB}
1527 if [[ -z "${GRUB}" ]] || ! dd if="${GRUB}" bs=512 count=1 2>/dev/null | cat -v | grep -Fq GRUB; then
1528   einfo "Installing Grub as bootloader."
1529
1530   if ! chroot "${MNTPOINT}" dpkg --list grub-pc 2>/dev/null | grep -q '^ii' ; then
1531     echo "Notice: grub-pc package not present yet, installing it therefore."
1532     # shellcheck disable=SC2086
1533     DEBIAN_FRONTEND=$DEBIAN_FRONTEND chroot "$MNTPOINT" apt-get -y --no-install-recommends install $DPKG_OPTIONS grub-pc
1534   fi
1535
1536   mkdir -p "${MNTPOINT}/boot/grub"
1537   if ! [ -d "${MNTPOINT}"/usr/lib/grub/i386-pc/ ] ; then
1538      eerror "Error: grub not installed inside Virtual Machine. Can not install bootloader." ; eend 1
1539      bailout 1
1540   fi
1541
1542   case "$RELEASE" in
1543     lenny|squeeze|wheezy)
1544       cp "${MNTPOINT}"/usr/lib/grub/i386-pc/* "${MNTPOINT}/boot/grub/"
1545       ;;
1546     *)
1547       cp -a "${MNTPOINT}"/usr/lib/grub/i386-pc "${MNTPOINT}/boot/grub/"
1548       ;;
1549   esac
1550   dd if="${MNTPOINT}/usr/lib/grub/i386-pc/boot.img" of="${ORIG_TARGET}" conv=notrunc bs=440 count=1
1551   case "${_opt_filesystem}" in
1552     f2fs)
1553       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos f2fs
1554       ;;
1555     xfs)
1556       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos xfs
1557       ;;
1558     # NOTE - we might need to distinguish between further filesystems
1559     *)
1560       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos ext2
1561       ;;
1562   esac
1563
1564   dd if="${MNTPOINT}/tmp/core.img" of="${ORIG_TARGET}" conv=notrunc seek=1
1565   rm -f "${MNTPOINT}/tmp/core.img"
1566 fi
1567
1568   # workaround for Debian bug #918590 with lvm + udev:
1569   # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
1570   if [ -d /run/udev ] ; then
1571     einfo "Setting up bind-mount /run/udev"
1572     mkdir -p "${MNTPOINT}"/run/udev
1573     mount --bind /run/udev "${MNTPOINT}"/run/udev
1574     eend $?
1575   fi
1576
1577   einfo "Updating grub configuration file."
1578   chroot "${MNTPOINT}" update-grub
1579
1580   case "$RELEASE" in
1581     jessie)
1582       einfo "Applying workaround for GRUB font path bug in jessie (Debian #787685)."
1583       mkdir -p "${MNTPOINT}/boot/grub/fonts/"
1584       cp "${MNTPOINT}/usr/share/grub/unicode.pf2" "${MNTPOINT}/boot/grub/fonts/"
1585       ;;
1586   esac
1587
1588   if grep -q '^GRUB_DISABLE_LINUX_UUID=.*true' "${MNTPOINT}"/etc/default/grub 2>/dev/null ; then
1589     ewarn "GRUB_DISABLE_LINUX_UUID is set to true in /etc/default/grub, not adjusting root= in grub.cfg."
1590     ewarn "Please note that your system might NOT be able to properly boot."
1591   else
1592     einfo "Adjusting grub.cfg for successful boot sequence."
1593     sed -i "s;root=[^ ]\\+;root=UUID=$TARGET_UUID;" "${MNTPOINT}"/boot/grub/grub.cfg
1594   fi
1595
1596   # workaround for Debian bug #918590 with lvm + udev:
1597   # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
1598   if mountpoint "${MNTPOINT}"/run/udev &>/dev/null ; then
1599     einfo "Unmounting bind-mount /run/udev"
1600     umount "${MNTPOINT}"/run/udev
1601     eend $?
1602   fi
1603
1604   umount "${MNTPOINT}"/proc
1605   umount "${MNTPOINT}"/sys
1606   umount "${MNTPOINT}"/dev/pts
1607   try_umount 3 "${MNTPOINT}"/dev
1608
1609 }
1610 # }}}
1611
1612 # unmount VM image {{{
1613 umount_target() {
1614   if [ -z "${VIRTUAL}" ] ; then
1615      return 0
1616   fi
1617
1618   umount "${MNTPOINT}"
1619   kpartx -d "${ORIG_TARGET}" >/dev/null
1620   # Workaround for a bug in kpartx which doesn't clean up properly,
1621   # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
1622   if dmsetup ls | grep -q "^${LOOP_PART} "; then
1623     kpartx -d "/dev/${LOOP_DISK}" >/dev/null
1624   fi
1625 }
1626 # }}}
1627
1628 # install main chroot {{{
1629 debootstrap_system() {
1630   if [ "$_opt_nodebootstrap" ]; then
1631      einfo "Skipping debootstrap as requested."
1632      return
1633   fi
1634
1635   if grep -q "$MNTPOINT" /proc/mounts || [ -n "$DIRECTORY" ] ; then
1636     :
1637   else
1638     eerror "Error: $MNTPOINT not mounted, can not continue."
1639     eend 1 ; exit 1
1640   fi
1641
1642   if [ -n "$ISO" ] ; then
1643     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${ISO}"
1644     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $ISO"
1645     # shellcheck disable=SC2086
1646     "$DEBOOTSTRAP" $ARCHCMD $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$ISO"
1647     RC=$?
1648   else
1649     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${MIRROR}"
1650     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $MIRROR"
1651     # shellcheck disable=SC2086
1652     "$DEBOOTSTRAP" $ARCHCMD $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$MIRROR"
1653     RC=$?
1654   fi
1655
1656   if [ $RC -ne 0 ] ; then
1657     if [ -r "$MNTPOINT/debootstrap/debootstrap.log" ] && \
1658       [ -s "$MNTPOINT/debootstrap/debootstrap.log" ] ; then
1659       einfo "Presenting last ten lines of debootstrap.log:"
1660       tail -10 "${MNTPOINT}"/debootstrap/debootstrap.log
1661       einfo "End of debootstrap.log"
1662     fi
1663   fi
1664
1665   eend $RC
1666 }
1667 # }}}
1668
1669 # prepare chroot via chroot-script {{{
1670 preparechroot() {
1671   einfo "Preparing chroot system"
1672
1673   # provide variables to chroot system
1674   CHROOT_VARIABLES="/var/cache/grml-debootstrap/variables_${SHORT_TARGET}"
1675   touch "$CHROOT_VARIABLES"
1676   chmod 600 "$CHROOT_VARIABLES" # make sure nobody except root can read it
1677   echo "# Configuration of ${PN}"                                                                                   > "$CHROOT_VARIABLES"
1678   # Resorting to sed(1) for escaping since "VAR='${VAR//\'/\'\\\'\'}'" does not work with all versions of Bash,
1679   #   e.g. not with 4.2.37(1)-release (a.k.a 4.2+dfsg-0.1+deb7u3) of Debian wheezy
1680   [ -n "$ARCH" ]                && echo "ARCH='$(sed "s,','\\\\'',g" <<<"${ARCH}")'"                               >> "$CHROOT_VARIABLES"
1681   [ -n "$BACKPORTREPOS" ]       && echo "BACKPORTREPOS='$(sed "s,','\\\\'',g" <<<"${BACKPORTREPOS}")'"             >> "$CHROOT_VARIABLES"
1682   [ -n "$BOOT_APPEND" ]         && echo "BOOT_APPEND='$(sed "s,','\\\\'',g" <<<"${BOOT_APPEND}")'"                 >> "$CHROOT_VARIABLES"
1683   [ -n "$CHROOT_SCRIPTS" ]      && echo "CHROOT_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${CHROOT_SCRIPTS}")'"           >> "$CHROOT_VARIABLES"
1684   [ -n "$COMPONENTS" ]          && echo "COMPONENTS='$(sed "s,','\\\\'',g" <<<"${COMPONENTS}")'"                   >> "$CHROOT_VARIABLES"
1685   [ -n "$CONFFILES" ]           && echo "CONFFILES='$(sed "s,','\\\\'',g" <<<"${CONFFILES}")'"                     >> "$CHROOT_VARIABLES"
1686   [ -n "$DEBCONF" ]             && echo "DEBCONF='$(sed "s,','\\\\'',g" <<<"${DEBCONF}")'"                         >> "$CHROOT_VARIABLES"
1687   [ -n "$DEBIAN_FRONTEND" ]     && echo "DEBIAN_FRONTEND='$(sed "s,','\\\\'',g" <<<"${DEBIAN_FRONTEND}")'"         >> "$CHROOT_VARIABLES"
1688   [ -n "$DEBOOTSTRAP" ]         && echo "DEBOOTSTRAP='$(sed "s,','\\\\'',g" <<<"${DEBOOTSTRAP}")'"                 >> "$CHROOT_VARIABLES"
1689   [ -n "$DEFAULT_LOCALES" ]     && echo "DEFAULT_LOCALES='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LOCALES}")'"         >> "$CHROOT_VARIABLES"
1690   [ -n "$DEFAULT_LANGUAGE" ]    && echo "DEFAULT_LANGUAGE='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LANGUAGE}")'"       >> "$CHROOT_VARIABLES"
1691   [ -n "$EXTRAPACKAGES" ]       && echo "EXTRAPACKAGES='$(sed "s,','\\\\'',g" <<<"${EXTRAPACKAGES}")'"             >> "$CHROOT_VARIABLES"
1692   [ -n "$EFI" ]                 && echo "EFI='$(sed "s,','\\\\'',g" <<<"${EFI}")'"                                 >> "$CHROOT_VARIABLES"
1693   [ -n "$FALLBACK_MIRROR" ]     && echo "FALLBACK_MIRROR='$(sed "s,','\\\\'',g" <<<"${FALLBACK_MIRROR}")'"         >> "$CHROOT_VARIABLES"
1694   [ -n "$FILESYSTEM" ]          && echo "FILESYSTEM='$(sed "s,','\\\\'',g" <<<"${FILESYSTEM}")'"                   >> "$CHROOT_VARIABLES"
1695   [ -n "$FORCE" ]               && echo "FORCE='$(sed "s,','\\\\'',g" <<<"${FORCE}")'"                             >> "$CHROOT_VARIABLES"
1696   [ -n "$GRMLREPOS" ]           && echo "GRMLREPOS='$(sed "s,','\\\\'',g" <<<"${GRMLREPOS}")'"                     >> "$CHROOT_VARIABLES"
1697   [ -n "$GRUB" ]                && echo "GRUB='$(sed "s,','\\\\'',g" <<<"${GRUB}")'"                               >> "$CHROOT_VARIABLES"
1698   [ -n "$HOSTNAME" ]            && echo "HOSTNAME='$(sed "s,','\\\\'',g" <<<"${HOSTNAME}")'"                       >> "$CHROOT_VARIABLES"
1699   [ -n "$INITRD" ]              && echo "INITRD='$(sed "s,','\\\\'',g" <<<"${INITRD}")'"                           >> "$CHROOT_VARIABLES"
1700   [ -n "$INITRD_GENERATOR" ]    && echo "INITRD_GENERATOR='$(sed "s,','\\\\'',g" <<<"${INITRD_GENERATOR}")'"       >> "$CHROOT_VARIABLES"
1701   [ -n "$INITRD_GENERATOR_OPTS" ] && echo "INITRD_GENERATOR_OPTS='$(sed "s,','\\\\'',g" <<<"${INITRD_GENERATOR_OPTS}")'" >> "$CHROOT_VARIABLES"
1702   [ -n "$INSTALL_NOTES" ]       && echo "INSTALL_NOTES='$(sed "s,','\\\\'',g" <<<"${INSTALL_NOTES}")'"             >> "$CHROOT_VARIABLES"
1703   [ -n "$ISODIR" ]              && echo "ISODIR='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                              >> "$CHROOT_VARIABLES"
1704   [ -n "$ISO" ]                 && echo "ISO='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                                 >> "$CHROOT_VARIABLES"
1705   [ -n "$KEEP_SRC_LIST" ]       && echo "KEEP_SRC_LIST='$(sed "s,','\\\\'',g" <<<"${KEEP_SRC_LIST}")'"             >> "$CHROOT_VARIABLES"
1706   [ -n "$LOCALES" ]             && echo "LOCALES='$(sed "s,','\\\\'',g" <<<"${LOCALES}")'"                         >> "$CHROOT_VARIABLES"
1707   [ -n "$MIRROR" ]              && echo "MIRROR='$(sed "s,','\\\\'',g" <<<"${MIRROR}")'"                           >> "$CHROOT_VARIABLES"
1708   [ -n "$MKFS" ]                && echo "MKFS='$(sed "s,','\\\\'',g" <<<"${MKFS}")'"                               >> "$CHROOT_VARIABLES"
1709   [ -n "$NOPASSWORD" ]          && echo "NOPASSWORD=\"true\""                                                      >> "$CHROOT_VARIABLES"
1710   [ -n "$NOKERNEL" ]            && echo "NOKERNEL=\"true\""                                                        >> "$CHROOT_VARIABLES"
1711   [ -n "$PACKAGES" ]            && echo "PACKAGES='$(sed "s,','\\\\'',g" <<<"${PACKAGES}")'"                       >> "$CHROOT_VARIABLES"
1712   [ -n "$POST_SCRIPTS" ]        && echo "POST_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${POST_SCRIPTS}")'"               >> "$CHROOT_VARIABLES"
1713   [ -n "$PRE_SCRIPTS" ]         && echo "PRE_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${PRE_SCRIPTS}")'"                 >> "$CHROOT_VARIABLES"
1714   [ -n "$RECONFIGURE" ]         && echo "RECONFIGURE='$(sed "s,','\\\\'',g" <<<"${RECONFIGURE}")'"                 >> "$CHROOT_VARIABLES"
1715   [ -n "$RELEASE" ]             && echo "RELEASE='$(sed "s,','\\\\'',g" <<<"${RELEASE}")'"                         >> "$CHROOT_VARIABLES"
1716   [ -n "$RM_APTCACHE" ]         && echo "RM_APTCACHE='$(sed "s,','\\\\'',g" <<<"${RM_APTCACHE}")'"                 >> "$CHROOT_VARIABLES"
1717   [ -n "$ROOTPASSWORD" ]        && echo "ROOTPASSWORD='$(sed "s,','\\\\'',g" <<<"${ROOTPASSWORD}")'"               >> "$CHROOT_VARIABLES"
1718   [ -n "$SCRIPTS" ]             && echo "SCRIPTS='$(sed "s,','\\\\'',g" <<<"${SCRIPTS}")'"                         >> "$CHROOT_VARIABLES"
1719   [ -n "$SECURE" ]              && echo "SECURE='$(sed "s,','\\\\'',g" <<<"${SECURE}")'"                           >> "$CHROOT_VARIABLES"
1720   [ -n "$SELECTED_PARTITIONS" ] && echo "SELECTED_PARTITIONS='$(sed "s,','\\\\'',g" <<<"${SELECTED_PARTITIONS}")'" >> "$CHROOT_VARIABLES"
1721   [ -n "$TARGET" ]              && echo "TARGET='$(sed "s,','\\\\'',g" <<<"${TARGET}")'"                           >> "$CHROOT_VARIABLES"
1722   [ -n "$UPGRADE_SYSTEM" ]      && echo "UPGRADE_SYSTEM='$(sed "s,','\\\\'',g" <<<"${UPGRADE_SYSTEM}")'"           >> "$CHROOT_VARIABLES"
1723   [ -n "$TARGET_UUID" ]         && echo "TARGET_UUID='$(sed "s,','\\\\'',g" <<<"${TARGET_UUID}")'"                 >> "$CHROOT_VARIABLES"
1724   [ -n "$TIMEZONE" ]            && echo "TIMEZONE='$(sed "s,','\\\\'',g" <<<"${TIMEZONE}")'"                       >> "$CHROOT_VARIABLES"
1725   [ -n "$TUNE2FS" ]             && echo "TUNE2FS='$(sed "s,','\\\\'',g" <<<"${TUNE2FS}")'"                         >> "$CHROOT_VARIABLES"
1726   [ -n "$VMSIZE" ]              && echo "VMSIZE='$(sed "s,','\\\\'',g" <<<"${VMSIZE}")'"                           >> "$CHROOT_VARIABLES"
1727
1728   cp $VERBOSE "${CONFFILES}"/chroot-script "${MNTPOINT}"/bin/chroot-script
1729   chmod 755 "${MNTPOINT}"/bin/chroot-script
1730   [ -d "$MNTPOINT"/etc/debootstrap/ ] || mkdir "$MNTPOINT"/etc/debootstrap/
1731
1732   # make sure we have our files for later use via chroot-script
1733   cp $VERBOSE "${CONFFILES}/config"           "${MNTPOINT}"/etc/debootstrap/
1734   # make sure we adjust the configuration variables accordingly:
1735   sed -i "s#RELEASE=.*#RELEASE=\"$RELEASE\"#" "${MNTPOINT}"/etc/debootstrap/config
1736   sed -i "s#TARGET=.*#TARGET=\"$TARGET\"#"    "${MNTPOINT}"/etc/debootstrap/config
1737   sed -i "s#GRUB=.*#GRUB=\"$GRUB\"#"          "${MNTPOINT}"/etc/debootstrap/config
1738
1739   # install notes:
1740   if [ -n "$INSTALL_NOTES" ] ; then
1741      [ -r "$INSTALL_NOTES" ] && cp "$INSTALL_NOTES" "${MNTPOINT}"/etc/debootstrap/
1742   fi
1743
1744   # package selection:
1745   if [ "$PACKAGES" = 'yes' ] ; then
1746     cp $VERBOSE "${_opt_packages:-$CONFFILES/packages}" \
1747       "${MNTPOINT}"/etc/debootstrap/packages
1748   fi
1749
1750   # debconf preseeding:
1751   _opt_debconf=${_opt_debconf:-$CONFFILES/debconf-selections}
1752   [ -f "${_opt_debconf}" ] && [ "$DEBCONF" = 'yes' ] && \
1753     cp $VERBOSE "${_opt_debconf}" "${MNTPOINT}"/etc/debootstrap/debconf-selections
1754
1755   # copy scripts that should be executed inside the chroot:
1756   _opt_chroot_scripts=${_opt_chroot_scripts:-$CONFFILES/chroot-scripts/}
1757   [ -d "$_opt_chroot_scripts" ] && [ "$CHROOT_SCRIPTS" = 'yes' ] && {
1758     mkdir -p "${MNTPOINT}"/etc/debootstrap/chroot-scripts
1759     cp -a $VERBOSE "${_opt_chroot_scripts}"/* "${MNTPOINT}"/etc/debootstrap/chroot-scripts/
1760   }
1761
1762   # notice: do NOT use $CHROOT_VARIABLES inside chroot but statically file instead!
1763   cp $VERBOSE "${CHROOT_VARIABLES}" "${MNTPOINT}"/etc/debootstrap/variables
1764
1765   cp $VERBOSE -a -L "${CONFFILES}"/extrapackages/ "${MNTPOINT}"/etc/debootstrap/
1766
1767   # make sure we can access network [relevant for cdebootstrap/mmdebstrap]
1768   [ -f "${MNTPOINT}"/etc/resolv.conf ] || cp $VERBOSE /etc/resolv.conf "${MNTPOINT}"/etc/resolv.conf
1769
1770   # setup default locales
1771   [ -n "$LOCALES" ] && cp $VERBOSE "${CONFFILES}"/locale.gen "${MNTPOINT}"/etc/locale.gen
1772
1773   # MAKEDEV is just a forking bomb crap, let's do it on our own instead :)
1774   ( cd "${MNTPOINT}"/dev && tar zxf /etc/debootstrap/devices.tar.gz )
1775
1776   # copy any existing files to chroot
1777   [ -d "${CONFFILES}"/bin   ] && cp $VERBOSE -a -L "${CONFFILES}"/bin/*   "${MNTPOINT}"/bin/
1778   [ -d "${CONFFILES}"/boot  ] && cp $VERBOSE -a -L "${CONFFILES}"/boot/*  "${MNTPOINT}"/boot/
1779   [ -d "${CONFFILES}"/etc   ] && cp $VERBOSE -a -L "${CONFFILES}"/etc/*   "${MNTPOINT}"/etc/
1780   [ -d "${CONFFILES}"/sbin  ] && cp $VERBOSE -a -L "${CONFFILES}"/sbin/*  "${MNTPOINT}"/sbin/
1781   [ -d "${CONFFILES}"/share ] && cp $VERBOSE -a -L "${CONFFILES}"/share/* "${MNTPOINT}"/share/
1782   [ -d "${CONFFILES}"/usr   ] && cp $VERBOSE -a -L "${CONFFILES}"/usr/*   "${MNTPOINT}"/usr/
1783   [ -d "${CONFFILES}"/var   ] && cp $VERBOSE -a -L "${CONFFILES}"/var/*   "${MNTPOINT}"/var/
1784
1785   # network setup
1786   DEFAULT_INTERFACES="# /etc/network/interfaces - generated by grml-debootstrap
1787
1788 # Include files from /etc/network/interfaces.d when using
1789 # ifupdown v0.7.44 or newer:
1790 #source-directory /etc/network/interfaces.d
1791
1792 auto lo
1793 iface lo inet loopback
1794
1795 allow-hotplug eth0
1796 iface eth0 inet dhcp
1797 "
1798
1799   # add dhcp setting for Predictable Network Interface Names
1800   if [ -x /bin/udevadm ]; then
1801     tmpfile=$(mktemp)
1802     for interface in /sys/class/net/*; do
1803       udevadm info --query=all --path="${interface}" > "${tmpfile}"
1804       # skip virtual devices, like bridges, vboxnet,...
1805       if grep -q 'P: /devices/virtual/net/' "${tmpfile}" ; then
1806         continue
1807       fi
1808
1809       # iterate over possible naming policies by precedence (see udev/net/link-config.c),
1810       # use and stop on first match to have same behavior as udev's link_config_apply()
1811       for property in ID_NET_NAME_FROM_DATABASE ID_NET_NAME_ONBOARD ID_NET_NAME_SLOT ID_NET_NAME_PATH ID_NET_NAME_MAC ; do
1812         if grep -q "${property}" "${tmpfile}" ; then
1813           interface=$(grep "${property}" "${tmpfile}" | sed -n -e "s/E: ${property}=\([^\$*]\)/\1/p")
1814           DEFAULT_INTERFACES="${DEFAULT_INTERFACES}
1815 allow-hotplug ${interface}
1816 iface ${interface} inet dhcp
1817 "
1818           break
1819         fi
1820       done
1821     done
1822     rm -f "${tmpfile}"
1823   fi
1824
1825   if [ -n "$NOINTERFACES" ] ; then
1826     einfo "Not installing /etc/network/interfaces as requested via --nointerfaces option" ; eend 0
1827   elif [ -n "$USE_DEFAULT_INTERFACES" ] ; then
1828     einfo "Installing default /etc/network/interfaces as requested via --defaultinterfaces options."
1829     mkdir -p "${MNTPOINT}/etc/network"
1830     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1831     eend $?
1832   elif [ -n "$VIRTUAL" ] ; then
1833     einfo "Setting up Virtual Machine, installing default /etc/network/interfaces"
1834     mkdir -p "${MNTPOINT}/etc/network"
1835     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1836     eend $?
1837   elif [ -r /etc/network/interfaces ] ; then
1838     einfo "Copying /etc/network/interfaces from host to target system"
1839     mkdir -p "${MNTPOINT}/etc/network"
1840     cp $VERBOSE /etc/network/interfaces "${MNTPOINT}/etc/network/interfaces"
1841     eend $?
1842   else
1843     ewarn "Couldn't read /etc/network/interfaces, installing default /etc/network/interfaces"
1844     mkdir -p "${MNTPOINT}/etc/network"
1845     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1846     eend $?
1847   fi
1848
1849   # install config file providing some example entries
1850   if [ -r /etc/network/interfaces.examples ] && [ ! -r "$MNTPOINT/etc/network/interfaces.examples" ] ; then
1851     mkdir -p "${MNTPOINT}/etc/network"
1852     cp /etc/network/interfaces.examples "$MNTPOINT/etc/network/interfaces.examples"
1853   fi
1854
1855   if [ -n "${SSHCOPYID}" ] ; then
1856     AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-$HOME/.ssh/authorized_keys}
1857     AUTHORIZED_KEYS_TARGET=${AUTHORIZED_KEYS_TARGET:-$MNTPOINT/root/.ssh/}
1858     if ssh-add -L >/dev/null 2>&1 ; then
1859       einfo "Use locally available public keys to authorise root login on the target system as requested via --sshcopyid option."
1860       mkdir -p "${MNTPOINT}"/root/.ssh
1861       chmod 0700 "${MNTPOINT}"/root/.ssh
1862       if ssh-add -L >> "${MNTPOINT}"/root/.ssh/authorized_keys ; then
1863         eend 0
1864       else
1865         eerror "Error: executing 'ssh-add -L' failed."
1866         eend 1
1867         bailout 1
1868       fi
1869     elif [ -f "$AUTHORIZED_KEYS_SOURCE" ]; then
1870       einfo "copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' as requested via --sshcopyid option."
1871       mkdir -p "$AUTHORIZED_KEYS_TARGET"
1872       chmod 0700 "$AUTHORIZED_KEYS_TARGET"
1873       if cp "$AUTHORIZED_KEYS_SOURCE" "$AUTHORIZED_KEYS_TARGET" ; then
1874         eend 0
1875       else
1876         eerror "Error: copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' failed"
1877         eend 1
1878         bailout 1
1879       fi
1880     else
1881       eerror "Error: Could not open a connection to your authentication agent or the agent has no identities."
1882       eend 1
1883       bailout 1
1884     fi
1885   fi
1886
1887   if [ -n "${SSHCOPYAUTH}" ] ; then
1888     AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-${HOME}/.ssh/authorized_keys}
1889
1890     if ! [ -f "${AUTHORIZED_KEYS_SOURCE}" ]; then
1891       eerror "Error: could not read '${AUTHORIZED_KEYS_SOURCE}' for setting up SSH key login."
1892       eend 1
1893       bailout 1
1894     fi
1895
1896     AUTHORIZED_KEYS_TARGET="${MNTPOINT}/root/.ssh/"
1897     einfo "Copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' as requested via --sshcopyauth option."
1898     mkdir -p "${AUTHORIZED_KEYS_TARGET}"
1899     chmod 0700 "${AUTHORIZED_KEYS_TARGET}"
1900     if cp "${AUTHORIZED_KEYS_SOURCE}" "${AUTHORIZED_KEYS_TARGET}" ; then
1901       eend 0
1902     else
1903       eerror "Error: copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' failed."
1904       eend 1
1905       bailout 1
1906     fi
1907   fi
1908
1909   if [ -d /run/udev ] ; then
1910     einfo "Setting up bind-mount /run/udev"
1911     mkdir -p "${MNTPOINT}"/run/udev
1912     mount --bind /run/udev "${MNTPOINT}"/run/udev
1913     eend $?
1914   fi
1915
1916   eend 0
1917 }
1918 # }}}
1919
1920 # execute all scripts in /etc/debootstrap/pre-scripts/ {{{
1921 execute_pre_scripts() {
1922   # make sure hostname is set even before chroot-script get executed
1923   echo "$HOSTNAME" > "$MNTPOINT"/etc/hostname
1924
1925   # make sure we have $MNTPOINT available for our scripts
1926   export MNTPOINT
1927
1928   if [ -d "$_opt_pre_scripts" ] || [ "$PRE_SCRIPTS" = 'yes' ] ; then
1929     [ -d "$_opt_pre_scripts" ] && pre_scripts="$_opt_pre_scripts" || pre_scripts="${CONFFILES}/pre-scripts/"
1930     for script in "${pre_scripts}"/* ; do
1931       if [ -x "$script" ] ; then
1932         einfo "Executing pre-script $script"
1933         "$script" ; eend $?
1934       fi
1935     done
1936   fi
1937 }
1938 # }}}
1939
1940 # execute all scripts in /etc/debootstrap/post-scripts/ {{{
1941 execute_post_scripts() {
1942   # make sure we have $MNTPOINT and HOSTNAME available for our scripts
1943   export MNTPOINT
1944   export TARGET_HOSTNAME=$HOSTNAME
1945
1946   if [ -d "$_opt_scripts" ] || [ "$SCRIPTS" = 'yes' ] ; then
1947     # legacy support for /etc/debootstrap/scripts/
1948     [ -d "$_opt_scripts" ] && post_scripts="$_opt_scripts" || post_scripts="${CONFFILES}/scripts/"
1949     ewarn "Deprecation NOTE: --scripts/SCRIPTS are deprecated, please switch to --post-scripts/POST_SCRIPTS instead."
1950   elif [ -d "$_opt_post_scripts" ] || [ "$POST_SCRIPTS" = 'yes' ] ; then
1951     [ -d "$_opt_post_scripts" ] && post_scripts="$_opt_post_scripts" || post_scripts="${CONFFILES}/post-scripts/"
1952   fi
1953
1954   if [ -n "$post_scripts" ] ; then
1955     for script in "${post_scripts}"/* ; do
1956       if [ -x "$script" ] ; then
1957         einfo "Executing post-script $script"
1958         "$script" ; eend $?
1959       fi
1960     done
1961   fi
1962 }
1963 # }}}
1964
1965 # unmount mountpoint {{{
1966 try_umount() {
1967   local tries=$1
1968   local mountpoint="$2"
1969
1970   for (( try=1; try<=tries; try++ )); do
1971     if [[ ${try} -eq ${tries} ]]; then
1972       # Last time, show errors this time
1973       umount "${mountpoint}" && return 0
1974     else
1975       # Not last time, hide errors until fatal
1976       if umount "${mountpoint}" 2>/dev/null ; then
1977         return 0
1978       else
1979         sleep 1
1980       fi
1981     fi
1982   done
1983   return 1  # Tried enough
1984 }
1985 # }}}
1986
1987 # execute chroot-script {{{
1988 chrootscript() {
1989   if ! [ -r "$MNTPOINT/bin/chroot-script" ] ; then
1990     mount_target
1991   fi
1992
1993   if ! [ -x "$MNTPOINT/bin/chroot-script" ] ; then
1994     eerror "Fatal: $MNTPOINT/bin/chroot-script could not be found."
1995     eend 1
1996   else
1997     einfo "Executing chroot-script now"
1998     mount -t devtmpfs udev "${MNTPOINT}"/dev
1999     mount -t devpts devpts "${MNTPOINT}"/dev/pts
2000     if [ "$DEBUG" = "true" ] ; then
2001       chroot "$MNTPOINT" /bin/bash -x /bin/chroot-script ; RC=$?
2002     else
2003       chroot "$MNTPOINT" /bin/chroot-script ; RC=$?
2004     fi
2005     try_umount 3 "$MNTPOINT"/dev/pts
2006     try_umount 3 "$MNTPOINT"/dev
2007     eend $RC
2008   fi
2009
2010   # finally get rid of chroot-script again, there's no good reason to
2011   # keep it on the installed system
2012   if grep -q GRML_CHROOT_SCRIPT_MARKER "${MNTPOINT}/bin/chroot-script" ; then
2013     einfo "Removing chroot-script again"
2014     rm -f "${MNTPOINT}/bin/chroot-script"
2015     eend $?
2016   else
2017     einfo "Keeping chroot-script as string GRML_CHROOT_SCRIPT_MARKER could not be found"
2018     eend 0
2019   fi
2020 }
2021 # }}}
2022
2023 # unmount $MNTPOINT {{{
2024 umount_chroot() {
2025
2026   # display installation notes:
2027   if [ -n "$INSTALL_NOTES" ] ; then
2028      [ -r "${MNTPOINT}/${INSTALL_NOTES}" ] && cat "${MNTPOINT}/${INSTALL_NOTES}"
2029   fi
2030
2031   if [ -n "$ISODIR" ] ; then
2032      if grep -q "$ISODIR" /proc/mounts ; then
2033         einfo "Unmount $MNTPOINT/$ISODIR"
2034         umount "$MNTPOINT/$ISODIR"
2035         eend $?
2036      fi
2037   fi
2038
2039   if grep -q "$MNTPOINT" /proc/mounts ; then
2040     if mountpoint "${MNTPOINT}"/run/udev &>/dev/null ; then
2041       einfo "Unmounting bind-mount /run/udev"
2042       umount "${MNTPOINT}"/run/udev
2043       eend $?
2044     fi
2045
2046      if [ -n "$PARTITION" ] ; then
2047         einfo "Unmount $MNTPOINT"
2048         umount "$MNTPOINT"
2049         eend $?
2050      fi
2051   fi
2052 }
2053 # }}}
2054
2055 # execute filesystem check {{{
2056 fscktool() {
2057  if [ -n "$VIRTUAL" ] ; then
2058    einfo "Skipping filesystem check because we deploy a virtual machine."
2059    return 0
2060  fi
2061
2062  if [ "$FSCK" = 'yes' ] ; then
2063    [ -n "$FSCKTOOL" ] || FSCKTOOL="fsck.${MKFS#mkfs.}"
2064    einfo "Checking filesystem on $TARGET using $FSCKTOOL"
2065    "$FSCKTOOL" "$TARGET"
2066    eend $?
2067  fi
2068 }
2069 # }}}
2070
2071 # get rid of grml-debootstrap config files {{{
2072 remove_configs() {
2073   if [ "$REMOVE_CONFIGS" != "yes" ] ; then
2074     return 0
2075   fi
2076
2077   if ! mountpoint "${MNTPOINT}" >/dev/null 2>&1 ; then
2078     ewarn "Target ${MNTPOINT} doesn't seem to be mounted, can't remove configuration files." ; eend 0
2079     return 0
2080   fi
2081
2082   einfo "Removing configuration files from installed system as requested via --remove-configs / REMOVE_CONFIGS."
2083   rm -rf "${MNTPOINT}"/etc/debootstrap/
2084   eend $?
2085 }
2086 # }}}
2087
2088 # now execute all the functions {{{
2089 for i in format_efi_partition prepare_vm mkfs tunefs \
2090          mount_target mountpoint_to_blockdevice debootstrap_system \
2091          preparechroot execute_pre_scripts chrootscript execute_post_scripts \
2092          remove_configs umount_chroot grub_install umount_target fscktool ; do
2093     if stage "${i}" ; then
2094       if "$i" ; then
2095         stage "${i}" 'done' && rm -f "${STAGES}/${i}"
2096       else
2097         bailout 2 "$i"
2098       fi
2099     fi
2100 done
2101
2102 cleanup
2103 # }}}
2104
2105 # end dialog of autoinstallation {{{
2106 if [ -n "$AUTOINSTALL" ] ; then
2107    if dialog --title "${PN}" --pause "Finished execution of ${PN}.
2108 Automatically rebooting in 10 seconds.
2109
2110 Choose Cancel to skip rebooting." 10 60 10 ; then
2111      noeject noprompt reboot
2112   fi
2113 else
2114    einfo "Finished execution of ${PN}. Enjoy your Debian system." ; eend 0
2115 fi
2116 # }}}
2117
2118 ## END OF FILE #################################################################
2119 # vim: ai tw=100 expandtab foldmethod=marker shiftwidth=2