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