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