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