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