7fd52a26505a24e03364399aec1fe23361050eac
[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 http://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 "$(which "$0")")"/.git ]]; then
44   VERSION="$(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://http.debian.net/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 "$INSTALL_NOTES" ] || INSTALL_NOTES='/etc/debootstrap/install_notes'
67 [ -n "$LOCALES" ] || LOCALES='yes'
68 [ -n "$MIRROR" ] || MIRROR="$FALLBACK_MIRROR"
69 [ -n "$MKFS" ] || MKFS='mkfs.ext4'
70 [ -n "$MKFS_OPTS" ] || MKFS_OPTS=''
71 [ -n "$PACKAGES" ] || PACKAGES='yes'
72 [ -n "$POST_SCRIPTS" ] || POST_SCRIPTS='yes'
73 [ -n "$PRE_SCRIPTS" ] || PRE_SCRIPTS='yes'
74 [ -n "$RECONFIGURE" ] || RECONFIGURE='console-data'
75 [ -n "$RELEASE" ] || RELEASE='jessie'
76 [ -n "$RM_APTCACHE" ] || RM_APTCACHE='yes'
77 [ -n "$SCRIPTS" ] || SCRIPTS='yes'
78 [ -n "$SECURE" ] || SECURE='yes'
79 [ -n "$TIMEZONE" ] || TIMEZONE='Europe/Vienna'
80 [ -n "$TUNE2FS" ] || TUNE2FS='tune2fs -c0 -i0'
81 [ -n "$UPGRADE_SYSTEM" ] || UPGRADE_SYSTEM='yes'
82 [ -n "$VMSIZE" ] || VMSIZE="2G"
83
84 # inside the chroot system locales might not be available, so use minimum:
85 export LANG=C
86 export LC_ALL=C
87 export LANGUAGE=C
88
89 # make sure interactive mode is only executed when
90 # using an empty configuration file or option --interactive
91 INTERACTIVE=''
92 # }}}
93
94 # help text {{{
95 usage() {
96   echo "$PN - wrapper around debootstrap for installing Debian
97
98 Usage: $PN [options]
99
100 Bootstrap options:
101
102   -m, --mirror <URL>     Mirror which should be used for apt-get/aptitude.
103   -i, --iso <mnt>        Mountpoint where a Debian ISO is mounted to, for use
104                          instead of fetching packages from a mirror.
105   -r, --release <name>   Release of new Debian system (default: jessie).
106   -t, --target <target>  Target partition (/dev/...) or directory where the
107                          system should be installed to.
108   -p, --mntpoint <mnt>   Mountpoint used for mounting the target system,
109                          has no effect if -t is given and represents a directory.
110       --debopt <params>  Extra parameters passed to the debootstrap command.
111       --interactive      Use interactive mode (frontend).
112       --nodebootstrap    Skip debootstrap, only do configuration to the target.
113       --grub <device>    Target for grub installation. Usage example: /dev/sda
114       --arch <arch>      Set target architecture, use for installing i386 on amd64.
115       --filesystem <fs>  Filesystem that should be used when target is a partition
116                          or Virtual Machine (see --vmfile).
117       --force            Do not prompt for user acknowledgement.
118
119 Options for Virtual Machine deployment:
120
121       --vm               Set up a Virtual Machine on an existing block device
122                          instead of plainly installing to a partition or
123                          directory. Needs to be combined with --target.
124                          Example: --vm --target /dev/mapper/your-vm-disk
125       --vmfile           Like --vm, but install into a regular file (created by
126                          'qemu-img create -f raw ...') instead.
127                          Example: --vmfile --target /mnt/sda1/qemu.img
128       --vmsize <size>    Use specified size for size of VM file (default: 2G).
129                          Syntax as supported by qemu-img, like: --vmsize 3G
130
131 Configuration options:
132
133   -c, --config <file>      Use specified configuration file, defaults to
134                              /etc/debootstrap/config
135   -d, --confdir <path>     Place of config files for debootstrap, defaults
136                              to /etc/debootstrap
137       --packages <file>    Install packages defined in specified list file
138                              instead of using /etc/debootstrap/packages.
139       --nopackages         Skip installation of packages defined in
140                              /etc/debootstrap/packages
141       --nokernel           Skip installation of default kernel images.
142       --nointerfaces       Do not copy /etc/network/interfaces from host system
143                            to target system.
144                            (This option is automatically enabled when using --vmfile.)
145       --defaultinterfaces  Install a default /etc/network/interfaces file (enabling
146                            DHCP for eth0) instead of taking over config from host system.
147       --debconf <file>     Pre-seed packages using specified pre-seed db file.
148       --grmlrepos          Enable Grml's Debian repository (deb.grml.org).
149       --backportrepos      Enable Debian's backports repository (backports.debian.org).
150       --keep_src_list      Do not overwrite user provided apt sources.list.
151       --contrib            Enable 'contrib' in COMPONENTS (defaults to 'main' only).
152       --non-free           Enable non-free in COMPONENTS (defaults to 'main' only).
153       --hostname <name>    Hostname of Debian system.
154       --nopassword         Do not prompt for the root password.
155       --password <pwd>     Use specified password as password for user root.
156       --bootappend <line>  Add specified appendline to kernel whilst booting.
157       --chroot-scripts <d> Execute chroot scripts from specified directory.
158       --pre-scripts <dir>  Execute scripts from specified directory (before chroot-scripts).
159       --scripts <dir>      Execute scripts from specified directory (after chroot-scripts).
160
161 Other options:
162
163   -v, --verbose            Increase verbosity.
164       --debug              Execute in very verbose way.
165   -h, --help               Print this usage information and exit.
166   -V, --version            Show summary of options and exit.
167
168 Usage examples can be found in the grml-debootstrap manpage.
169 Send bugreports to the grml-team: bugs (at) grml.org || http://grml.org/bugs/
170 "
171 }
172
173 if [ "$1" = '-h' ] || [ "$1" = '-help' ] || [ "$1" = "--help" ] ; then
174    usage
175    echo 'Please notice that this script requires root permissions!'
176    exit 0
177 fi
178 # }}}
179
180 # early helper functions {{{
181 GOOD='\e[32;01m'
182 BAD='\e[31;01m'
183 WARN='\e[33;01m'
184 NORMAL='\e[0m'
185
186 einfo() {
187   einfon "$1\n"
188   return 0
189 }
190
191 einfon() {
192   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
193   printf " ${GOOD}*${NORMAL} $*"
194   LAST_E_CMD=einfon
195   return 0
196 }
197
198 ewarn() {
199   printf " ${WARN}*${NORMAL} $*\n"
200   return 0
201 }
202
203 eerror() {
204   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
205   printf " ${BAD}*${NORMAL} $*\n" >&2
206   LAST_E_CMD=eerror
207   return 0
208 }
209
210 eend() {
211   local retval="${1:-0}"
212   shift
213   if [ "$retval" -gt 0 ]; then
214     printf " ${BAD}-> Failed (rc=${retval})${NORMAL}\n"
215   fi
216   return "$retval"
217 }
218
219 check4root(){
220   if [ "$(id -u 2>/dev/null)" != 0 ] ; then
221     echo 1>&2 "Error: please run this script with uid 0 (root)." ; return 1
222   fi
223 }
224
225 check4progs(){
226   local RC=''
227   for arg in "$@" ; do
228     which "$arg" >/dev/null 2>&1 || RC="$arg"
229   done
230   if [ -n "$RC" ] ; then
231      echo "$RC not installed"
232      return 1
233   fi
234 }
235 # }}}
236
237 # helper functions {{{
238 cleanup() {
239   if [ -n "$CHROOT_VARIABLES" ] ; then
240     einfo "Removing ${CHROOT_VARIABLES}" ; rm "$CHROOT_VARIABLES" ; eend $?
241   fi
242
243   if [ -n "$STAGES" ] ; then
244     einfo "Removing ${STAGES}" ; rmdir "$STAGES" ; eend $?
245   fi
246
247   # Remove temporary mountpoint again
248   if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
249     rmdir "$MNTPOINT" 2>/dev/null
250   fi
251
252   # make sure $TARGET is not mounted when exiting grml-debootstrap
253   if [ -n "$MNTPOINT" ] ; then
254     if grep -q "$MNTPOINT" /proc/mounts ; then
255       # make sure nothing is left inside chroot so we can unmount it
256       for service in ssh mdadm ; do
257         if [ -x "${MNTPOINT}/etc/init.d/${service}" ] ; then
258           chroot "$MNTPOINT" "/etc/init.d/${service}" stop
259         fi
260       done
261
262       [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount -a >/dev/null 2>&1
263
264       # ugly, but make sure we really don't leave anything (/proc /proc and
265       # /dev /dev are intended, trying to work around timing issues, see #657023)
266       for ARG in /sys /proc /proc /dev/pts /dev/pts /dev /dev ; do
267         [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount $ARG >/dev/null 2>&1
268         umount "$MNTPOINT"/$ARG >/dev/null 2>&1
269       done
270
271       if [ -n "$ISODIR" ] ; then
272         [ -d "$MNTPOINT/$ISODIR" ] && umount "$MNTPOINT/$ISODIR" >/dev/null 2>&1
273       fi
274
275       if [ -n "$DIRECTORY" ] ; then
276         einfo "Not unmounting $MNTPOINT as you requested me to install into a directory of your own choice." ; eend 0
277       else
278         einfo "Unmounting $MNTPOINT"
279         umount "$MNTPOINT"
280         eend $?
281       fi
282
283       if [ -n "$STAGES" ] ; then
284         echo -n "Removing stages directory ${STAGES}: "
285         rm -rf "$STAGES" && echo 'done'
286       fi
287
288       # remove directory only if we used the default with process id inside the name
289       if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
290         einfo "Removing directory ${MNTPOINT}"
291         rmdir "$MNTPOINT"
292         eend $?
293       fi
294     fi
295   fi
296
297   if [ -n "${ORIG_TARGET}" ] ; then
298     einfo "Removing loopback mount of file ${ORIG_TARGET}."
299     kpartx -d "${ORIG_TARGET}" ; eend $?
300   fi
301 }
302
303 # we want to exit smoothly and clean:
304 bailout(){
305
306   cleanup
307
308   [ -n "$1" ] && EXIT="$1" || EXIT="1"
309   [ -n "$2" ] && einfo "Notice: remove $STAGES/$2 to reexecute the stage"
310
311   exit "$EXIT"
312 }
313 trap bailout HUP INT QUIT TERM
314
315 # we want to execute all the functions only once, simple check for it:
316 stage() {
317   if [ -n "$2" ] ; then
318      echo "$2" > "${STAGES}/${1}"
319      return 0
320   elif grep -q 'done' "${STAGES}/${1}" 2>/dev/null ; then
321      ewarn "Notice: stage $1 has been executed already, skipping execution therefore." ; eend 0
322      ewarn "  To reexecute it clean up the according directory inside $STAGES" ; eend 0
323      return 1
324   fi
325 }
326 # }}}
327
328 # make sure we have what we need {{{
329 check4progs debootstrap || bailout 1
330 # }}}
331
332 # source main configuration file {{{
333 if [ -r /etc/debootstrap/config ] ; then
334   . /etc/debootstrap/config
335 fi
336 # }}}
337
338 # cmdline handling {{{
339 # source external command line parameter-processing script
340 self_dir="$(dirname "$(which "$0")")"
341 if [ -r "${self_dir}"/cmdlineopts.clp ] ; then
342    . "${self_dir}"/cmdlineopts.clp
343 elif [ -r /usr/share/grml-debootstrap/functions/cmdlineopts.clp ] ; then
344    . /usr/share/grml-debootstrap/functions/cmdlineopts.clp
345 else
346    eerror "Error: cmdline function file not found, exiting."
347    eend 1
348    bailout 1
349 fi
350
351 # == business-logic of command line parameter-processing
352
353 # source configuration file in <confdir> if supplied. {{{
354 [ "$_opt_confdir" ] && {
355   CONFFILES=$_opt_confdir
356   einfo "Using config files under $CONFFILES/."
357   if ! [ -r "$CONFFILES/config" ] ; then
358     eerror "Error: config file $CONFFILES/config not found."; eend 1; bailout 1
359   fi
360   if ! . "$CONFFILES/config" ; then
361     eerror "Error reading config file $CONFFILES/config" ; eend 1 ; bailout 1
362   fi
363   # restore the command line parameter value
364   CONFFILES=$_opt_confdir
365 }
366 # }}}
367
368 [ "$_opt_mirror" ]              && MIRROR=$_opt_mirror
369 [ "$_opt_iso" ]                 && ISO=$_opt_iso
370 [ "$_opt_release" ]             && RELEASE=$_opt_release
371 [ "$_opt_target" ]              && TARGET=$_opt_target
372 [ "$_opt_vm" ]                  && VIRTUAL=1
373 [ "$_opt_vmfile" ]              && VMFILE=1 && VIRTUAL=1
374 [ "$_opt_vmsize" ]              && VMSIZE=$_opt_vmsize
375 [ "$_opt_mntpoint" ]            && MNTPOINT=$_opt_mntpoint
376 [ "$_opt_debopt" ]              && DEBOOTSTRAP_OPT=$_opt_debopt
377 [ "$_opt_interactive" ]         && INTERACTIVE=1
378 [ "$_opt_config" ]              && CONFIGFILE=$_opt_config
379 [ "$_opt_filesystem" ]          && MKFS="mkfs.$_opt_filesystem"
380 [ "$_opt_packages_set" ]        && PACKAGES='yes'
381 [ "$_opt_nopackages" ]          && PACKAGES=''
382 [ "$_opt_debconf_set" ]         && DEBCONF='yes'
383
384 if [ "$_opt_scripts_set" ] ; then
385   ewarn "Deprecation NOTE: --scripts option is deprecated, please switch to --post-scripts instead."
386   SCRIPTS='yes' # deprecated since grml-debootstrap >=0.71
387 fi
388
389 [ "$_opt_post_scripts_set" ]    && POST_SCRIPTS='yes'
390 [ "$_opt_pre_scripts_set" ]     && PRE_SCRIPTS='yes'
391 [ "$_opt_chroot_scripts_set" ]  && CHROOT_SCRIPTS='yes'
392 [ "$_opt_keep_src_list" ]       && KEEP_SRC_LIST='yes'
393 [ "$_opt_grmlrepos" ]           && GRMLREPOS='yes'
394 [ "$_opt_backportrepos" ]       && BACKPORTREPOS='yes'
395 [ "$_opt_hostname" ]            && HOSTNAME=$_opt_hostname
396 [ "$_opt_password" ]            && ROOTPASSWORD=$_opt_password
397 [ "$_opt_nopassword" ]          && NOPASSWORD='yes'
398 [ "$_opt_defaultinterfaces" ]   && USE_DEFAULT_INTERFACES="true"
399 [ "$_opt_nointerfaces" ]        && NOINTERFACES="true"
400 [ "$_opt_nokernel" ]            && NOKERNEL="true"
401 [ "$_opt_bootappend" ]          && BOOT_APPEND=$_opt_bootappend
402 [ "$_opt_grub" ]                && GRUB=$_opt_grub
403 [ "$_opt_arch" ]                && ARCH=$_opt_arch
404 [ "$_opt_insecure" ]            && echo "Warning: --insecure is deprecated, continuing anyway."
405 [ "$_opt_force" ]               && FORCE=$_opt_force
406 [ "$_opt_verbose" ]             && VERBOSE="-v"
407 [ "$_opt_debug" ]               && DEBUG="true"
408
409 # make sure main is always included
410 [ -z "$COMPONENTS" ]            && COMPONENTS="main"
411 [ "$_opt_contrib" ]             && COMPONENTS="$COMPONENTS contrib"
412 [ "$_opt_non_free" ]            && COMPONENTS="$COMPONENTS non-free"
413
414 if [ "$DEBUG" = "true" ] ; then
415   set -x
416 fi
417
418 [ "$_opt_help" ] && {
419   usage ; eend 0
420   eend 0
421   exit 0
422 }
423
424 [ "$_opt_version" ] && {
425   einfo "$PN - version $VERSION"
426   einfo "Send bug reports to bugs@grml.org or http://grml.org/bugs/"
427   eend 0
428   exit 0
429 }
430 # }}}
431
432 # check for root permissions {{{
433 if ! check4root ; then
434    echo "For usage instructions please execute '$PN --help'."
435    bailout 1
436 fi
437 # }}}
438
439 # make sure we have what we need {{{
440 if [ -n "$VIRTUAL" ] ; then
441   check4progs kpartx mksh parted qemu-img || bailout 1
442 fi
443 # }}}
444
445 # source specified configuration file {{{
446 if [ -n "$CONFIGFILE" ] ; then
447    einfo "Reading specified config file $CONFIGFILE."
448    if ! . "$CONFIGFILE" ; then
449       eerror "Error reading config file $CONFIGFILE" ; eend 1 ; bailout 1
450    fi
451 fi
452 # }}}
453
454 # backwards compability checks {{{
455 if [ -n "$GROOT" ] ; then
456    eerror "Error: you seem to have \$GROOT configured."
457    eerror "This variable is no longer supported, please visit the"
458    eerror "grml-debootstrap documentation for details."
459    eend 1
460    bailout 1
461 fi
462
463 if echo "$GRUB" | grep -q '^hd' ; then
464    eerror "Error: this syntax for the grub configuration variable is no longer supported."
465    eerror "Please do not use hd... any longer but /dev/sdX instead."
466    eend 1
467    bailout 1
468 fi
469 # }}}
470
471 # welcome screen {{{
472 welcome_dialog()
473 {
474    dialog --title "$PN" --yesno "Welcome to the interactive configuration of ${PN}.
475 Do you want to continue installing Debian using this frontend?" 0 0 || bailout 0
476 }
477 # }}}
478
479 # ask for target {{{
480 prompt_for_target()
481 {
482   AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
483                sed 's/*//' | \
484                grep -v 'Extended$' | \
485                gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}'; ls /dev/md[0-9]* 2>/dev/null || true);
486
487   if [ -z "$AVAILABLE_PARTITIONS" ] ; then
488      dialog --title "$PN" --trim \
489      --msgbox "Sorry, no partitions found. Please configure your
490      harddisks (see /proc/partitions) using a tool like fdisk,
491      cfdisk, gpart, gparted,..." 0 0
492      bailout 1
493   fi
494
495   PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
496                      fs="$(blkid -s TYPE -o value "$i" 2>/dev/null)"
497                      [ -n "$fs" ] || fs='[no_filesystem_yet]'
498                      echo "$i" "$fs"
499                      unset fs
500                    done)
501
502   TARGET=$(dialog --title "$PN" --single-quoted --stdout \
503          --menu "Please select the target partition:" 0 0 0 \
504          $PARTITION_LIST)
505   [ $? -eq 0 ] || bailout 1
506 }
507 # }}}
508
509 # ask for bootmanager {{{
510 prompt_for_bootmanager()
511 {
512   ADDITIONAL_PARAMS=""
513
514   if echo "$TARGET" | grep -q "/dev/md" ; then
515      MBRPART="all disks of Software RAID $TARGET"
516   else
517      # figure out whole disk device
518      found=
519      for device in /dev/disk/by-id/*
520      do
521         [ "$(readlink -f "$device")" = "${TARGET}" ] || continue
522         found=1
523         break
524      done
525      [ -n "$found" ] && MBRDISK=$(echo "${device}" |sed -e 's/-part[0-9][0-9]*$//')
526      if [ -e "$MBRDISK" ]; then
527         MBRDISK=$(readlink -f "$MBRDISK")
528      else
529         # fall back to old behaviour
530         MBRDISK=$(echo "${TARGET}" | sed -e 's/[0-9][0-9]*$//')
531      fi
532
533      MBRPART="MBR of $MBRDISK"
534   fi
535
536   for device in cciss/c0d0 sda hda; do
537     if [ "/dev/$device" != "${MBRDISK}" ]; then
538       grep -q $device /proc/partitions && \
539       ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS:$device:install bootmanager grub into MBR of /dev/$device"
540     fi
541   done
542   ADDITIONAL_PARAMS=${ADDITIONAL_PARAMS#:}
543
544   OIFS="$IFS"; IFS=:
545
546   GETMBR=$(dialog --stdout --title "$PN" --default-item mbr \
547           --menu "Where do you want to install the bootmanager grub?" 0 0 0 \
548             mbr       "install bootmanager into $MBRPART" \
549             nowhere   "do not install bootmanager at all" \
550           ${ADDITIONAL_PARAMS})
551   [ $? -eq 0 ] || bailout 3
552   IFS="$OIFS"
553
554   case "$GETMBR" in
555     mbr)
556       # /dev/md0: has to be installed in MBR of /dev/md0 and not in /dev/md:
557       if echo "$TARGET" | grep -q "/dev/md" ; then
558         GRUB="$TARGET"
559       else
560         GRUB="$MBRDISK"
561       fi
562       ;;
563     hda)
564       GRUB="/dev/hda"
565       ;;
566     sda)
567       GRUB="/dev/sda"
568       ;;
569     nowhere)
570       GRUB=''
571       ;;
572   esac
573 }
574 # }}}
575
576 # ask for Debian release {{{
577 prompt_for_release()
578 {
579   [ -n "$RELEASE" ] && DEFAULT_RELEASE="$RELEASE" || DEFAULT_RELEASE='jessie'
580   RELEASE="$(dialog --stdout --title "${PN}" --default-item $DEFAULT_RELEASE --menu \
581             "Please enter the Debian release you would like to use for installation:" \
582             0 50 5 \
583             lenny    Debian/5.0 \
584             squeeze  Debian/6.0 \
585             wheezy   Debian/7.0 \
586             jessie   Debian/8.0 \
587             stretch  Debian/9.0 \
588             sid      Debian/unstable)"
589   [ $? -eq 0 ] || bailout
590 }
591 # }}}
592
593 # ask for hostname {{{
594 prompt_for_hostname()
595 {
596   HOSTNAME="$(dialog --stdout --title "${PN}" --inputbox \
597             "Please enter the hostname you would like to use for installation:" \
598             0 0 "$HOSTNAME")"
599   [ $? -eq 0 ] || bailout
600 }
601 # }}}
602
603 # ask for password {{{
604 prompt_for_password()
605 {
606   if [ "$_opt_nopassword" ] ; then
607     einfo "Skip asking for root password as requested."
608     return 0
609   fi
610
611   ROOTPW1='PW1'
612   ROOTPW2='PW2'
613   while [ "$ROOTPW1" != "$ROOTPW2" ]; do
614     ROOTPW1=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
615     "Please enter the password for the root account:" 10 60)
616     [ $? -eq 0 ] || bailout
617
618     ROOTPW2=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
619     "Please enter the password for the root account again for \
620     confirmation:" 10 60)
621     [ $? -eq 0 ] || bailout
622
623     if [ "$ROOTPW1" != "$ROOTPW2" ]; then
624       dialog --stdout --title "${PN}" --ok-label \
625         "Retry" --msgbox "Passwords do not match!" 10 60
626     fi
627   done
628   ROOTPASSWORD="$ROOTPW1"
629 }
630 # }}}
631
632 # ask for Debian mirror {{{
633 prompt_for_mirror()
634 {
635   [ -n "$ISO" ] && DEFAULT_MIRROR='local' || DEFAULT_MIRROR='net'
636
637   CHOOSE_MIRROR=$(dialog --stdout --title "$PN" --default-item $DEFAULT_MIRROR \
638           --menu "Where do you want to install from?" 0 0 0 \
639             net   "install via network (downloading from mirror)" \
640             local "install from local directory/mirror"
641           )
642   [ $? -eq 0 ] || bailout
643
644   if [ "$CHOOSE_MIRROR" = 'net' ] ; then
645      [ -n "$MIRROR" ] || MIRROR='http://http.debian.net/debian'
646      MIRROR="$(dialog --stdout --title "${PN}" --inputbox \
647                "Please enter Debian mirror you would like to use for installing packages." \
648                0 0 $MIRROR)"
649      [ $? -eq 0 ] || bailout
650   else # CHOOSE_MIRROR == local
651      [ -n "$ISO" ] || ISO='/mnt/mirror'
652      ISO="$(dialog --stdout --title "${PN}" --inputbox \
653                "Please enter directory name you would like to use for installing packages." \
654                0 0 $ISO)"
655      [ $? -eq 0 ] || bailout
656   fi
657 }
658 # }}}
659
660 # software raid setup {{{
661 config_swraid_setup()
662 {
663 TMPFILE=$(mktemp)
664
665 # Currently we support only raid1:
666 RAIDLEVEL='raid1'
667
668 MD_LIST=$(for i in $(seq 0 9) ; do
669             awk '{print $4}' /proc/partitions | grep -q "md$i" || \
670             echo "/dev/md$i /dev/md$i"
671           done)
672
673 TARGET=$(dialog --stdout --title "$PN" --default-item /dev/md0 \
674 --menu "Which device do you want to use for ${RAIDLEVEL}?
675
676 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 \
677 $MD_LIST)
678 [ $? -eq 0 ] || bailout 20
679
680 AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
681              sed 's/*//' | \
682              grep -v 'Extended$' | \
683              gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}')
684 [ -n "$AVAILABLE_PARTITIONS" ] || echo "Fatal error: no partitions available?"
685 PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
686                      echo "$i $(blkid -s TYPE -o value "$i" 2>/dev/null || echo '[no_filesystem_yet]') off"
687                  done)
688
689 dialog --title "$PN" --separate-output \
690        --checklist "Please select the partitions you would like to use for your $RAIDLEVEL on ${TARGET}:" 0 0 0 \
691        $PARTITION_LIST 2>"$TMPFILE"
692 [ $? -eq 0 ] || bailout
693 SELECTED_PARTITIONS="$(cat "$TMPFILE")"
694
695 NUM_PARTITIONS=0
696 for i in $(cat "$TMPFILE") ; do
697    NUM_PARTITIONS=$(( NUM_PARTITIONS + 1 ))
698 done
699
700 # force metadata version 0.90 for lenny so old grub can boot from this array.
701 METADATA_VERSION=""
702 if [ "$RELEASE" = "lenny" ]; then
703    METADATA_VERSION="-e0"
704 fi
705
706 ERRORFILE=$(mktemp)
707 yes | mdadm --create "${TARGET}" --level="${RAIDLEVEL}" \
708       --raid-devices="${NUM_PARTITIONS}" ${METADATA_VERSION} ${SELECTED_PARTITIONS} >/dev/null 2>$ERRORFILE
709 RC=$?
710 if [ "$RC" = 0 ] ; then
711    dialog --title "$PN" --msgbox \
712    "Creating $TARGET was successful." 0 0
713    rm -f "$TMPFILE" "$ERRORFILE"
714 else
715    dialog --title "$PN" --msgbox \
716    "There was an error setting up $TARGET:
717
718 $(cat "$ERRORFILE")
719
720 Exiting." 0 0
721    rm -f "$TMPFILE" "$ERRORFILE"
722    bailout 1
723 fi
724
725 }
726
727 prompt_for_swraid()
728 {
729 if dialog --stdout --title "$PN" \
730           --defaultno --yesno "Do you want to configure Software RAID?
731
732 Please notice that only RAID level 1 is supported by ${PN} currently. Configuration will take place using mdadm." 0 0 ; then
733   config_swraid_setup
734 fi
735 }
736 # }}}
737
738 # user should recheck his configuration {{{
739 # support full automatic installation:
740 checkforrun() {
741    dialog --timeout 10 --title "$PN" \
742           --yesno "Do you want to stop at this stage?
743
744 Notice: you are running ${PN} in non-interactive mode.
745 ${PN} will install Debian ${RELEASE} on ${TARGET}.
746 Last chance to quit. Timeout of 10 seconds running....
747
748 Do you want to stop now?" 0 0 2>/dev/null
749 }
750 # }}}
751
752 # make sure the user is aware of the used configuration {{{
753 checkconfiguration()
754 {
755 if [ -n "$AUTOINSTALL" ] ; then
756    if checkforrun ; then
757       eerror "Exiting as requested" ; eend 0
758       bailout 1
759    fi
760 elif [ -n "$INTERACTIVE" ] ; then
761
762    INFOTEXT="Please recheck configuration before execution:
763    "
764    [ -n "$TARGET" ]  && INFOTEXT="$INFOTEXT
765    Target:          $TARGET"
766    [ -n "$GRUB" ]    && INFOTEXT="$INFOTEXT
767    Install grub:    $GRUB"
768    [ -n "$RELEASE" ] && INFOTEXT="$INFOTEXT
769    Using release:   $RELEASE"
770    [ -n "$HOSTNAME" ] && INFOTEXT="$INFOTEXT
771    Using hostname:  $HOSTNAME"
772    [ -n "$MIRROR" ]  && INFOTEXT="$INFOTEXT
773    Using mirror:    $MIRROR"
774    [ -n "$ISO" ]  && INFOTEXT="$INFOTEXT
775    Using ISO:       $ISO"
776    [ -n "$ARCH" ]  && INFOTEXT="$INFOTEXT
777    Using arch:      $ARCH"
778
779    INFOTEXT="$INFOTEXT
780
781 Is this ok for you? Notice: selecting 'No' will exit ${PN}."
782
783    dialog --title "$PN" --no-collapse \
784           --yesno "$INFOTEXT" 0 0
785    [ $? -eq 0 ] || bailout 0
786
787 else # if not running automatic installation display configuration and prompt for execution:
788    einfo "$PN [${VERSION}] - Please recheck configuration before execution:"
789    echo
790    echo "   Target:          $TARGET"
791
792    # do not display if MNTPOINT is the default one
793    case "$MNTPOINT" in /mnt/debootstrap*) ;; *) echo "   Mount point:     $MNTPOINT" ;; esac
794
795    if [ -n "$VIRTUAL" ] ; then
796       echo "   Install grub:    yes"
797    else
798      [ -n "$GRUB" ]     && echo "   Install grub:    $GRUB" || echo "   Install grub:    no"
799    fi
800
801    [ -n "$RELEASE" ]  && echo "   Using release:   $RELEASE"
802    [ -n "$HOSTNAME" ] && echo "   Using hostname:  $HOSTNAME"
803    [ -n "$MIRROR" ]   && echo "   Using mirror:    $MIRROR"
804    [ -n "$ISO" ]      && echo "   Using ISO:       $ISO"
805    [ -n "$ARCH" ]     && echo "   Using arch:      $ARCH"
806    if [ -n "$VIRTUAL" ] ; then
807       echo "   Deploying as Virtual Machine."
808       if [ -n "$VMSIZE" -a -n "$VMFILE" ]; then
809          echo "   Using Virtual Disk file with size of ${VMSIZE}."
810       fi
811    fi
812
813    if [ ! -t 0 -a -z "$ROOTPASSWORD" -a -z "$NOPASSWORD" ] ; then
814       echo
815       echo "   You do not have a TTY allocated, your password will be shown in"
816       echo "   plaintext on the terminal! If you are using SSH, try its -t option!"
817    fi
818
819    echo
820    echo "   Important! Continuing will delete all data from ${TARGET}!"
821
822    if [ -n "$FORCE" ] ; then
823      einfo "Skip user acknowledgement as requested via --force option."
824    else
825      echo
826      einfon "Is this ok for you? [y/N] "
827      read a
828      if ! [ "$a" = 'y' -o "$a" = 'Y' ] ; then
829         eerror "Exiting as requested." ; eend 1
830         bailout 1
831      fi
832    fi
833 fi
834 }
835 # }}}
836
837 # interactive mode {{{
838 interactive_mode()
839 {
840   check4progs dialog || bailout 1
841
842   welcome_dialog
843
844   prompt_for_release
845
846   prompt_for_swraid
847
848   prompt_for_target
849
850   prompt_for_bootmanager
851
852   prompt_for_hostname
853
854   prompt_for_password
855
856   prompt_for_mirror
857 }
858
859 # run interactive mode if we didn't get the according configuration yet
860 if [ -z "$TARGET" -o -n "$INTERACTIVE" ] ; then
861    # only target might be unset, so make sure the INTERACTIVE flag is set as well
862    INTERACTIVE=1
863    interactive_mode
864 fi
865 # }}}
866
867 # architecture setup {{{
868 if [ -n "$ARCH" ] ; then
869    ARCHCMD="--arch $ARCH"
870    ARCHINFO=" (${ARCH})"
871 else
872    ARCH="$(dpkg --print-architecture)"
873    ARCHCMD="--arch $ARCH"
874    ARCHINFO=" (${ARCH})"
875 fi
876 # }}}
877
878 # It is not possible to build amd64 on i686. {{{
879 CURRENT_ARCH="$(uname -m)"
880 if [ "$CURRENT_ARCH" != "x86_64" ] ; then
881    if [ "$ARCH" = "amd64" ] ; then
882       eerror "It is not possible to build amd64 on $CURRENT_ARCH." ; eend 1
883       bailout 1
884    fi
885 fi
886 # }}}
887
888 # Support for generic release codenames is unavailable. {{{
889 if [ "$RELEASE" = "stable" ] || [ "$RELEASE" = "testing" ] ; then
890    eerror "Generic release codenames (stable, testing) are unsupported. \
891 Please use specific codenames such as lenny, squeeze, wheezy, jessie or stretch." ; eend 1
892    bailout 1
893 fi
894 # }}}
895
896 checkconfiguration
897
898 # finally make sure at least $TARGET is set [the partition for the new system] {{{
899 if [ -n "$TARGET" ] ; then
900    SHORT_TARGET="${TARGET##*/}"
901 else
902    eerror "Please adjust $CONFFILES/config or..."
903    eerror "... use the interactive version for configuration before running ${0}" ; eend 1
904    bailout 1
905 fi
906 # }}}
907
908 # stages setup {{{
909 if [ -z "$STAGES" ] ; then
910    STAGES="/var/cache/grml-debootstrap/stages_${SHORT_TARGET}"
911    [ -d "$STAGES" ] || mkdir -p "$STAGES"
912 fi
913
914 if [ -r "$STAGES"/grml-debootstrap ] ; then
915    if grep -q 'done' "${STAGES}/grml-debootstrap" ; then
916       eerror "Error: grml-debootstrap has been executed already, won't continue therefore."
917       eerror "If you want to re-execute grml-debootstrap just manually remove ${STAGES}" ; eend 1
918    fi
919 fi
920 # }}}
921
922 # partition handling {{{
923 PARTITION=''
924 DIRECTORY=''
925
926 set_target_directory(){
927     # assume we are installing into a directory, don't run mkfs and grub related stuff therefore
928     DIRECTORY=1
929     MNTPOINT="$TARGET"
930     MKFS=''
931     TUNE2FS=''
932     FSCK=''
933     # make sure we normalise the path to an absolute directory name so something like:
934     #  mkdir -p foo/a bar/a; (cd foo; grml-debootstrap -t a)&; (cd bar; grml-debootstrap -t a)&; wait
935     # works
936     TARGET="$(readlink -f "$TARGET")"
937 }
938
939 if [ -b "$TARGET" ] || [ -n "$VIRTUAL" ] ; then
940     PARTITION=1
941 else
942     set_target_directory
943 fi
944 # }}}
945
946 # make sure we have the right syntax when using an iso image {{{
947 if [ -n "$ISO" ] ; then
948    case $ISO in
949       file*) # do nothing
950       ;;
951       *)
952       ISO=file:$ISO
953       ;;
954    esac
955 fi
956 ISODIR=${ISO##file:}
957 ISODIR=${ISODIR%%/}
958 # }}}
959
960 # Debian ISOs do not contain signed Release files {{{
961 if [ -n "$ISO" ] ; then
962     DEBOOTSTRAP_OPT="$DEBOOTSTRAP_OPT --no-check-gpg"
963 fi
964 # }}}
965
966 # create filesystem {{{
967 mkfs() {
968   if [ -n "$DIRECTORY" ] ; then
969      einfo "Running grml-debootstrap on a directory, skipping mkfs stage."
970      return 0
971   fi
972
973   if grep -q "$TARGET" /proc/mounts ; then
974     eerror "$TARGET already mounted, exiting to avoid possible damage. (Manually unmount $TARGET)" ; eend 1
975     bailout 1
976   fi
977
978   # mkfs.ext* might prompt with "/dev/sdX# contains a ext* file system
979   # created on ... Proceed anyway? (y,n)" which we want to skip in force mode
980   if [ -n "$MKFS" ] && [ -n "$FORCE" ] ; then
981     case "$MKFS" in
982       mkfs.ext*)
983         einfo "Enabling force option (-F) for mkfs.ext* tool as requested via --force switch."
984         MKFS_OPTS="$MKFS_OPTS -F"
985         eend 0
986         ;;
987     esac
988   fi
989
990   if [ -n "$MKFS" ] ; then
991     einfo "Running $MKFS $MKFS_OPTS on $TARGET"
992     "$MKFS" $MKFS_OPTS "$TARGET" ; RC=$?
993
994     if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
995       if ! echo "$MKFS" | grep -q "mkfs.ext" ; then
996         eerror "Not changing disk uuid for $TARGET because $MKFS doesn't seem to match for ext{2,3,4} file system"
997         eend 1
998         bailout 1
999       else
1000         einfo "Changing disk uuid for $TARGET to fixed (non-random) value $DISK_IDENTIFIER using tune2fs"
1001         tune2fs "$TARGET" -U "$DISK_IDENTIFIER"
1002         eend $?
1003       fi
1004     fi
1005
1006     # make sure /dev/disk/by-uuid/... is up2date, otherwise grub
1007     # will fail to detect the uuid in the chroot
1008     if [ -n "$VIRTUAL" ] ; then
1009       einfo "Virtual environment doesn't require blockdev --rereadpt, skipping therefore"
1010     elif echo "$TARGET" | grep -q "/dev/md" ; then
1011       blockdev --rereadpt "${TARGET}"
1012     else
1013       # if we deploy to /dev/sdX# then let's see if /dev/sdX exists
1014       local main_device="${TARGET%%[0-9]*}"
1015       # sanity check to not try to e.g. access /dev/loop if we get /dev/loop0
1016       if [ -f "/sys/block/$(basename ${main_device})/$(basename ${TARGET})/dev" ] ; then
1017         blockdev --rereadpt "$main_device"
1018       else
1019         einfo "No underlying block device for $TARGET identified, skipping blockdev --rereadpt."
1020       fi
1021     fi
1022     # give the system 2 seconds, otherwise we might run into
1023     # race conditions :-/
1024     sleep 2
1025
1026     eval "$(blkid -o udev "$TARGET" 2>/dev/null)"
1027     [ -n "$ID_FS_UUID" ] && TARGET_UUID="$ID_FS_UUID" || TARGET_UUID=""
1028
1029     eend $RC
1030   fi
1031 }
1032 # }}}
1033
1034 # modify filesystem settings {{{
1035 tunefs() {
1036   if [ -n "$TUNE2FS" ] && echo "$MKFS" | grep -q "mkfs.ext" ; then
1037      einfo "Disabling automatic filesystem check on $TARGET via tune2fs"
1038      $TUNE2FS "$TARGET"
1039      eend $?
1040   fi
1041 }
1042 # }}}
1043
1044 # mount the new partition or if it's a directory do nothing at all {{{
1045 mount_target() {
1046   if [ -n "$DIRECTORY" ] ; then
1047      einfo "Running grml-debootstrap on a directory, nothing to mount."
1048   else
1049      if grep -q "$TARGET" /proc/mounts ; then
1050         ewarn "$TARGET already mounted, continuing anyway." ; eend 0
1051      else
1052        if ! [ -d "${MNTPOINT}" ] ; then
1053           [ -n "$VIRTUAL" ] || mkdir -p "${MNTPOINT}"
1054        fi
1055        einfo "Mounting $TARGET to $MNTPOINT"
1056        mkdir -p "$MNTPOINT"
1057        mount -o rw,suid,dev "$TARGET" "$MNTPOINT"
1058        eend $?
1059      fi
1060   fi
1061   if [ -n "$ISODIR" ] ; then
1062      einfo "Mounting Debian image loopback to $MNTPOINT/$ISODIR."
1063      mkdir -p "$MNTPOINT/$ISODIR"
1064      mount --bind "$ISODIR" "$MNTPOINT/$ISODIR"
1065      eend $?
1066   fi
1067 }
1068 # }}}
1069
1070 # prepare VM image for usage with debootstrap {{{
1071 prepare_vm() {
1072   if [ -z "$VIRTUAL" ] ; then
1073      return 0 # be quiet by intention
1074   fi
1075
1076   if [ -b "$TARGET" -a -n "$VMFILE" ] ; then
1077      eerror "Error: specified virtual disk target ($TARGET) is an existing block device."
1078      eend 1
1079      bailout 1
1080   fi
1081   if [ ! -b "$TARGET" -a -z "$VMFILE" ] ; then
1082      eerror "Error: specified virtual disk target ($TARGET) does not exist yet."
1083      eend 1
1084      bailout 1
1085   fi
1086
1087   ORIG_TARGET="$TARGET" # store for later reuse
1088
1089   if [ -n "$VMFILE" ]; then
1090     qemu-img create -f raw "${TARGET}" "${VMSIZE}"
1091   fi
1092   echo 4 66 | /usr/share/grml-debootstrap/bootgrub.mksh -A | dd of="$TARGET" conv=notrunc
1093   dd if=/dev/zero bs=1 conv=notrunc count=64 seek=446 of="$TARGET"
1094   if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1095     einfo "Adjusting disk signature to a fixed (non-random) value"
1096     MBRTMPFILE=$(mktemp)
1097     dd if="${TARGET}" of="${MBRTMPFILE}" bs=512 count=1
1098     echo -en "\x41\x41\x41\x41" | dd of="${MBRTMPFILE}" conv=notrunc seek=440 bs=1
1099     dd if="${MBRTMPFILE}" of="${TARGET}" conv=notrunc
1100     eend $?
1101   fi
1102   parted -s "${TARGET}" 'mkpart primary ext4 2M -1'
1103
1104   # if dm-mod isn't available then kpartx will fail with
1105   # "Is device-mapper driver missing from kernel? [...]"
1106   if ! kpartx -av "$TARGET" >/dev/null 2>&1 || ! grep -q 'device-mapper' /proc/misc >/dev/null 2>&1 ; then
1107     einfo "Device-mapper not ready yet, trying to load dm-mod module."
1108     modprobe dm-mod ; eend $?
1109   fi
1110
1111   # make sure loop module is present
1112   if ! losetup -f >/dev/null 2>&1; then
1113     einfo "Can not find a usable loop device, retrying after loading loop module."
1114     modprobe loop
1115     if losetup -f >/dev/null 2>&1; then
1116       einfo "Found a usable loop device now, continuing."
1117     else
1118       eerror "Error finding usable loop device" ; eend 1
1119       bailout 1
1120     fi
1121   fi
1122
1123   DEVINFO=$(kpartx -asv "$TARGET") # 'add map loop1p1 (253:0): 0 6289408 linear /dev/loop1 2048'
1124   if [ -z "${DEVINFO}" ] ; then
1125     eerror "Error setting up loopback device." ; eend 1
1126     bailout 1
1127   fi
1128
1129   # hopefully this always works as expected
1130   LOOP=$(echo "${DEVINFO}" | sed 's/.* linear //; s/ [[:digit:]]*//') # 'loop1'
1131   LOOP_PART="$(echo "${DEVINFO##add map }" | sed 's/ .*//')" # 'loop1p1'
1132   export TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop1p1'
1133
1134   if [ -z "$TARGET" ] ; then
1135      eerror "Error: target could not be set to according /dev/mapper/* device." ; eend 1
1136      bailout 1
1137   fi
1138 }
1139 # }}}
1140
1141 # make VM image bootable and unmount it {{{
1142 finalize_vm() {
1143   if [ -z "${VIRTUAL}" ] ; then
1144      return 0
1145   fi
1146
1147   if ! mount "${TARGET}" "${MNTPOINT}" ; then
1148     eerror "Error: Mounting ${TARGET} failed, can not continue." ; eend 1
1149     bailout 1
1150   fi
1151
1152   mount -t proc none "${MNTPOINT}"/proc
1153   mount -t sysfs none "${MNTPOINT}"/sys
1154   mount --bind /dev "${MNTPOINT}"/dev
1155   mount --bind /dev/pts "${MNTPOINT}"/dev/pts
1156
1157 # Has chroot-script installed GRUB to MBR using grub-install (successfully), already?
1158 # chroot-script skips installation for unset ${GRUB}
1159 if [[ -z "${GRUB}" ]] || ! dd if="${GRUB}" bs=512 count=1 2>/dev/null | cat -v | fgrep -q GRUB; then
1160   einfo "Installing Grub as bootloader."
1161
1162   if ! chroot "${MNTPOINT}" dpkg --list grub-pc 2>/dev/null | grep -q '^ii' ; then
1163     echo "Notice: grub-pc package not present yet, installing it therefore."
1164     DEBIAN_FRONTEND=$DEBIAN_FRONTEND chroot "$MNTPOINT" apt-get -y install $DPKG_OPTIONS grub-pc
1165   fi
1166
1167   mkdir -p "${MNTPOINT}/boot/grub"
1168   if ! [ -d "${MNTPOINT}"/usr/lib/grub/i386-pc/ ] ; then
1169      eerror "Error: grub not installed inside Virtual Machine. Can not install bootloader." ; eend 1
1170      bailout 1
1171   fi
1172
1173   case "$RELEASE" in
1174     lenny|squeeze|wheezy)
1175       cp "${MNTPOINT}"/usr/lib/grub/i386-pc/* "${MNTPOINT}/boot/grub/"
1176       ;;
1177     *)
1178       cp -a "${MNTPOINT}"/usr/lib/grub/i386-pc "${MNTPOINT}/boot/grub/"
1179       ;;
1180   esac
1181   chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos ext2
1182   dd if="${MNTPOINT}/tmp/core.img" of="${ORIG_TARGET}" conv=notrunc seek=4
1183   rm -f "${MNTPOINT}/tmp/core.img"
1184 fi
1185
1186   einfo "Updating grub configuration file."
1187   if [ -n "$BOOT_APPEND" ] ; then
1188      sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" "${MNTPOINT}"/etc/default/grub
1189   fi
1190   chroot "${MNTPOINT}" update-grub
1191
1192   case "$RELEASE" in
1193     jessie)
1194       einfo "Applying workaround for GRUB font path bug in jessie (Debian #787685)."
1195       mkdir -p "${MNTPOINT}/boot/grub/fonts/"
1196       cp "${MNTPOINT}/usr/share/grub/unicode.pf2" "${MNTPOINT}/boot/grub/fonts/"
1197       ;;
1198   esac
1199
1200   case "$RELEASE" in
1201     lenny|squeeze|wheezy)
1202       einfo "Adjusting grub.cfg for successful boot sequence."
1203       sed -i "s;root=[^ ]\+;root=UUID=$TARGET_UUID;" "${MNTPOINT}"/boot/grub/grub.cfg
1204       ;;
1205   esac
1206
1207   umount "${MNTPOINT}"/proc
1208   umount "${MNTPOINT}"/sys
1209   umount "${MNTPOINT}"/dev/pts
1210   try_umount 3 "${MNTPOINT}"/dev
1211   umount "${MNTPOINT}"
1212   kpartx -d "${ORIG_TARGET}" >/dev/null
1213 }
1214 # }}}
1215
1216 # install main chroot {{{
1217 debootstrap_system() {
1218   if [ "$_opt_nodebootstrap" ]; then
1219      einfo "Skipping debootstrap as requested."
1220      return
1221   fi
1222
1223   if grep -q "$MNTPOINT" /proc/mounts || [ -n "$DIRECTORY" ] ; then
1224     :
1225   else
1226     eerror "Error: $MNTPOINT not mounted, can not continue."
1227     eend 1 ; exit 1
1228   fi
1229
1230   if [ -n "$ISO" ] ; then
1231     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${ISO}"
1232     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $ISO"
1233     "$DEBOOTSTRAP" $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$ISO"
1234     RC=$?
1235   else
1236     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${MIRROR}"
1237     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $MIRROR"
1238     "$DEBOOTSTRAP" $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$MIRROR"
1239     RC=$?
1240   fi
1241
1242   if [ $RC -ne 0 ] ; then
1243     if [ -r "$MNTPOINT/debootstrap/debootstrap.log" ] && \
1244       [ -s "$MNTPOINT/debootstrap/debootstrap.log" ] ; then
1245       einfo "Presenting last ten lines of debootstrap.log:"
1246       tail -10 "${MNTPOINT}"/debootstrap/debootstrap.log
1247       einfo "End of debootstrap.log"
1248     fi
1249   fi
1250
1251   eend $RC
1252 }
1253 # }}}
1254
1255 # prepare chroot via chroot-script {{{
1256 preparechroot() {
1257   einfo "Preparing chroot system"
1258
1259   # provide variables to chroot system
1260   CHROOT_VARIABLES="/var/cache/grml-debootstrap/variables_${SHORT_TARGET}"
1261   touch "$CHROOT_VARIABLES"
1262   chmod 600 "$CHROOT_VARIABLES" # make sure nobody except root can read it
1263   echo "# Configuration of ${PN}"                                                                                   > "$CHROOT_VARIABLES"
1264   # Resorting to sed(1) for escaping since "VAR='${VAR//\'/\'\\\'\'}'" does not work with all versions of Bash,
1265   #   e.g. not with 4.2.37(1)-release (a.k.a 4.2+dfsg-0.1+deb7u3) of Debian wheezy
1266   [ -n "$ARCH" ]                && echo "ARCH='$(sed "s,','\\\\'',g" <<<"${ARCH}")'"                               >> "$CHROOT_VARIABLES"
1267   [ -n "$BACKPORTREPOS" ]       && echo "BACKPORTREPOS='$(sed "s,','\\\\'',g" <<<"${BACKPORTREPOS}")'"             >> "$CHROOT_VARIABLES"
1268   [ -n "$CHROOT_SCRIPTS" ]      && echo "CHROOT_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${CHROOT_SCRIPTS}")'"           >> "$CHROOT_VARIABLES"
1269   [ -n "$COMPONENTS" ]          && echo "COMPONENTS='$(sed "s,','\\\\'',g" <<<"${COMPONENTS}")'"                   >> "$CHROOT_VARIABLES"
1270   [ -n "$CONFFILES" ]           && echo "CONFFILES='$(sed "s,','\\\\'',g" <<<"${CONFFILES}")'"                     >> "$CHROOT_VARIABLES"
1271   [ -n "$DEBCONF" ]             && echo "DEBCONF='$(sed "s,','\\\\'',g" <<<"${DEBCONF}")'"                         >> "$CHROOT_VARIABLES"
1272   [ -n "$DEBIAN_FRONTEND" ]     && echo "DEBIAN_FRONTEND='$(sed "s,','\\\\'',g" <<<"${DEBIAN_FRONTEND}")'"         >> "$CHROOT_VARIABLES"
1273   [ -n "$DEBOOTSTRAP" ]         && echo "DEBOOTSTRAP='$(sed "s,','\\\\'',g" <<<"${DEBOOTSTRAP}")'"                 >> "$CHROOT_VARIABLES"
1274   [ -n "$DEFAULT_LOCALES" ]     && echo "DEFAULT_LOCALES='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LOCALES}")'"         >> "$CHROOT_VARIABLES"
1275   [ -n "$DEFAULT_LANGUAGE" ]    && echo "DEFAULT_LANGUAGE='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LANGUAGE}")'"       >> "$CHROOT_VARIABLES"
1276   [ -n "$EXTRAPACKAGES" ]       && echo "EXTRAPACKAGES='$(sed "s,','\\\\'',g" <<<"${EXTRAPACKAGES}")'"             >> "$CHROOT_VARIABLES"
1277   [ -n "$FALLBACK_MIRROR" ]     && echo "FALLBACK_MIRROR='$(sed "s,','\\\\'',g" <<<"${FALLBACK_MIRROR}")'"         >> "$CHROOT_VARIABLES"
1278   [ -n "$FORCE" ]               && echo "FORCE='$(sed "s,','\\\\'',g" <<<"${FORCE}")'"                             >> "$CHROOT_VARIABLES"
1279   [ -n "$GRMLREPOS" ]           && echo "GRMLREPOS='$(sed "s,','\\\\'',g" <<<"${GRMLREPOS}")'"                     >> "$CHROOT_VARIABLES"
1280   [ -n "$GRUB" ]                && echo "GRUB='$(sed "s,','\\\\'',g" <<<"${GRUB}")'"                               >> "$CHROOT_VARIABLES"
1281   [ -n "$HOSTNAME" ]            && echo "HOSTNAME='$(sed "s,','\\\\'',g" <<<"${HOSTNAME}")'"                       >> "$CHROOT_VARIABLES"
1282   [ -n "$INITRD" ]              && echo "INITRD='$(sed "s,','\\\\'',g" <<<"${INITRD}")'"                           >> "$CHROOT_VARIABLES"
1283   [ -n "$INSTALL_NOTES" ]       && echo "INSTALL_NOTES='$(sed "s,','\\\\'',g" <<<"${INSTALL_NOTES}")'"             >> "$CHROOT_VARIABLES"
1284   [ -n "$ISODIR" ]              && echo "ISODIR='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                              >> "$CHROOT_VARIABLES"
1285   [ -n "$ISO" ]                 && echo "ISO='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                                 >> "$CHROOT_VARIABLES"
1286   [ -n "$KEEP_SRC_LIST" ]       && echo "KEEP_SRC_LIST='$(sed "s,','\\\\'',g" <<<"${KEEP_SRC_LIST}")'"             >> "$CHROOT_VARIABLES"
1287   [ -n "$LOCALES" ]             && echo "LOCALES='$(sed "s,','\\\\'',g" <<<"${LOCALES}")'"                         >> "$CHROOT_VARIABLES"
1288   [ -n "$MIRROR" ]              && echo "MIRROR='$(sed "s,','\\\\'',g" <<<"${MIRROR}")'"                           >> "$CHROOT_VARIABLES"
1289   [ -n "$MKFS" ]                && echo "MKFS='$(sed "s,','\\\\'',g" <<<"${MKFS}")'"                               >> "$CHROOT_VARIABLES"
1290   [ -n "$NOPASSWORD" ]          && echo "NOPASSWORD=\"true\""                                                      >> "$CHROOT_VARIABLES"
1291   [ -n "$NOKERNEL" ]            && echo "NOKERNEL=\"true\""                                                        >> "$CHROOT_VARIABLES"
1292   [ -n "$PACKAGES" ]            && echo "PACKAGES='$(sed "s,','\\\\'',g" <<<"${PACKAGES}")'"                       >> "$CHROOT_VARIABLES"
1293   [ -n "$POST_SCRIPTS" ]        && echo "POST_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${POST_SCRIPTS}")'"               >> "$CHROOT_VARIABLES"
1294   [ -n "$PRE_SCRIPTS" ]         && echo "PRE_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${PRE_SCRIPTS}")'"                 >> "$CHROOT_VARIABLES"
1295   [ -n "$RECONFIGURE" ]         && echo "RECONFIGURE='$(sed "s,','\\\\'',g" <<<"${RECONFIGURE}")'"                 >> "$CHROOT_VARIABLES"
1296   [ -n "$RELEASE" ]             && echo "RELEASE='$(sed "s,','\\\\'',g" <<<"${RELEASE}")'"                         >> "$CHROOT_VARIABLES"
1297   [ -n "$RM_APTCACHE" ]         && echo "RM_APTCACHE='$(sed "s,','\\\\'',g" <<<"${RM_APTCACHE}")'"                 >> "$CHROOT_VARIABLES"
1298   [ -n "$ROOTPASSWORD" ]        && echo "ROOTPASSWORD='$(sed "s,','\\\\'',g" <<<"${ROOTPASSWORD}")'"               >> "$CHROOT_VARIABLES"
1299   [ -n "$SCRIPTS" ]             && echo "SCRIPTS='$(sed "s,','\\\\'',g" <<<"${SCRIPTS}")'"                         >> "$CHROOT_VARIABLES"
1300   [ -n "$SECURE" ]              && echo "SECURE='$(sed "s,','\\\\'',g" <<<"${SECURE}")'"                           >> "$CHROOT_VARIABLES"
1301   [ -n "$SELECTED_PARTITIONS" ] && echo "SELECTED_PARTITIONS='$(sed "s,','\\\\'',g" <<<"${SELECTED_PARTITIONS}")'" >> "$CHROOT_VARIABLES"
1302   [ -n "$TARGET" ]              && echo "TARGET='$(sed "s,','\\\\'',g" <<<"${TARGET}")'"                           >> "$CHROOT_VARIABLES"
1303   [ -n "$UPGRADE_SYSTEM" ]      && echo "UPGRADE_SYSTEM='$(sed "s,','\\\\'',g" <<<"${UPGRADE_SYSTEM}")'"           >> "$CHROOT_VARIABLES"
1304   [ -n "$TARGET_UUID" ]         && echo "TARGET_UUID='$(sed "s,','\\\\'',g" <<<"${TARGET_UUID}")'"                 >> "$CHROOT_VARIABLES"
1305   [ -n "$TIMEZONE" ]            && echo "TIMEZONE='$(sed "s,','\\\\'',g" <<<"${TIMEZONE}")'"                       >> "$CHROOT_VARIABLES"
1306   [ -n "$TUNE2FS" ]             && echo "TUNE2FS='$(sed "s,','\\\\'',g" <<<"${TUNE2FS}")'"                         >> "$CHROOT_VARIABLES"
1307   [ -n "$VMSIZE" ]              && echo "VMSIZE='$(sed "s,','\\\\'',g" <<<"${VMSIZE}")'"                           >> "$CHROOT_VARIABLES"
1308
1309   cp $VERBOSE "${CONFFILES}"/chroot-script "${MNTPOINT}"/bin/chroot-script
1310   chmod 755 "${MNTPOINT}"/bin/chroot-script
1311   [ -d "$MNTPOINT"/etc/debootstrap/ ] || mkdir "$MNTPOINT"/etc/debootstrap/
1312
1313   # make sure we have our files for later use via chroot-script
1314   cp $VERBOSE "${CONFFILES}/config"           "${MNTPOINT}"/etc/debootstrap/
1315   # make sure we adjust the configuration variables accordingly:
1316   sed -i "s#RELEASE=.*#RELEASE=\"$RELEASE\"#" "${MNTPOINT}"/etc/debootstrap/config
1317   sed -i "s#TARGET=.*#TARGET=\"$TARGET\"#"    "${MNTPOINT}"/etc/debootstrap/config
1318   sed -i "s#GRUB=.*#GRUB=\"$GRUB\"#"          "${MNTPOINT}"/etc/debootstrap/config
1319
1320   # install notes:
1321   if [ -n "$INSTALL_NOTES" ] ; then
1322      [ -r "$INSTALL_NOTES" ] && cp "$INSTALL_NOTES" "${MNTPOINT}"/etc/debootstrap/
1323   fi
1324
1325   # package selection:
1326   if [ "$PACKAGES" = 'yes' ] ; then
1327     cp $VERBOSE "${_opt_packages:-$CONFFILES/packages}" \
1328       "${MNTPOINT}"/etc/debootstrap/packages
1329   fi
1330
1331   # debconf preseeding:
1332   _opt_debconf=${_opt_debconf:-$CONFFILES/debconf-selections}
1333   [ -f "${_opt_debconf}" ] && [ "$DEBCONF" = 'yes' ] && \
1334     cp $VERBOSE "${_opt_debconf}" "${MNTPOINT}"/etc/debootstrap/debconf-selections
1335
1336   # copy scripts that should be executed inside the chroot:
1337   _opt_chroot_scripts=${_opt_chroot_scripts:-$CONFFILES/chroot-scripts/}
1338   [ -d "$_opt_chroot_scripts" ] && [ "$CHROOT_SCRIPTS" = 'yes' ] && {
1339     mkdir -p "${MNTPOINT}"/etc/debootstrap/chroot-scripts
1340     cp -a $VERBOSE "${_opt_chroot_scripts}"/* "${MNTPOINT}"/etc/debootstrap/chroot-scripts/
1341   }
1342
1343   # notice: do NOT use $CHROOT_VARIABLES inside chroot but statically file instead!
1344   cp $VERBOSE "${CHROOT_VARIABLES}" "${MNTPOINT}"/etc/debootstrap/variables
1345
1346   cp $VERBOSE -a -L "${CONFFILES}"/extrapackages/ "${MNTPOINT}"/etc/debootstrap/
1347
1348   # make sure we can access network [relevant for cdebootstrap]
1349   [ -f "${MNTPOINT}"/etc/resolv.conf ] || cp $VERBOSE /etc/resolv.conf "${MNTPOINT}"/etc/resolv.conf
1350
1351   # provide system's /etc/hosts to the target:
1352   if ! [ -f "$MNTPOINT/etc/hosts" ] ; then
1353      cp $VERBOSE /etc/hosts "${MNTPOINT}"/etc/hosts
1354   fi
1355
1356   # setup default locales
1357   [ -n "$LOCALES" ] && cp $VERBOSE "${CONFFILES}"/locale.gen "${MNTPOINT}"/etc/locale.gen
1358
1359   # MAKEDEV is just a forking bomb crap, let's do it on our own instead :)
1360   ( cd "${MNTPOINT}"/dev && tar zxf /etc/debootstrap/devices.tar.gz )
1361
1362   # copy any existing files to chroot
1363   [ -d "${CONFFILES}"/bin   ] && cp $VERBOSE -a -L "${CONFFILES}"/bin/*   "${MNTPOINT}"/bin/
1364   [ -d "${CONFFILES}"/boot  ] && cp $VERBOSE -a -L "${CONFFILES}"/boot/*  "${MNTPOINT}"/boot/
1365   [ -d "${CONFFILES}"/etc   ] && cp $VERBOSE -a -L "${CONFFILES}"/etc/*   "${MNTPOINT}"/etc/
1366   [ -d "${CONFFILES}"/sbin  ] && cp $VERBOSE -a -L "${CONFFILES}"/sbin/*  "${MNTPOINT}"/sbin/
1367   [ -d "${CONFFILES}"/share ] && cp $VERBOSE -a -L "${CONFFILES}"/share/* "${MNTPOINT}"/share/
1368   [ -d "${CONFFILES}"/usr   ] && cp $VERBOSE -a -L "${CONFFILES}"/usr/*   "${MNTPOINT}"/usr/
1369   [ -d "${CONFFILES}"/var   ] && cp $VERBOSE -a -L "${CONFFILES}"/var/*   "${MNTPOINT}"/var/
1370
1371   # network setup
1372   DEFAULT_INTERFACES="# /etc/network/interfaces - generated by grml-debootstrap
1373
1374 # Include files from /etc/network/interfaces.d when using
1375 # ifupdown v0.7.44 or newer:
1376 #source-directory /etc/network/interfaces.d
1377
1378 auto lo
1379 iface lo inet loopback
1380
1381 allow-hotplug eth0
1382 iface eth0 inet dhcp
1383 "
1384
1385   if [ -n "$NOINTERFACES" ] ; then
1386     einfo "Not installing /etc/network/interfaces as requested via --nointerfaces option" ; eend 0
1387   elif [ -n "$USE_DEFAULT_INTERFACES" ] ; then
1388     einfo "Installing default /etc/network/interfaces as requested via --defaultinterfaces options."
1389     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1390     eend $?
1391   elif [ -n "$VIRTUAL" ] ; then
1392     einfo "Setting up Virtual Machine, installing default /etc/network/interfaces"
1393     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1394     eend $?
1395   elif [ -r /etc/network/interfaces ] ; then
1396     einfo "Copying /etc/network/interfaces from host to target system"
1397     cp $VERBOSE /etc/network/interfaces "${MNTPOINT}/etc/network/interfaces"
1398     eend $?
1399   else
1400     ewarn "Couldn't read /etc/network/interfaces, installing default /etc/network/interfaces"
1401     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1402     eend $?
1403   fi
1404
1405   # install config file providing some example entries
1406   if [ -r /etc/network/interfaces.examples -a ! -r "$MNTPOINT/etc/network/interfaces.examples" ] ; then
1407      cp /etc/network/interfaces.examples "$MNTPOINT/etc/network/interfaces.examples"
1408   fi
1409
1410   eend 0
1411 }
1412 # }}}
1413
1414 # execute all scripts in /etc/debootstrap/pre-scripts/ {{{
1415 execute_pre_scripts() {
1416   # make sure hostname is set even before chroot-script get executed
1417   echo "$HOSTNAME" > /etc/hostname
1418
1419   # make sure we have $MNTPOINT available for our scripts
1420   export MNTPOINT
1421
1422   if [ -d "$_opt_pre_scripts" ] || [ "$PRE_SCRIPTS" = 'yes' ] ; then
1423     [ -d "$_opt_pre_scripts" ] && pre_scripts="$_opt_pre_scripts" || pre_scripts="${CONFFILES}/pre-scripts/"
1424     for script in "${pre_scripts}"/* ; do
1425       if [ -x "$script" ] ; then
1426         einfo "Executing pre-script $script"
1427         "$script" ; eend $?
1428       fi
1429     done
1430   fi
1431 }
1432 # }}}
1433
1434 # execute all scripts in /etc/debootstrap/post-scripts/ {{{
1435 execute_post_scripts() {
1436   # make sure we have $MNTPOINT available for our scripts
1437   export MNTPOINT
1438
1439   if [ -d "$_opt_scripts" ] || [ "$SCRIPTS"  = 'yes'] ; then
1440     # legacy support for /etc/debootstrap/scripts/
1441     [ -d "$_opt_scripts" ] && post_scripts="$_opt_scripts" || post_scripts="${CONFFILES}/scripts/"
1442     ewarn "Deprecation NOTE: --scripts/SCRIPTS are deprecated, please switch to --post-scripts/POST_SCRIPTS instead."
1443   elif [ -d "$_opt_post_scripts" ] || [ "$POST_SCRIPTS" = 'yes' ] ; then
1444     [ -d "$_opt_post_scripts" ] && post_scripts="$_opt_post_scripts" || post_scripts="${CONFFILES}/post-scripts/"
1445   fi
1446
1447   if [ -n "$post_scripts" ] ; then
1448     for script in "${post_scripts}"/* ; do
1449       if [ -x "$script" ] ; then
1450         einfo "Executing post-script $script"
1451         "$script" ; eend $?
1452       fi
1453     done
1454   fi
1455 }
1456 # }}}
1457
1458 try_umount() {
1459   local tries=$1
1460   local mountpoint="$2"
1461
1462   for (( try=1; try<=tries; try++ )); do
1463     if [[ ${try} -eq ${tries} ]]; then
1464       # Last time, show errors this time
1465       umount "${mountpoint}" && return 0
1466     else
1467       # Not last time, hide errors until fatal
1468       if umount "${mountpoint}" 2>/dev/null ; then
1469         return 0
1470       else
1471         sleep 1
1472       fi
1473     fi
1474   done
1475   return 1  # Tried enough
1476 }
1477
1478 # execute chroot-script {{{
1479 chrootscript() {
1480   if ! [ -r "$MNTPOINT/bin/chroot-script" ] ; then
1481     mount_target
1482   fi
1483
1484   if ! [ -x "$MNTPOINT/bin/chroot-script" ] ; then
1485     eerror "Fatal: $MNTPOINT/bin/chroot-script could not be found."
1486     eend 1
1487   else
1488     einfo "Executing chroot-script now"
1489     mount --bind /dev "$MNTPOINT"/dev
1490     mount --bind /dev/pts "$MNTPOINT"/dev/pts
1491     if [ "$DEBUG" = "true" ] ; then
1492       chroot "$MNTPOINT" /bin/bash -x /bin/chroot-script ; RC=$?
1493     else
1494       chroot "$MNTPOINT" /bin/chroot-script ; RC=$?
1495     fi
1496     try_umount 3 "$MNTPOINT"/dev/pts
1497     try_umount 3 "$MNTPOINT"/dev
1498     eend $RC
1499   fi
1500
1501   # finally get rid of chroot-script again, there's no good reason to
1502   # keep it on the installed system
1503   if grep -q GRML_CHROOT_SCRIPT_MARKER "${MNTPOINT}/bin/chroot-script" ; then
1504     einfo "Removing chroot-script again"
1505     rm -f "${MNTPOINT}/bin/chroot-script"
1506     eend $?
1507   else
1508     einfo "Keeping chroot-script as string GRML_CHROOT_SCRIPT_MARKER could not be found"
1509     eend 0
1510   fi
1511 }
1512 # }}}
1513
1514 # unmount $MNTPOINT {{{
1515 umount_chroot() {
1516
1517   # display installation notes:
1518   if [ -n "$INSTALL_NOTES" ] ; then
1519      [ -r "${MNTPOINT}/${INSTALL_NOTES}" ] && cat "${MNTPOINT}/${INSTALL_NOTES}"
1520   fi
1521
1522   if [ -n "$ISODIR" ] ; then
1523      if grep -q "$ISODIR" /proc/mounts ; then
1524         einfo "Unmount $MNTPOINT/$ISODIR"
1525         umount "$MNTPOINT/$ISODIR"
1526         eend $?
1527      fi
1528   fi
1529
1530   if grep -q "$MNTPOINT" /proc/mounts ; then
1531      if [ -n "$PARTITION" ] ; then
1532         einfo "Unmount $MNTPOINT"
1533         umount "$MNTPOINT"
1534         eend $?
1535      fi
1536   fi
1537 }
1538 # }}}
1539
1540 # execute filesystem check {{{
1541 fscktool() {
1542  if [ -n "$VIRTUAL" ] ; then
1543    einfo "Skipping filesystem check because we deploy a virtual machine."
1544    return 0
1545  fi
1546
1547  if [ "$FSCK" = 'yes' ] ; then
1548    [ -n "$FSCKTOOL" ] || FSCKTOOL="fsck.${MKFS#mkfs.}"
1549    einfo "Checking filesystem on $TARGET using $FSCKTOOL"
1550    "$FSCKTOOL" "$TARGET"
1551    eend $?
1552  fi
1553 }
1554 # }}}
1555
1556 # now execute all the functions {{{
1557 for i in prepare_vm mkfs tunefs mount_target debootstrap_system \
1558          preparechroot execute_pre_scripts chrootscript execute_post_scripts \
1559          umount_chroot finalize_vm fscktool ; do
1560     if stage "${i}" ; then
1561       if "$i" ; then
1562         stage "${i}" 'done' && rm -f "${STAGES}/${i}"
1563       else
1564         bailout 2 "$i"
1565       fi
1566     fi
1567 done
1568
1569 cleanup
1570 # }}}
1571
1572 # end dialog of autoinstallation {{{
1573 if [ -n "$AUTOINSTALL" ] ; then
1574    if dialog --title "${PN}" --pause "Finished execution of ${PN}.
1575 Automatically rebooting in 10 seconds.
1576
1577 Choose Cancel to skip rebooting." 10 60 10 ; then
1578      noeject noprompt reboot
1579   fi
1580 else
1581    einfo "Finished execution of ${PN}. Enjoy your Debian system." ; eend 0
1582 fi
1583 # }}}
1584
1585 ## END OF FILE #################################################################
1586 # vim: ai tw=100 expandtab foldmethod=marker shiftwidth=2