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