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