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