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