Release new version 0.108
[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='bullseye'
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 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 [ "$_opt_non_free" ]            && COMPONENTS="$COMPONENTS non-free"
593
594 # command line option checks
595 if [ "$_opt_scripts_set" ] ; then
596   ewarn "Deprecation NOTE: --scripts option is deprecated, please switch to --post-scripts instead."
597   SCRIPTS='yes' # deprecated since grml-debootstrap >=0.71
598 fi
599
600 if [ "$_opt_grub" ] && [ "$_opt_vmfile" ] ; then
601   eerror "The --grub option is incompatible with --vmfile, please drop it from your command line."
602   eerror "The --grub option is unneeded as GRUB will be installed automatically."
603   eend 1
604   bailout 1
605 fi
606
607 if [ "${_opt_sshcopyid}" ] && [ "${_opt_sshcopyauth}" ] ; then
608   eerror "The --sshcopyid option is incompatible with --sshcopyauth, please drop either of them from your command line."
609   eend 1
610   bailout 1
611 fi
612
613 if [ -n "$ISO" ] && [[ "$DEBOOTSTRAP" =~ mmdebstrap$ ]] ; then
614   eerror "The ISO option is incompatible with usage of mmdebstrap for bootstrapping."
615   eerror "Either drop the --iso ... option or use plain debootstrap instead."
616   eend 1
617   bailout 1
618 fi
619
620 if [ "$DEBUG" = "true" ] ; then
621   set -x
622 fi
623
624 [ "$_opt_help" ] && {
625   usage ; eend 0
626   eend 0
627   exit 0
628 }
629
630 [ "$_opt_version" ] && {
631   einfo "$PN - version $VERSION"
632   einfo "Report bugs via https://github.com/grml/grml-debootstrap/ or https://grml.org/bugs/"
633   eend 0
634   exit 0
635 }
636 # }}}
637
638 # check for root permissions {{{
639 if ! check4root ; then
640    echo "For usage instructions please execute '$PN --help'."
641    bailout 1
642 fi
643 # }}}
644
645 # make sure we have what we need {{{
646 check4progs "${DEBOOTSTRAP}" || bailout 1
647
648 if [ -n "$VIRTUAL" ] ; then
649   check4progs kpartx parted qemu-img || bailout 1
650 fi
651 # }}}
652
653 # source specified configuration file {{{
654 if [ -n "$CONFIGFILE" ] ; then
655   einfo "Reading specified config file $CONFIGFILE."
656   # shellcheck disable=SC1091 source=config
657   if ! . "$CONFIGFILE" ; then
658     eerror "Error reading config file $CONFIGFILE" ; eend 1 ; bailout 1
659   fi
660 fi
661 # }}}
662
663 # backwards compatibility checks {{{
664 if [ -n "$GROOT" ] ; then
665    eerror "Error: you seem to have \$GROOT configured."
666    eerror "This variable is no longer supported, please visit the"
667    eerror "grml-debootstrap documentation for details."
668    eend 1
669    bailout 1
670 fi
671
672 if echo "$GRUB" | grep -q '^hd' ; then
673    eerror "Error: this syntax for the grub configuration variable is no longer supported."
674    eerror "Please do not use hd... any longer but /dev/sdX instead."
675    eend 1
676    bailout 1
677 fi
678 # }}}
679
680 # welcome screen {{{
681 welcome_dialog()
682 {
683    dialog --title "$PN" --yesno "Welcome to the interactive configuration of ${PN}.
684 Do you want to continue installing Debian using this frontend?" 0 0 || bailout 0
685 }
686 # }}}
687
688 # ask for target {{{
689 prompt_for_target()
690 {
691   AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
692                sed 's/*//' | \
693                grep -v 'Extended$' | \
694                gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}'; ls /dev/md[0-9]* 2>/dev/null || true);
695
696   if [ -z "$AVAILABLE_PARTITIONS" ] ; then
697      dialog --title "$PN" --trim \
698      --msgbox "Sorry, no partitions found. Please configure your
699      harddisks (see /proc/partitions) using a tool like fdisk,
700      cfdisk, gpart, gparted,..." 0 0
701      bailout 1
702   fi
703
704   PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
705                      fs="$(blkid -s TYPE -o value "$i" 2>/dev/null)"
706                      [ -n "$fs" ] || fs='[no_filesystem_yet]'
707                      echo "$i" "$fs"
708                      unset fs
709                    done)
710
711   # shellcheck disable=SC2086
712   TARGET=$(dialog --title "$PN" --single-quoted --stdout \
713          --menu "Please select the target partition:" 0 0 0 \
714          $PARTITION_LIST)
715   [ $? -eq 0 ] || bailout 1
716 }
717 # }}}
718
719 # ask for bootmanager {{{
720 prompt_for_bootmanager()
721 {
722   ADDITIONAL_PARAMS=""
723
724   if echo "$TARGET" | grep -q "/dev/md" ; then
725      MBRPART="all disks of Software RAID $TARGET"
726   else
727      # figure out whole disk device
728      found=
729      for device in /dev/disk/by-id/*
730      do
731         [ "$(readlink -f "$device")" = "${TARGET}" ] || continue
732         found=1
733         break
734      done
735      # shellcheck disable=SC2001
736      [ -n "$found" ] && MBRDISK=$(echo "${device}" | sed -e 's/-part[0-9][0-9]*$//')
737      if [ -e "$MBRDISK" ]; then
738         MBRDISK=$(readlink -f "$MBRDISK")
739      else
740         # fall back to old behaviour
741         # shellcheck disable=SC2001
742         MBRDISK=$(echo "${TARGET}" | sed -e 's/[0-9][0-9]*$//')
743      fi
744
745      MBRPART="MBR of $MBRDISK"
746   fi
747
748   for device in cciss/c0d0 sda hda; do
749     if [ "/dev/$device" != "${MBRDISK}" ]; then
750       grep -q $device /proc/partitions && \
751       ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS:$device:install bootmanager grub into MBR of /dev/$device"
752     fi
753   done
754   ADDITIONAL_PARAMS=${ADDITIONAL_PARAMS#:}
755
756   OIFS="$IFS"; IFS=:
757
758   # shellcheck disable=SC2086
759   GETMBR=$(dialog --stdout --title "$PN" --default-item mbr \
760           --menu "Where do you want to install the bootmanager grub?" 0 0 0 \
761             mbr       "install bootmanager into $MBRPART" \
762             nowhere   "do not install bootmanager at all" \
763           ${ADDITIONAL_PARAMS})
764   [ $? -eq 0 ] || bailout 3
765   IFS="$OIFS"
766
767   case "$GETMBR" in
768     mbr)
769       # /dev/md0: has to be installed in MBR of /dev/md0 and not in /dev/md:
770       if echo "$TARGET" | grep -q "/dev/md" ; then
771         GRUB="$TARGET"
772       else
773         GRUB="$MBRDISK"
774       fi
775       ;;
776     hda)
777       GRUB="/dev/hda"
778       ;;
779     sda)
780       GRUB="/dev/sda"
781       ;;
782     nowhere)
783       GRUB=''
784       ;;
785   esac
786 }
787 # }}}
788
789 # ask for Debian release {{{
790 prompt_for_release()
791 {
792   [ -n "$RELEASE" ] && DEFAULT_RELEASE="$RELEASE" || DEFAULT_RELEASE='bullseye'
793   RELEASE="$(dialog --stdout --title "${PN}" --default-item $DEFAULT_RELEASE --menu \
794             "Please enter the Debian release you would like to use for installation:" \
795             0 50 8 \
796             lenny    Debian/5.0 \
797             squeeze  Debian/6.0 \
798             wheezy   Debian/7.0 \
799             jessie   Debian/8.0 \
800             stretch  Debian/9.0 \
801             buster   Debian/10.0 \
802             bullseye Debian/11.0 \
803             sid      Debian/unstable)"
804   [ $? -eq 0 ] || bailout
805 }
806 # }}}
807
808 # ask for hostname {{{
809 prompt_for_hostname()
810 {
811   HOSTNAME="$(dialog --stdout --title "${PN}" --inputbox \
812             "Please enter the hostname you would like to use for installation:" \
813             0 0 "$HOSTNAME")"
814   [ $? -eq 0 ] || bailout
815 }
816 # }}}
817
818 # ask for password {{{
819 prompt_for_password()
820 {
821   if [ "$_opt_nopassword" ] ; then
822     einfo "Skip asking for root password as requested."
823     return 0
824   fi
825
826   ROOTPW1='PW1'
827   ROOTPW2='PW2'
828   while [ "$ROOTPW1" != "$ROOTPW2" ]; do
829     ROOTPW1=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
830     "Please enter the password for the root account:" 10 60)
831     [ $? -eq 0 ] || bailout
832
833     ROOTPW2=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
834     "Please enter the password for the root account again for \
835     confirmation:" 10 60)
836     [ $? -eq 0 ] || bailout
837
838     if [ "$ROOTPW1" != "$ROOTPW2" ]; then
839       dialog --stdout --title "${PN}" --ok-label \
840         "Retry" --msgbox "Passwords do not match!" 10 60
841     fi
842   done
843   ROOTPASSWORD="$ROOTPW1"
844 }
845 # }}}
846
847 # ask for Debian mirror {{{
848 prompt_for_mirror()
849 {
850   [ -n "$ISO" ] && DEFAULT_MIRROR='local' || DEFAULT_MIRROR='net'
851
852   CHOOSE_MIRROR=$(dialog --stdout --title "$PN" --default-item $DEFAULT_MIRROR \
853           --menu "Where do you want to install from?" 0 0 0 \
854             net   "install via network (downloading from mirror)" \
855             local "install from local directory/mirror"
856           )
857   [ $? -eq 0 ] || bailout
858
859   if [ "$CHOOSE_MIRROR" = 'net' ] ; then
860      [ -n "$MIRROR" ] || MIRROR='http://deb.debian.org/debian'
861      MIRROR="$(dialog --stdout --title "${PN}" --inputbox \
862                "Please enter Debian mirror you would like to use for installing packages." \
863                0 0 $MIRROR)"
864      [ $? -eq 0 ] || bailout
865   else # CHOOSE_MIRROR == local
866      [ -n "$ISO" ] || ISO='/mnt/mirror'
867      ISO="$(dialog --stdout --title "${PN}" --inputbox \
868                "Please enter directory name you would like to use for installing packages." \
869                0 0 $ISO)"
870      [ $? -eq 0 ] || bailout
871   fi
872 }
873 # }}}
874
875 # software raid setup {{{
876 config_swraid_setup()
877 {
878 TMPFILE=$(mktemp)
879
880 # Currently we support only raid1:
881 RAIDLEVEL='raid1'
882
883 MD_LIST=$(for i in $(seq 0 9) ; do
884             awk '{print $4}' /proc/partitions | grep -q "md$i" || \
885             echo "/dev/md$i /dev/md$i"
886           done)
887
888 # shellcheck disable=SC2086
889 TARGET=$(dialog --stdout --title "$PN" --default-item /dev/md0 \
890 --menu "Which device do you want to use for ${RAIDLEVEL}?
891
892 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 \
893 $MD_LIST)
894 [ $? -eq 0 ] || bailout 20
895
896 AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
897              sed 's/*//' | \
898              grep -v 'Extended$' | \
899              gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}')
900 [ -n "$AVAILABLE_PARTITIONS" ] || echo "Fatal error: no partitions available?"
901 PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
902                      echo "$i $(blkid -s TYPE -o value "$i" 2>/dev/null || echo '[no_filesystem_yet]') off"
903                  done)
904
905 # shellcheck disable=SC2086
906 dialog --title "$PN" --separate-output \
907        --checklist "Please select the partitions you would like to use for your $RAIDLEVEL on ${TARGET}:" 0 0 0 \
908        $PARTITION_LIST 2>"$TMPFILE"
909 [ $? -eq 0 ] || bailout
910 SELECTED_PARTITIONS="$(cat "$TMPFILE")"
911
912 NUM_PARTITIONS=0
913 while IFS= read -r i; do
914   NUM_PARTITIONS=$(( NUM_PARTITIONS + 1 ))
915 done < "$TMPFILE"
916
917 # force metadata version 0.90 for lenny so old grub can boot from this array.
918 METADATA_VERSION=""
919 if [ "$RELEASE" = "lenny" ]; then
920    METADATA_VERSION="-e0"
921 fi
922
923 ERRORFILE=$(mktemp)
924 # shellcheck disable=SC2086
925 yes | mdadm --create "${TARGET}" --level="${RAIDLEVEL}" \
926       --raid-devices="${NUM_PARTITIONS}" ${METADATA_VERSION} ${SELECTED_PARTITIONS} >/dev/null 2>$ERRORFILE
927 RC=$?
928 if [ "$RC" = 0 ] ; then
929    dialog --title "$PN" --msgbox \
930    "Creating $TARGET was successful." 0 0
931    rm -f "$TMPFILE" "$ERRORFILE"
932 else
933    dialog --title "$PN" --msgbox \
934    "There was an error setting up $TARGET:
935
936 $(cat "$ERRORFILE")
937
938 Exiting." 0 0
939    rm -f "$TMPFILE" "$ERRORFILE"
940    bailout 1
941 fi
942
943 }
944
945 prompt_for_swraid()
946 {
947 if dialog --stdout --title "$PN" \
948           --defaultno --yesno "Do you want to configure Software RAID?
949
950 Please notice that only RAID level 1 is supported by ${PN} currently. Configuration will take place using mdadm." 0 0 ; then
951   config_swraid_setup
952 fi
953 }
954 # }}}
955
956 # user should recheck his configuration {{{
957 # support full automatic installation:
958 checkforrun() {
959    dialog --timeout 10 --title "$PN" \
960           --yesno "Do you want to stop at this stage?
961
962 Notice: you are running ${PN} in non-interactive mode.
963 ${PN} will install Debian ${RELEASE} on ${TARGET}.
964 Last chance to quit. Timeout of 10 seconds running....
965
966 Do you want to stop now?" 0 0 2>/dev/null
967 }
968 # }}}
969
970 # format efi partition {{{
971 format_efi_partition() {
972   if [ -z "$EFI" ] ; then
973     return 0
974   fi
975
976   if ! [ -b "$EFI" ] ; then
977     eerror "Specified efi argument [$EFI] not a valid block device."
978     bailout 1
979   fi
980
981   if fsck.vfat -bn "$EFI" >/dev/null; then
982     einfo "EFI partition $EFI seems to have a FAT filesystem, not modifying." ; eend 0
983   else
984     einfo "EFI partition $EFI doesn't seem to be formatted, creating filesystem."
985     mkfs.fat -F32 -n "EFI" "$EFI"
986     RC=$?
987     if [ $RC -eq 0 ] ; then
988       eend 0
989     else
990       eerror "Error while creating filesystem on ${EFI}."
991       eend 1
992       bailout 1
993     fi
994   fi
995 }
996 # }}}
997
998 # check for EFI support or try to enable it {{{
999 efi_support() {
1000   local efivars_loaded=false
1001   # this is for kernels versions before v3.10, which didn't provide efivarfs yet
1002   if modprobe efivars &>/dev/null ; then
1003     efivars_loaded=true
1004   fi
1005   # kernel versions v3.10 and newer usually provide efivarfs
1006   if modprobe efivarfs &>/dev/null ; then
1007     efivars_loaded=true
1008   fi
1009
1010   if [ -d /sys/firmware/efi ] ; then
1011     einfo "EFI support detected." ; eend 0
1012     return 0
1013   fi
1014
1015   if ! [ -d /sys/firmware/efi ] && [ "${efivars_loaded:-}" = "true" ] ; then
1016     einfo "EFI support detected, but system seems to be running in BIOS mode."
1017   fi
1018
1019   return 1
1020 }
1021 # }}}
1022
1023 # make sure the user is aware of the used configuration {{{
1024 checkconfiguration()
1025 {
1026
1027 if efi_support ; then
1028   if [ -z "$_opt_efi" ] ; then
1029     ewarn "EFI support detected but no --efi option given, please consider enabling it." ; eend 0
1030   fi
1031 else
1032   if [ -n "$_opt_efi" ] ; then
1033      eerror "EFI option used but no EFI support detected." ; eend 0
1034      bailout 1
1035   fi
1036 fi
1037
1038 if [ -n "$AUTOINSTALL" ] ; then
1039    if checkforrun ; then
1040       eerror "Exiting as requested" ; eend 0
1041       bailout 1
1042    fi
1043 elif [ -n "$INTERACTIVE" ] ; then
1044
1045    INFOTEXT="Please recheck configuration before execution:
1046    "
1047    [ -n "$TARGET" ]  && INFOTEXT="$INFOTEXT
1048    Target:          $TARGET"
1049    [ -n "$GRUB" ]    && INFOTEXT="$INFOTEXT
1050    Install grub:    $GRUB"
1051    [ -n "$EFI" ]    && INFOTEXT="$INFOTEXT
1052    Install efi:     $EFI"
1053    [ -n "$RELEASE" ] && INFOTEXT="$INFOTEXT
1054    Using release:   $RELEASE"
1055    [ -n "$HOSTNAME" ] && INFOTEXT="$INFOTEXT
1056    Using hostname:  $HOSTNAME"
1057    [ -n "$MIRROR" ]  && INFOTEXT="$INFOTEXT
1058    Using mirror:    $MIRROR"
1059    [ -n "$ISO" ]  && INFOTEXT="$INFOTEXT
1060    Using ISO:       $ISO"
1061    [ -n "$ARCH" ]  && INFOTEXT="$INFOTEXT
1062    Using arch:      $ARCH"
1063    [ -n "$CONFFILES" ] && INFOTEXT="$INFOTEXT
1064    Config files:    $CONFFILES"
1065
1066    INFOTEXT="$INFOTEXT
1067
1068 Is this ok for you? Notice: selecting 'No' will exit ${PN}."
1069
1070    dialog --title "$PN" --no-collapse \
1071           --yesno "$INFOTEXT" 0 0
1072    [ $? -eq 0 ] || bailout 0
1073
1074 else # if not running automatic installation display configuration and prompt for execution:
1075    einfo "$PN [${VERSION}] - Please recheck configuration before execution:"
1076    echo
1077    echo "   Target:          $TARGET"
1078
1079    # do not display if MNTPOINT is the default one
1080    case "$MNTPOINT" in /mnt/debootstrap*) ;; *) echo "   Mount point:     $MNTPOINT" ;; esac
1081
1082    if [ -n "$VIRTUAL" ] ; then
1083       echo "   Install grub:    yes"
1084    else
1085      [ -n "$GRUB" ]     && echo "   Install grub:    $GRUB" || echo "   Install grub:    no"
1086      [ -n "$EFI" ]      && echo "   Install efi:     $EFI"  || echo "   Install efi:     no"
1087    fi
1088
1089    [ -n "$RELEASE" ]   && echo "   Using release:   $RELEASE"
1090    [ -n "$HOSTNAME" ]  && echo "   Using hostname:  $HOSTNAME"
1091    [ -n "$MIRROR" ]    && echo "   Using mirror:    $MIRROR"
1092    [ -n "$ISO" ]       && echo "   Using ISO:       $ISO"
1093    [ -n "$ARCH" ]      && echo "   Using arch:      $ARCH"
1094    [ -n "$CONFFILES" ] && echo "   Config files:    $CONFFILES"
1095    if [ -n "$VIRTUAL" ] ; then
1096       echo "   Deploying as Virtual Machine."
1097       if [ -n "$VMSIZE" ] && [ -n "$VMFILE" ]; then
1098          echo "   Using Virtual Disk file with size of ${VMSIZE}."
1099       fi
1100    fi
1101
1102    if [ ! -t 0 ] && [ -z "$ROOTPASSWORD" ] && [ -z "$NOPASSWORD" ] ; then
1103       echo
1104       echo "   You do not have a TTY allocated, your password will be shown in"
1105       echo "   plaintext on the terminal! If you are using SSH, try its -t option!"
1106    fi
1107
1108    echo
1109    echo "   Important! Continuing will delete all data from ${TARGET}!"
1110
1111    if [ -n "$FORCE" ] ; then
1112      einfo "Skip user acknowledgement as requested via --force option."
1113    else
1114      echo
1115      einfon "Is this ok for you? [y/N] "
1116      read -r a
1117      if ! [ "$a" = 'y' ] || [ "$a" = 'Y' ] ; then
1118         eerror "Exiting as requested." ; eend 1
1119         bailout 1
1120      fi
1121    fi
1122 fi
1123 }
1124 # }}}
1125
1126 # interactive mode {{{
1127 interactive_mode()
1128 {
1129   check4progs dialog || bailout 1
1130
1131   welcome_dialog
1132
1133   prompt_for_release
1134
1135   prompt_for_swraid
1136
1137   prompt_for_target
1138
1139   prompt_for_bootmanager
1140
1141   prompt_for_hostname
1142
1143   prompt_for_password
1144
1145   prompt_for_mirror
1146 }
1147
1148 # run interactive mode if we didn't get the according configuration yet
1149 if [ -z "$TARGET" ] || [ -n "$INTERACTIVE" ] ; then
1150    # only target might be unset, so make sure the INTERACTIVE flag is set as well
1151    INTERACTIVE=1
1152    interactive_mode
1153 fi
1154 # }}}
1155
1156 # architecture setup {{{
1157 if [ -n "$ARCH" ] ; then
1158    ARCHCMD="--arch $ARCH"
1159    ARCHINFO=" (${ARCH})"
1160 else
1161    ARCH="$(dpkg --print-architecture)"
1162    ARCHCMD="--arch $ARCH"
1163    ARCHINFO=" (${ARCH})"
1164 fi
1165
1166 if [ -z "${ARCH:-}" ] ; then
1167   eerror 'Architecture neither set (environment variable ARCH), nor could be automatically identified (using dpkg).'
1168   eerror 'Consider setting the --arch ... option.' ; eend 1
1169   bailout 1
1170 fi
1171 # }}}
1172
1173 # It is not possible to build amd64 on i686. {{{
1174 CURRENT_ARCH="$(uname -m)"
1175 if [ "$CURRENT_ARCH" != "x86_64" ] ; then
1176    if [ "$ARCH" = "amd64" ] ; then
1177       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
1178       bailout 1
1179    fi
1180 fi
1181 # }}}
1182
1183 # Support for generic release codenames is unavailable. {{{
1184 if [ "$RELEASE" = "stable" ] || [ "$RELEASE" = "testing" ] ; then
1185    eerror "Generic release codenames (stable, testing) are unsupported. \
1186 Please use specific codenames such as buster or bullseye." ; eend 1
1187    bailout 1
1188 fi
1189 # }}}
1190
1191 checkconfiguration
1192
1193 # finally make sure at least $TARGET is set [the partition for the new system] {{{
1194 if [ -n "$TARGET" ] ; then
1195    SHORT_TARGET="${TARGET##*/}"
1196 else
1197    eerror "Please adjust $CONFFILES/config or..."
1198    eerror "... use the interactive version for configuration before running ${0}" ; eend 1
1199    bailout 1
1200 fi
1201 # }}}
1202
1203 # stages setup {{{
1204 if [ -z "$STAGES" ] ; then
1205    STAGES="/var/cache/grml-debootstrap/stages_${SHORT_TARGET}"
1206    [ -d "$STAGES" ] || mkdir -p "$STAGES"
1207 fi
1208
1209 if [ -r "$STAGES"/grml-debootstrap ] ; then
1210    if grep -q 'done' "${STAGES}/grml-debootstrap" ; then
1211       eerror "Error: grml-debootstrap has been executed already, won't continue therefore."
1212       eerror "If you want to re-execute grml-debootstrap just manually remove ${STAGES}" ; eend 1
1213    fi
1214 fi
1215 # }}}
1216
1217 # partition handling {{{
1218 PARTITION=''
1219 DIRECTORY=''
1220
1221 set_target_directory(){
1222     # assume we are installing into a directory, don't run mkfs and grub related stuff therefore
1223     DIRECTORY=1
1224     MNTPOINT="$TARGET"
1225     MKFS=''
1226     TUNE2FS=''
1227     FSCK=''
1228     # make sure we normalise the path to an absolute directory name so something like:
1229     #  mkdir -p foo/a bar/a; (cd foo; grml-debootstrap -t a)&; (cd bar; grml-debootstrap -t a)&; wait
1230     # works
1231     TARGET="$(readlink -f "$TARGET")"
1232 }
1233
1234 if [ -b "$TARGET" ] || [ -n "$VIRTUAL" ] ; then
1235     PARTITION=1
1236 else
1237     # $TARGET was not detected as block device, but we do not want to create target directory in /dev/
1238     if [[ $TARGET == "/dev/"* ]]; then
1239       eerror "Error: Will not create target directory $TARGET in /dev."
1240       eerror "  Please check the partition(s) of the blockdevice."; eend 1
1241       bailout 1
1242     fi
1243     set_target_directory
1244 fi
1245 # }}}
1246
1247 # make sure we have the right syntax when using an iso image {{{
1248 if [ -n "$ISO" ] ; then
1249    case $ISO in
1250       file*) # do nothing
1251       ;;
1252       *)
1253       ISO=file:$ISO
1254       ;;
1255    esac
1256 fi
1257 ISODIR=${ISO##file:}
1258 ISODIR=${ISODIR%%/}
1259 # }}}
1260
1261 # Debian ISOs do not contain signed Release files {{{
1262 if [ -n "$ISO" ] ; then
1263     DEBOOTSTRAP_OPT="$DEBOOTSTRAP_OPT --no-check-gpg"
1264 fi
1265 # }}}
1266
1267 # create filesystem {{{
1268 mkfs() {
1269   if [ -n "$DIRECTORY" ] ; then
1270      einfo "Running grml-debootstrap on a directory, skipping mkfs stage."
1271      return 0
1272   fi
1273
1274   if grep -q "$TARGET" /proc/mounts ; then
1275     eerror "$TARGET already mounted, exiting to avoid possible damage. (Manually unmount $TARGET)" ; eend 1
1276     bailout 1
1277   fi
1278
1279   # mkfs.ext* might prompt with "/dev/sdX# contains a ext* file system
1280   # created on ... Proceed anyway? (y,n)" which we want to skip in force mode
1281   if [ -n "$MKFS" ] && [ -n "$FORCE" ] ; then
1282     case "$MKFS" in
1283       mkfs.ext*)
1284         einfo "Enabling force option (-F) for mkfs.ext* tool as requested via --force switch."
1285         MKFS_OPTS="$MKFS_OPTS -F"
1286         eend 0
1287
1288         ;;
1289     esac
1290   fi
1291
1292   # starting with e2fsprogs 1.43~WIP.2015.05.18-1 mkfs.ext4 enables the metadata_csum feature
1293   # by default, which requires a recent version of tune2fs on the target system then,
1294   # so disable this feature for older Debian releases where it's known to be unsupported
1295   if [ -n "$MKFS" ] && [ "$MKFS" = "mkfs.ext4" ] ; then
1296     case "$RELEASE" in
1297       lenny|squeeze|wheezy|jessie)
1298         # assume a more recent version if we can't identify the version via dpkg-query
1299         local e2fsprogs_version
1300         e2fsprogs_version="$(dpkg-query --show --showformat='${Version}' e2fsprogs 2>/dev/null || echo 1.44)"
1301         if [ -n "$e2fsprogs_version" ] && dpkg --compare-versions "$e2fsprogs_version" ge '1.43~WIP.2015.05.18-1' ; then
1302           einfo "Disabling metadata_csum feature for $MKFS as $RELEASE doesn't support it."
1303           MKFS_OPTS="$MKFS_OPTS -O ^metadata_csum"
1304           eend 0
1305         fi
1306         ;;
1307     esac
1308   fi
1309
1310   if [ -n "$MKFS" ] ; then
1311     einfo "Running $MKFS $MKFS_OPTS on $TARGET"
1312     # shellcheck disable=SC2086
1313     "$MKFS" $MKFS_OPTS "$TARGET" ; RC=$?
1314
1315     if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1316       if ! echo "$MKFS" | grep -q "mkfs.ext" ; then
1317         eerror "Not changing disk uuid for $TARGET because $MKFS doesn't seem to match for ext{2,3,4} file system"
1318         eend 1
1319         bailout 1
1320       else
1321         einfo "Changing disk uuid for $TARGET to fixed (non-random) value $DISK_IDENTIFIER using tune2fs"
1322         tune2fs "$TARGET" -U "$DISK_IDENTIFIER"
1323         eend $?
1324       fi
1325     fi
1326
1327     # make sure /dev/disk/by-uuid/... is up2date, otherwise grub
1328     # will fail to detect the uuid in the chroot
1329     if [ -n "$VIRTUAL" ] ; then
1330       einfo "Virtual environment doesn't require blockdev --rereadpt, skipping therefore"
1331     elif echo "$TARGET" | grep -q "/dev/md" ; then
1332       blockdev --rereadpt "${TARGET}"
1333     else
1334       # if we deploy to /dev/sdX# then let's see if /dev/sdX exists
1335       local main_device="${TARGET%%[0-9]*}"
1336       # sanity check to not try to e.g. access /dev/loop if we get /dev/loop0
1337       if [ -f "/sys/block/$(basename "${main_device}")/$(basename "${TARGET}")/dev" ] ; then
1338         blockdev --rereadpt "$main_device"
1339       else
1340         einfo "No underlying block device for $TARGET identified, skipping blockdev --rereadpt."
1341       fi
1342     fi
1343     # give the system 2 seconds, otherwise we might run into
1344     # race conditions :-/
1345     sleep 2
1346
1347     eend $RC
1348   fi
1349 }
1350 # }}}
1351
1352 # retrieve ID_FS_UUID {{{
1353 identify_target_uuid() {
1354   local device="$1"
1355
1356   if ! [ -b "$device" ] ; then
1357     return 1
1358   fi
1359
1360   eval "$(blkid -o udev "$1" 2>/dev/null)"
1361
1362   if [ -n "$ID_FS_UUID" ] ; then
1363     echo "$ID_FS_UUID"
1364   else
1365     return 1
1366   fi
1367 }
1368 # }}}
1369
1370 # identify TARGET_UUID {{{
1371 mountpoint_to_blockdevice() {
1372   TARGET_UUID=''
1373
1374   TARGET_UUID=$(identify_target_uuid "$TARGET" 2>/dev/null || true)
1375   if [ -n "$TARGET_UUID" ] ; then
1376     einfo "Identified UUID $TARGET_UUID for $TARGET"
1377     return 0
1378   fi
1379
1380   # $TARGET might be a mountpoint and not a blockdevice, search for according entry
1381   for file in /sys/block/*/*/dev ; do
1382     if grep -q "^$(mountpoint -d "${TARGET}")$" "$file" ; then
1383       local dev
1384       dev="${file%/dev}"
1385       dev="/dev/${dev##*/}"
1386       TARGET_UUID=$(identify_target_uuid "$dev" 2>/dev/null || true)
1387
1388       if [ -n "$TARGET_UUID" ] ; then
1389         einfo "Identified UUID $TARGET_UUID for $TARGET (via $file)"
1390         return 0
1391       fi
1392     fi
1393   done
1394 }
1395 # }}}
1396
1397 # modify filesystem settings {{{
1398 tunefs() {
1399   if [ -n "$TUNE2FS" ] && echo "$MKFS" | grep -q "mkfs.ext" ; then
1400      einfo "Disabling automatic filesystem check on $TARGET via tune2fs"
1401      $TUNE2FS "$TARGET"
1402      eend $?
1403   fi
1404 }
1405 # }}}
1406
1407 # mount the new partition or if it's a directory do nothing at all {{{
1408 mount_target() {
1409   if [ -n "$DIRECTORY" ] ; then
1410      einfo "Running grml-debootstrap on a directory, nothing to mount."
1411   else
1412      if grep -q "$TARGET" /proc/mounts ; then
1413         ewarn "$TARGET already mounted, continuing anyway." ; eend 0
1414      else
1415        if ! [ -d "${MNTPOINT}" ] ; then
1416           [ -n "$VIRTUAL" ] || mkdir -p "${MNTPOINT}"
1417        fi
1418        einfo "Mounting $TARGET to $MNTPOINT"
1419        mkdir -p "$MNTPOINT"
1420        mount -o rw,suid,dev "$TARGET" "$MNTPOINT"
1421        eend $?
1422      fi
1423   fi
1424   if [ -n "$ISODIR" ] ; then
1425      einfo "Mounting Debian image loopback to $MNTPOINT/$ISODIR."
1426      mkdir -p "$MNTPOINT/$ISODIR"
1427      mount --bind "$ISODIR" "$MNTPOINT/$ISODIR"
1428      eend $?
1429   fi
1430 }
1431 # }}}
1432
1433 # prepare VM image for usage with debootstrap {{{
1434 prepare_vm() {
1435   if [ -z "$VIRTUAL" ] ; then
1436      return 0 # be quiet by intention
1437   fi
1438
1439   if [ -b "$TARGET" ] && [ -n "$VMFILE" ] ; then
1440      eerror "Error: specified virtual disk target ($TARGET) is an existing block device."
1441      eend 1
1442      bailout 1
1443   fi
1444   if [ ! -b "$TARGET" ] && [ -z "$VMFILE" ] ; then
1445      eerror "Error: specified virtual disk target ($TARGET) does not exist yet."
1446      eend 1
1447      bailout 1
1448   fi
1449
1450   # make sure loop module is present and a usable loop device exists
1451   modprobe -q loop
1452   if ! losetup -f >/dev/null 2>&1; then
1453     eerror "Error finding usable loop device" ; eend 1
1454     bailout 1
1455   fi
1456
1457   # if dm-mod isn't available then kpartx will fail with
1458   # "Is device-mapper driver missing from kernel? [...]"
1459   modprobe -q dm-mod
1460   if ! grep -q 'device-mapper' /proc/misc >/dev/null 2>&1 ; then
1461     eerror "Device-mapper support missing in kernel." ; eend 1
1462     bailout 1
1463   fi
1464
1465   ORIG_TARGET="$TARGET" # store for later reuse
1466
1467   if [ -n "$VMFILE" ]; then
1468     qemu-img create -f raw "${TARGET}" "${VMSIZE}"
1469   fi
1470   parted -s "${TARGET}" 'mklabel msdos'
1471   if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1472     einfo "Adjusting disk signature to a fixed (non-random) value"
1473     MBRTMPFILE=$(mktemp)
1474     dd if="${TARGET}" of="${MBRTMPFILE}" bs=512 count=1
1475     echo -en "\\x41\\x41\\x41\\x41" | dd of="${MBRTMPFILE}" conv=notrunc seek=440 bs=1
1476     dd if="${MBRTMPFILE}" of="${TARGET}" conv=notrunc
1477     eend $?
1478   fi
1479   parted -s "${TARGET}" 'mkpart primary ext4 4MiB 100%'
1480   parted -s "${TARGET}" 'set 1 boot on'
1481
1482   DEVINFO=$(kpartx -asv "$TARGET") # e.g. 'add map loop0p1 (254:5): 0 20477 linear 7:0 3'
1483   if [ -z "${DEVINFO}" ] ; then
1484     eerror "Error setting up loopback device." ; eend 1
1485     bailout 1
1486   fi
1487
1488   # hopefully this always works as expected
1489   LOOP_PART="${DEVINFO##add map }" # 'loop0p1 (254:5): 0 20477 linear 7:0 3'
1490   LOOP_PART="${LOOP_PART// */}"    # 'loop0p1'
1491   LOOP_DISK="${LOOP_PART%p*}"      # 'loop0'
1492   export TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop1p1'
1493
1494   if [ -z "$TARGET" ] ; then
1495      eerror "Error: target could not be set to according /dev/mapper/* device." ; eend 1
1496      bailout 1
1497   fi
1498 }
1499 # }}}
1500
1501 # make VM image bootable {{{
1502 grub_install() {
1503   if [ -z "${VIRTUAL}" ] ; then
1504      return 0
1505   fi
1506   if [ "${GRUB_INSTALL}" != "yes" ] ; then
1507     einfo "Not installing GRUB as requested via \$GRUB_INSTALL=$GRUB_INSTALL"
1508     return 0
1509   fi
1510
1511   if ! mount "${TARGET}" "${MNTPOINT}" ; then
1512     eerror "Error: Mounting ${TARGET} failed, can not continue." ; eend 1
1513     bailout 1
1514   fi
1515
1516   mount -t proc none "${MNTPOINT}"/proc
1517   mount -t sysfs none "${MNTPOINT}"/sys
1518   mount -t devtmpfs udev "${MNTPOINT}"/dev
1519   mount -t devpts devpts "${MNTPOINT}"/dev/pts
1520
1521 # Has chroot-script installed GRUB to MBR using grub-install (successfully), already?
1522 # chroot-script skips installation for unset ${GRUB}
1523 if [[ -z "${GRUB}" ]] || ! dd if="${GRUB}" bs=512 count=1 2>/dev/null | cat -v | grep -Fq GRUB; then
1524   einfo "Installing Grub as bootloader."
1525
1526   if ! chroot "${MNTPOINT}" dpkg --list grub-pc 2>/dev/null | grep -q '^ii' ; then
1527     echo "Notice: grub-pc package not present yet, installing it therefore."
1528     # shellcheck disable=SC2086
1529     DEBIAN_FRONTEND=$DEBIAN_FRONTEND chroot "$MNTPOINT" apt-get -y --no-install-recommends install $DPKG_OPTIONS grub-pc
1530   fi
1531
1532   mkdir -p "${MNTPOINT}/boot/grub"
1533   if ! [ -d "${MNTPOINT}"/usr/lib/grub/i386-pc/ ] ; then
1534      eerror "Error: grub not installed inside Virtual Machine. Can not install bootloader." ; eend 1
1535      bailout 1
1536   fi
1537
1538   case "$RELEASE" in
1539     lenny|squeeze|wheezy)
1540       cp "${MNTPOINT}"/usr/lib/grub/i386-pc/* "${MNTPOINT}/boot/grub/"
1541       ;;
1542     *)
1543       cp -a "${MNTPOINT}"/usr/lib/grub/i386-pc "${MNTPOINT}/boot/grub/"
1544       ;;
1545   esac
1546   dd if="${MNTPOINT}/usr/lib/grub/i386-pc/boot.img" of="${ORIG_TARGET}" conv=notrunc bs=440 count=1
1547   case "${_opt_filesystem}" in
1548     f2fs)
1549       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos f2fs
1550       ;;
1551     xfs)
1552       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos xfs
1553       ;;
1554     # NOTE - we might need to distinguish between further filesystems
1555     *)
1556       chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos ext2
1557       ;;
1558   esac
1559
1560   dd if="${MNTPOINT}/tmp/core.img" of="${ORIG_TARGET}" conv=notrunc seek=1
1561   rm -f "${MNTPOINT}/tmp/core.img"
1562 fi
1563
1564   # workaround for Debian bug #918590 with lvm + udev:
1565   # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
1566   if [ -d /run/udev ] ; then
1567     einfo "Setting up bind-mount /run/udev"
1568     mkdir -p "${MNTPOINT}"/run/udev
1569     mount --bind /run/udev "${MNTPOINT}"/run/udev
1570     eend $?
1571   fi
1572
1573   einfo "Updating grub configuration file."
1574   chroot "${MNTPOINT}" update-grub
1575
1576   case "$RELEASE" in
1577     jessie)
1578       einfo "Applying workaround for GRUB font path bug in jessie (Debian #787685)."
1579       mkdir -p "${MNTPOINT}/boot/grub/fonts/"
1580       cp "${MNTPOINT}/usr/share/grub/unicode.pf2" "${MNTPOINT}/boot/grub/fonts/"
1581       ;;
1582   esac
1583
1584   if grep -q '^GRUB_DISABLE_LINUX_UUID=.*true' "${MNTPOINT}"/etc/default/grub 2>/dev/null ; then
1585     ewarn "GRUB_DISABLE_LINUX_UUID is set to true in /etc/default/grub, not adjusting root= in grub.cfg."
1586     ewarn "Please note that your system might NOT be able to properly boot."
1587   else
1588     einfo "Adjusting grub.cfg for successful boot sequence."
1589     sed -i "s;root=[^ ]\\+;root=UUID=$TARGET_UUID;" "${MNTPOINT}"/boot/grub/grub.cfg
1590   fi
1591
1592   # workaround for Debian bug #918590 with lvm + udev:
1593   # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
1594   if mountpoint "${MNTPOINT}"/run/udev &>/dev/null ; then
1595     einfo "Unmounting bind-mount /run/udev"
1596     umount "${MNTPOINT}"/run/udev
1597     eend $?
1598   fi
1599
1600   umount "${MNTPOINT}"/proc
1601   umount "${MNTPOINT}"/sys
1602   umount "${MNTPOINT}"/dev/pts
1603   try_umount 3 "${MNTPOINT}"/dev
1604
1605 }
1606 # }}}
1607
1608 # unmount VM image {{{
1609 umount_target() {
1610   if [ -z "${VIRTUAL}" ] ; then
1611      return 0
1612   fi
1613
1614   umount "${MNTPOINT}"
1615   kpartx -d "${ORIG_TARGET}" >/dev/null
1616   # Workaround for a bug in kpartx which doesn't clean up properly,
1617   # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
1618   if dmsetup ls | grep -q "^${LOOP_PART} "; then
1619     kpartx -d "/dev/${LOOP_DISK}" >/dev/null
1620   fi
1621 }
1622 # }}}
1623
1624 # install main chroot {{{
1625 debootstrap_system() {
1626   if [ "$_opt_nodebootstrap" ]; then
1627      einfo "Skipping debootstrap as requested."
1628      return
1629   fi
1630
1631   if grep -q "$MNTPOINT" /proc/mounts || [ -n "$DIRECTORY" ] ; then
1632     :
1633   else
1634     eerror "Error: $MNTPOINT not mounted, can not continue."
1635     eend 1 ; exit 1
1636   fi
1637
1638   if [ -n "$ISO" ] ; then
1639     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${ISO}"
1640     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $ISO"
1641     # shellcheck disable=SC2086
1642     "$DEBOOTSTRAP" $ARCHCMD $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$ISO"
1643     RC=$?
1644   else
1645     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${MIRROR}"
1646     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $MIRROR"
1647     # shellcheck disable=SC2086
1648     "$DEBOOTSTRAP" $ARCHCMD $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$MIRROR"
1649     RC=$?
1650   fi
1651
1652   if [ $RC -ne 0 ] ; then
1653     if [ -r "$MNTPOINT/debootstrap/debootstrap.log" ] && \
1654       [ -s "$MNTPOINT/debootstrap/debootstrap.log" ] ; then
1655       einfo "Presenting last ten lines of debootstrap.log:"
1656       tail -10 "${MNTPOINT}"/debootstrap/debootstrap.log
1657       einfo "End of debootstrap.log"
1658     fi
1659   fi
1660
1661   eend $RC
1662 }
1663 # }}}
1664
1665 # prepare chroot via chroot-script {{{
1666 preparechroot() {
1667   einfo "Preparing chroot system"
1668
1669   # provide variables to chroot system
1670   CHROOT_VARIABLES="/var/cache/grml-debootstrap/variables_${SHORT_TARGET}"
1671   touch "$CHROOT_VARIABLES"
1672   chmod 600 "$CHROOT_VARIABLES" # make sure nobody except root can read it
1673   echo "# Configuration of ${PN}"                                                                                   > "$CHROOT_VARIABLES"
1674   # Resorting to sed(1) for escaping since "VAR='${VAR//\'/\'\\\'\'}'" does not work with all versions of Bash,
1675   #   e.g. not with 4.2.37(1)-release (a.k.a 4.2+dfsg-0.1+deb7u3) of Debian wheezy
1676   [ -n "$ARCH" ]                && echo "ARCH='$(sed "s,','\\\\'',g" <<<"${ARCH}")'"                               >> "$CHROOT_VARIABLES"
1677   [ -n "$BACKPORTREPOS" ]       && echo "BACKPORTREPOS='$(sed "s,','\\\\'',g" <<<"${BACKPORTREPOS}")'"             >> "$CHROOT_VARIABLES"
1678   [ -n "$BOOT_APPEND" ]         && echo "BOOT_APPEND='$(sed "s,','\\\\'',g" <<<"${BOOT_APPEND}")'"                 >> "$CHROOT_VARIABLES"
1679   [ -n "$CHROOT_SCRIPTS" ]      && echo "CHROOT_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${CHROOT_SCRIPTS}")'"           >> "$CHROOT_VARIABLES"
1680   [ -n "$COMPONENTS" ]          && echo "COMPONENTS='$(sed "s,','\\\\'',g" <<<"${COMPONENTS}")'"                   >> "$CHROOT_VARIABLES"
1681   [ -n "$CONFFILES" ]           && echo "CONFFILES='$(sed "s,','\\\\'',g" <<<"${CONFFILES}")'"                     >> "$CHROOT_VARIABLES"
1682   [ -n "$DEBCONF" ]             && echo "DEBCONF='$(sed "s,','\\\\'',g" <<<"${DEBCONF}")'"                         >> "$CHROOT_VARIABLES"
1683   [ -n "$DEBIAN_FRONTEND" ]     && echo "DEBIAN_FRONTEND='$(sed "s,','\\\\'',g" <<<"${DEBIAN_FRONTEND}")'"         >> "$CHROOT_VARIABLES"
1684   [ -n "$DEBOOTSTRAP" ]         && echo "DEBOOTSTRAP='$(sed "s,','\\\\'',g" <<<"${DEBOOTSTRAP}")'"                 >> "$CHROOT_VARIABLES"
1685   [ -n "$DEFAULT_LOCALES" ]     && echo "DEFAULT_LOCALES='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LOCALES}")'"         >> "$CHROOT_VARIABLES"
1686   [ -n "$DEFAULT_LANGUAGE" ]    && echo "DEFAULT_LANGUAGE='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LANGUAGE}")'"       >> "$CHROOT_VARIABLES"
1687   [ -n "$EXTRAPACKAGES" ]       && echo "EXTRAPACKAGES='$(sed "s,','\\\\'',g" <<<"${EXTRAPACKAGES}")'"             >> "$CHROOT_VARIABLES"
1688   [ -n "$EFI" ]                 && echo "EFI='$(sed "s,','\\\\'',g" <<<"${EFI}")'"                                 >> "$CHROOT_VARIABLES"
1689   [ -n "$FALLBACK_MIRROR" ]     && echo "FALLBACK_MIRROR='$(sed "s,','\\\\'',g" <<<"${FALLBACK_MIRROR}")'"         >> "$CHROOT_VARIABLES"
1690   [ -n "$FILESYSTEM" ]          && echo "FILESYSTEM='$(sed "s,','\\\\'',g" <<<"${FILESYSTEM}")'"                   >> "$CHROOT_VARIABLES"
1691   [ -n "$FORCE" ]               && echo "FORCE='$(sed "s,','\\\\'',g" <<<"${FORCE}")'"                             >> "$CHROOT_VARIABLES"
1692   [ -n "$GRMLREPOS" ]           && echo "GRMLREPOS='$(sed "s,','\\\\'',g" <<<"${GRMLREPOS}")'"                     >> "$CHROOT_VARIABLES"
1693   [ -n "$GRUB" ]                && echo "GRUB='$(sed "s,','\\\\'',g" <<<"${GRUB}")'"                               >> "$CHROOT_VARIABLES"
1694   [ -n "$HOSTNAME" ]            && echo "HOSTNAME='$(sed "s,','\\\\'',g" <<<"${HOSTNAME}")'"                       >> "$CHROOT_VARIABLES"
1695   [ -n "$INITRD" ]              && echo "INITRD='$(sed "s,','\\\\'',g" <<<"${INITRD}")'"                           >> "$CHROOT_VARIABLES"
1696   [ -n "$INITRD_GENERATOR" ]    && echo "INITRD_GENERATOR='$(sed "s,','\\\\'',g" <<<"${INITRD_GENERATOR}")'"       >> "$CHROOT_VARIABLES"
1697   [ -n "$INITRD_GENERATOR_OPTS" ] && echo "INITRD_GENERATOR_OPTS='$(sed "s,','\\\\'',g" <<<"${INITRD_GENERATOR_OPTS}")'" >> "$CHROOT_VARIABLES"
1698   [ -n "$INSTALL_NOTES" ]       && echo "INSTALL_NOTES='$(sed "s,','\\\\'',g" <<<"${INSTALL_NOTES}")'"             >> "$CHROOT_VARIABLES"
1699   [ -n "$ISODIR" ]              && echo "ISODIR='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                              >> "$CHROOT_VARIABLES"
1700   [ -n "$ISO" ]                 && echo "ISO='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                                 >> "$CHROOT_VARIABLES"
1701   [ -n "$KEEP_SRC_LIST" ]       && echo "KEEP_SRC_LIST='$(sed "s,','\\\\'',g" <<<"${KEEP_SRC_LIST}")'"             >> "$CHROOT_VARIABLES"
1702   [ -n "$LOCALES" ]             && echo "LOCALES='$(sed "s,','\\\\'',g" <<<"${LOCALES}")'"                         >> "$CHROOT_VARIABLES"
1703   [ -n "$MIRROR" ]              && echo "MIRROR='$(sed "s,','\\\\'',g" <<<"${MIRROR}")'"                           >> "$CHROOT_VARIABLES"
1704   [ -n "$MKFS" ]                && echo "MKFS='$(sed "s,','\\\\'',g" <<<"${MKFS}")'"                               >> "$CHROOT_VARIABLES"
1705   [ -n "$NOPASSWORD" ]          && echo "NOPASSWORD=\"true\""                                                      >> "$CHROOT_VARIABLES"
1706   [ -n "$NOKERNEL" ]            && echo "NOKERNEL=\"true\""                                                        >> "$CHROOT_VARIABLES"
1707   [ -n "$PACKAGES" ]            && echo "PACKAGES='$(sed "s,','\\\\'',g" <<<"${PACKAGES}")'"                       >> "$CHROOT_VARIABLES"
1708   [ -n "$POST_SCRIPTS" ]        && echo "POST_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${POST_SCRIPTS}")'"               >> "$CHROOT_VARIABLES"
1709   [ -n "$PRE_SCRIPTS" ]         && echo "PRE_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${PRE_SCRIPTS}")'"                 >> "$CHROOT_VARIABLES"
1710   [ -n "$RECONFIGURE" ]         && echo "RECONFIGURE='$(sed "s,','\\\\'',g" <<<"${RECONFIGURE}")'"                 >> "$CHROOT_VARIABLES"
1711   [ -n "$RELEASE" ]             && echo "RELEASE='$(sed "s,','\\\\'',g" <<<"${RELEASE}")'"                         >> "$CHROOT_VARIABLES"
1712   [ -n "$RM_APTCACHE" ]         && echo "RM_APTCACHE='$(sed "s,','\\\\'',g" <<<"${RM_APTCACHE}")'"                 >> "$CHROOT_VARIABLES"
1713   [ -n "$ROOTPASSWORD" ]        && echo "ROOTPASSWORD='$(sed "s,','\\\\'',g" <<<"${ROOTPASSWORD}")'"               >> "$CHROOT_VARIABLES"
1714   [ -n "$SCRIPTS" ]             && echo "SCRIPTS='$(sed "s,','\\\\'',g" <<<"${SCRIPTS}")'"                         >> "$CHROOT_VARIABLES"
1715   [ -n "$SECURE" ]              && echo "SECURE='$(sed "s,','\\\\'',g" <<<"${SECURE}")'"                           >> "$CHROOT_VARIABLES"
1716   [ -n "$SELECTED_PARTITIONS" ] && echo "SELECTED_PARTITIONS='$(sed "s,','\\\\'',g" <<<"${SELECTED_PARTITIONS}")'" >> "$CHROOT_VARIABLES"
1717   [ -n "$TARGET" ]              && echo "TARGET='$(sed "s,','\\\\'',g" <<<"${TARGET}")'"                           >> "$CHROOT_VARIABLES"
1718   [ -n "$UPGRADE_SYSTEM" ]      && echo "UPGRADE_SYSTEM='$(sed "s,','\\\\'',g" <<<"${UPGRADE_SYSTEM}")'"           >> "$CHROOT_VARIABLES"
1719   [ -n "$TARGET_UUID" ]         && echo "TARGET_UUID='$(sed "s,','\\\\'',g" <<<"${TARGET_UUID}")'"                 >> "$CHROOT_VARIABLES"
1720   [ -n "$TIMEZONE" ]            && echo "TIMEZONE='$(sed "s,','\\\\'',g" <<<"${TIMEZONE}")'"                       >> "$CHROOT_VARIABLES"
1721   [ -n "$TUNE2FS" ]             && echo "TUNE2FS='$(sed "s,','\\\\'',g" <<<"${TUNE2FS}")'"                         >> "$CHROOT_VARIABLES"
1722   [ -n "$VMSIZE" ]              && echo "VMSIZE='$(sed "s,','\\\\'',g" <<<"${VMSIZE}")'"                           >> "$CHROOT_VARIABLES"
1723
1724   cp $VERBOSE "${CONFFILES}"/chroot-script "${MNTPOINT}"/bin/chroot-script
1725   chmod 755 "${MNTPOINT}"/bin/chroot-script
1726   [ -d "$MNTPOINT"/etc/debootstrap/ ] || mkdir "$MNTPOINT"/etc/debootstrap/
1727
1728   # make sure we have our files for later use via chroot-script
1729   cp $VERBOSE "${CONFFILES}/config"           "${MNTPOINT}"/etc/debootstrap/
1730   # make sure we adjust the configuration variables accordingly:
1731   sed -i "s#RELEASE=.*#RELEASE=\"$RELEASE\"#" "${MNTPOINT}"/etc/debootstrap/config
1732   sed -i "s#TARGET=.*#TARGET=\"$TARGET\"#"    "${MNTPOINT}"/etc/debootstrap/config
1733   sed -i "s#GRUB=.*#GRUB=\"$GRUB\"#"          "${MNTPOINT}"/etc/debootstrap/config
1734
1735   # install notes:
1736   if [ -n "$INSTALL_NOTES" ] ; then
1737      [ -r "$INSTALL_NOTES" ] && cp "$INSTALL_NOTES" "${MNTPOINT}"/etc/debootstrap/
1738   fi
1739
1740   # package selection:
1741   if [ "$PACKAGES" = 'yes' ] ; then
1742     cp $VERBOSE "${_opt_packages:-$CONFFILES/packages}" \
1743       "${MNTPOINT}"/etc/debootstrap/packages
1744   fi
1745
1746   # debconf preseeding:
1747   _opt_debconf=${_opt_debconf:-$CONFFILES/debconf-selections}
1748   [ -f "${_opt_debconf}" ] && [ "$DEBCONF" = 'yes' ] && \
1749     cp $VERBOSE "${_opt_debconf}" "${MNTPOINT}"/etc/debootstrap/debconf-selections
1750
1751   # copy scripts that should be executed inside the chroot:
1752   _opt_chroot_scripts=${_opt_chroot_scripts:-$CONFFILES/chroot-scripts/}
1753   [ -d "$_opt_chroot_scripts" ] && [ "$CHROOT_SCRIPTS" = 'yes' ] && {
1754     mkdir -p "${MNTPOINT}"/etc/debootstrap/chroot-scripts
1755     cp -a $VERBOSE "${_opt_chroot_scripts}"/* "${MNTPOINT}"/etc/debootstrap/chroot-scripts/
1756   }
1757
1758   # notice: do NOT use $CHROOT_VARIABLES inside chroot but statically file instead!
1759   cp $VERBOSE "${CHROOT_VARIABLES}" "${MNTPOINT}"/etc/debootstrap/variables
1760
1761   cp $VERBOSE -a -L "${CONFFILES}"/extrapackages/ "${MNTPOINT}"/etc/debootstrap/
1762
1763   # make sure we can access network [relevant for cdebootstrap/mmdebstrap]
1764   [ -f "${MNTPOINT}"/etc/resolv.conf ] || cp $VERBOSE /etc/resolv.conf "${MNTPOINT}"/etc/resolv.conf
1765
1766   # setup default locales
1767   [ -n "$LOCALES" ] && cp $VERBOSE "${CONFFILES}"/locale.gen "${MNTPOINT}"/etc/locale.gen
1768
1769   # MAKEDEV is just a forking bomb crap, let's do it on our own instead :)
1770   ( cd "${MNTPOINT}"/dev && tar zxf /etc/debootstrap/devices.tar.gz )
1771
1772   # copy any existing files to chroot
1773   [ -d "${CONFFILES}"/bin   ] && cp $VERBOSE -a -L "${CONFFILES}"/bin/*   "${MNTPOINT}"/bin/
1774   [ -d "${CONFFILES}"/boot  ] && cp $VERBOSE -a -L "${CONFFILES}"/boot/*  "${MNTPOINT}"/boot/
1775   [ -d "${CONFFILES}"/etc   ] && cp $VERBOSE -a -L "${CONFFILES}"/etc/*   "${MNTPOINT}"/etc/
1776   [ -d "${CONFFILES}"/sbin  ] && cp $VERBOSE -a -L "${CONFFILES}"/sbin/*  "${MNTPOINT}"/sbin/
1777   [ -d "${CONFFILES}"/share ] && cp $VERBOSE -a -L "${CONFFILES}"/share/* "${MNTPOINT}"/share/
1778   [ -d "${CONFFILES}"/usr   ] && cp $VERBOSE -a -L "${CONFFILES}"/usr/*   "${MNTPOINT}"/usr/
1779   [ -d "${CONFFILES}"/var   ] && cp $VERBOSE -a -L "${CONFFILES}"/var/*   "${MNTPOINT}"/var/
1780
1781   # network setup
1782   DEFAULT_INTERFACES="# /etc/network/interfaces - generated by grml-debootstrap
1783
1784 # Include files from /etc/network/interfaces.d when using
1785 # ifupdown v0.7.44 or newer:
1786 #source-directory /etc/network/interfaces.d
1787
1788 auto lo
1789 iface lo inet loopback
1790
1791 allow-hotplug eth0
1792 iface eth0 inet dhcp
1793 "
1794
1795   # add dhcp setting for Predictable Network Interface Names
1796   if [ -x /bin/udevadm ]; then
1797     tmpfile=$(mktemp)
1798     for interface in /sys/class/net/*; do
1799       udevadm info --query=all --path="${interface}" > "${tmpfile}"
1800       # skip virtual devices, like bridges, vboxnet,...
1801       if grep -q 'P: /devices/virtual/net/' "${tmpfile}" ; then
1802         continue
1803       fi
1804
1805       # iterate over possible naming policies by precedence (see udev/net/link-config.c),
1806       # use and stop on first match to have same behavior as udev's link_config_apply()
1807       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
1808         if grep -q "${property}" "${tmpfile}" ; then
1809           interface=$(grep "${property}" "${tmpfile}" | sed -n -e "s/E: ${property}=\([^\$*]\)/\1/p")
1810           DEFAULT_INTERFACES="${DEFAULT_INTERFACES}
1811 allow-hotplug ${interface}
1812 iface ${interface} inet dhcp
1813 "
1814           break
1815         fi
1816       done
1817     done
1818     rm -f "${tmpfile}"
1819   fi
1820
1821   if [ -n "$NOINTERFACES" ] ; then
1822     einfo "Not installing /etc/network/interfaces as requested via --nointerfaces option" ; eend 0
1823   elif [ -n "$USE_DEFAULT_INTERFACES" ] ; then
1824     einfo "Installing default /etc/network/interfaces as requested via --defaultinterfaces options."
1825     mkdir -p "${MNTPOINT}/etc/network"
1826     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1827     eend $?
1828   elif [ -n "$VIRTUAL" ] ; then
1829     einfo "Setting up Virtual Machine, installing default /etc/network/interfaces"
1830     mkdir -p "${MNTPOINT}/etc/network"
1831     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1832     eend $?
1833   elif [ -r /etc/network/interfaces ] ; then
1834     einfo "Copying /etc/network/interfaces from host to target system"
1835     mkdir -p "${MNTPOINT}/etc/network"
1836     cp $VERBOSE /etc/network/interfaces "${MNTPOINT}/etc/network/interfaces"
1837     eend $?
1838   else
1839     ewarn "Couldn't read /etc/network/interfaces, installing default /etc/network/interfaces"
1840     mkdir -p "${MNTPOINT}/etc/network"
1841     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1842     eend $?
1843   fi
1844
1845   # install config file providing some example entries
1846   if [ -r /etc/network/interfaces.examples ] && [ ! -r "$MNTPOINT/etc/network/interfaces.examples" ] ; then
1847     mkdir -p "${MNTPOINT}/etc/network"
1848     cp /etc/network/interfaces.examples "$MNTPOINT/etc/network/interfaces.examples"
1849   fi
1850
1851   if [ -n "${SSHCOPYID}" ] ; then
1852     AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-$HOME/.ssh/authorized_keys}
1853     AUTHORIZED_KEYS_TARGET=${AUTHORIZED_KEYS_TARGET:-$MNTPOINT/root/.ssh/}
1854     if ssh-add -L >/dev/null 2>&1 ; then
1855       einfo "Use locally available public keys to authorise root login on the target system as requested via --sshcopyid option."
1856       mkdir -p "${MNTPOINT}"/root/.ssh
1857       chmod 0700 "${MNTPOINT}"/root/.ssh
1858       if ssh-add -L >> "${MNTPOINT}"/root/.ssh/authorized_keys ; then
1859         eend 0
1860       else
1861         eerror "Error: executing 'ssh-add -L' failed."
1862         eend 1
1863         bailout 1
1864       fi
1865     elif [ -f "$AUTHORIZED_KEYS_SOURCE" ]; then
1866       einfo "copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' as requested via --sshcopyid option."
1867       mkdir -p "$AUTHORIZED_KEYS_TARGET"
1868       chmod 0700 "$AUTHORIZED_KEYS_TARGET"
1869       if cp "$AUTHORIZED_KEYS_SOURCE" "$AUTHORIZED_KEYS_TARGET" ; then
1870         eend 0
1871       else
1872         eerror "Error: copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' failed"
1873         eend 1
1874         bailout 1
1875       fi
1876     else
1877       eerror "Error: Could not open a connection to your authentication agent or the agent has no identities."
1878       eend 1
1879       bailout 1
1880     fi
1881   fi
1882
1883   if [ -n "${SSHCOPYAUTH}" ] ; then
1884     AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-${HOME}/.ssh/authorized_keys}
1885
1886     if ! [ -f "${AUTHORIZED_KEYS_SOURCE}" ]; then
1887       eerror "Error: could not read '${AUTHORIZED_KEYS_SOURCE}' for setting up SSH key login."
1888       eend 1
1889       bailout 1
1890     fi
1891
1892     AUTHORIZED_KEYS_TARGET="${MNTPOINT}/root/.ssh/"
1893     einfo "Copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' as requested via --sshcopyauth option."
1894     mkdir -p "${AUTHORIZED_KEYS_TARGET}"
1895     chmod 0700 "${AUTHORIZED_KEYS_TARGET}"
1896     if cp "${AUTHORIZED_KEYS_SOURCE}" "${AUTHORIZED_KEYS_TARGET}" ; then
1897       eend 0
1898     else
1899       eerror "Error: copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' failed."
1900       eend 1
1901       bailout 1
1902     fi
1903   fi
1904
1905   if [ -d /run/udev ] ; then
1906     einfo "Setting up bind-mount /run/udev"
1907     mkdir -p "${MNTPOINT}"/run/udev
1908     mount --bind /run/udev "${MNTPOINT}"/run/udev
1909     eend $?
1910   fi
1911
1912   eend 0
1913 }
1914 # }}}
1915
1916 # execute all scripts in /etc/debootstrap/pre-scripts/ {{{
1917 execute_pre_scripts() {
1918   # make sure hostname is set even before chroot-script get executed
1919   echo "$HOSTNAME" > "$MNTPOINT"/etc/hostname
1920
1921   # make sure we have $MNTPOINT available for our scripts
1922   export MNTPOINT
1923
1924   if [ -d "$_opt_pre_scripts" ] || [ "$PRE_SCRIPTS" = 'yes' ] ; then
1925     [ -d "$_opt_pre_scripts" ] && pre_scripts="$_opt_pre_scripts" || pre_scripts="${CONFFILES}/pre-scripts/"
1926     for script in "${pre_scripts}"/* ; do
1927       if [ -x "$script" ] ; then
1928         einfo "Executing pre-script $script"
1929         "$script" ; eend $?
1930       fi
1931     done
1932   fi
1933 }
1934 # }}}
1935
1936 # execute all scripts in /etc/debootstrap/post-scripts/ {{{
1937 execute_post_scripts() {
1938   # make sure we have $MNTPOINT and HOSTNAME available for our scripts
1939   export MNTPOINT
1940   export TARGET_HOSTNAME=$HOSTNAME
1941
1942   if [ -d "$_opt_scripts" ] || [ "$SCRIPTS" = 'yes' ] ; then
1943     # legacy support for /etc/debootstrap/scripts/
1944     [ -d "$_opt_scripts" ] && post_scripts="$_opt_scripts" || post_scripts="${CONFFILES}/scripts/"
1945     ewarn "Deprecation NOTE: --scripts/SCRIPTS are deprecated, please switch to --post-scripts/POST_SCRIPTS instead."
1946   elif [ -d "$_opt_post_scripts" ] || [ "$POST_SCRIPTS" = 'yes' ] ; then
1947     [ -d "$_opt_post_scripts" ] && post_scripts="$_opt_post_scripts" || post_scripts="${CONFFILES}/post-scripts/"
1948   fi
1949
1950   if [ -n "$post_scripts" ] ; then
1951     for script in "${post_scripts}"/* ; do
1952       if [ -x "$script" ] ; then
1953         einfo "Executing post-script $script"
1954         "$script" ; eend $?
1955       fi
1956     done
1957   fi
1958 }
1959 # }}}
1960
1961 # unmount mountpoint {{{
1962 try_umount() {
1963   local tries=$1
1964   local mountpoint="$2"
1965
1966   for (( try=1; try<=tries; try++ )); do
1967     if [[ ${try} -eq ${tries} ]]; then
1968       # Last time, show errors this time
1969       umount "${mountpoint}" && return 0
1970     else
1971       # Not last time, hide errors until fatal
1972       if umount "${mountpoint}" 2>/dev/null ; then
1973         return 0
1974       else
1975         sleep 1
1976       fi
1977     fi
1978   done
1979   return 1  # Tried enough
1980 }
1981 # }}}
1982
1983 # execute chroot-script {{{
1984 chrootscript() {
1985   if ! [ -r "$MNTPOINT/bin/chroot-script" ] ; then
1986     mount_target
1987   fi
1988
1989   if ! [ -x "$MNTPOINT/bin/chroot-script" ] ; then
1990     eerror "Fatal: $MNTPOINT/bin/chroot-script could not be found."
1991     eend 1
1992   else
1993     einfo "Executing chroot-script now"
1994     mount -t devtmpfs udev "${MNTPOINT}"/dev
1995     mount -t devpts devpts "${MNTPOINT}"/dev/pts
1996     if [ "$DEBUG" = "true" ] ; then
1997       chroot "$MNTPOINT" /bin/bash -x /bin/chroot-script ; RC=$?
1998     else
1999       chroot "$MNTPOINT" /bin/chroot-script ; RC=$?
2000     fi
2001     try_umount 3 "$MNTPOINT"/dev/pts
2002     try_umount 3 "$MNTPOINT"/dev
2003     eend $RC
2004   fi
2005
2006   # finally get rid of chroot-script again, there's no good reason to
2007   # keep it on the installed system
2008   if grep -q GRML_CHROOT_SCRIPT_MARKER "${MNTPOINT}/bin/chroot-script" ; then
2009     einfo "Removing chroot-script again"
2010     rm -f "${MNTPOINT}/bin/chroot-script"
2011     eend $?
2012   else
2013     einfo "Keeping chroot-script as string GRML_CHROOT_SCRIPT_MARKER could not be found"
2014     eend 0
2015   fi
2016 }
2017 # }}}
2018
2019 # unmount $MNTPOINT {{{
2020 umount_chroot() {
2021
2022   # display installation notes:
2023   if [ -n "$INSTALL_NOTES" ] ; then
2024      [ -r "${MNTPOINT}/${INSTALL_NOTES}" ] && cat "${MNTPOINT}/${INSTALL_NOTES}"
2025   fi
2026
2027   if [ -n "$ISODIR" ] ; then
2028      if grep -q "$ISODIR" /proc/mounts ; then
2029         einfo "Unmount $MNTPOINT/$ISODIR"
2030         umount "$MNTPOINT/$ISODIR"
2031         eend $?
2032      fi
2033   fi
2034
2035   if grep -q "$MNTPOINT" /proc/mounts ; then
2036     if mountpoint "${MNTPOINT}"/run/udev &>/dev/null ; then
2037       einfo "Unmounting bind-mount /run/udev"
2038       umount "${MNTPOINT}"/run/udev
2039       eend $?
2040     fi
2041
2042      if [ -n "$PARTITION" ] ; then
2043         einfo "Unmount $MNTPOINT"
2044         umount "$MNTPOINT"
2045         eend $?
2046      fi
2047   fi
2048 }
2049 # }}}
2050
2051 # execute filesystem check {{{
2052 fscktool() {
2053  if [ -n "$VIRTUAL" ] ; then
2054    einfo "Skipping filesystem check because we deploy a virtual machine."
2055    return 0
2056  fi
2057
2058  if [ "$FSCK" = 'yes' ] ; then
2059    [ -n "$FSCKTOOL" ] || FSCKTOOL="fsck.${MKFS#mkfs.}"
2060    einfo "Checking filesystem on $TARGET using $FSCKTOOL"
2061    "$FSCKTOOL" "$TARGET"
2062    eend $?
2063  fi
2064 }
2065 # }}}
2066
2067 # get rid of grml-debootstrap config files {{{
2068 remove_configs() {
2069   if [ "$REMOVE_CONFIGS" != "yes" ] ; then
2070     return 0
2071   fi
2072
2073   if ! mountpoint "${MNTPOINT}" >/dev/null 2>&1 ; then
2074     ewarn "Target ${MNTPOINT} doesn't seem to be mounted, can't remove configuration files." ; eend 0
2075     return 0
2076   fi
2077
2078   einfo "Removing configuration files from installed system as requested via --remove-configs / REMOVE_CONFIGS."
2079   rm -rf "${MNTPOINT}"/etc/debootstrap/
2080   eend $?
2081 }
2082 # }}}
2083
2084 # now execute all the functions {{{
2085 for i in format_efi_partition prepare_vm mkfs tunefs \
2086          mount_target mountpoint_to_blockdevice debootstrap_system \
2087          preparechroot execute_pre_scripts chrootscript execute_post_scripts \
2088          remove_configs umount_chroot grub_install umount_target fscktool ; do
2089     if stage "${i}" ; then
2090       if "$i" ; then
2091         stage "${i}" 'done' && rm -f "${STAGES}/${i}"
2092       else
2093         bailout 2 "$i"
2094       fi
2095     fi
2096 done
2097
2098 cleanup
2099 # }}}
2100
2101 # end dialog of autoinstallation {{{
2102 if [ -n "$AUTOINSTALL" ] ; then
2103    if dialog --title "${PN}" --pause "Finished execution of ${PN}.
2104 Automatically rebooting in 10 seconds.
2105
2106 Choose Cancel to skip rebooting." 10 60 10 ; then
2107      noeject noprompt reboot
2108   fi
2109 else
2110    einfo "Finished execution of ${PN}. Enjoy your Debian system." ; eend 0
2111 fi
2112 # }}}
2113
2114 ## END OF FILE #################################################################
2115 # vim: ai tw=100 expandtab foldmethod=marker shiftwidth=2