Fix detection of predictable network interface names
[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 https://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 "$(command -v "$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://deb.debian.org/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 "$POST_SCRIPTS" ] || POST_SCRIPTS='yes'
73 [ -n "$PRE_SCRIPTS" ] || PRE_SCRIPTS='yes'
74 [ -n "$RECONFIGURE" ] || RECONFIGURE='console-data'
75 [ -n "$RELEASE" ] || RELEASE='buster'
76 [ -n "$RM_APTCACHE" ] || RM_APTCACHE='yes'
77 [ -n "$SCRIPTS" ] || SCRIPTS='no' # deprecated, replaced by POST_SCRIPTS
78 [ -n "$SECURE" ] || SECURE='yes'
79 [ -n "$TIMEZONE" ] || TIMEZONE='Europe/Vienna'
80 [ -n "$TUNE2FS" ] || TUNE2FS='tune2fs -c0 -i0'
81 [ -n "$UPGRADE_SYSTEM" ] || UPGRADE_SYSTEM='yes'
82 [ -n "$VMSIZE" ] || VMSIZE="2G"
83 [ -n "$GRUB_INSTALL" ] || GRUB_INSTALL='yes'
84
85 # inside the chroot system locales might not be available, so use minimum:
86 export LANG=C
87 export LC_ALL=C
88 export LANGUAGE=C
89
90 # make sure interactive mode is only executed when
91 # using an empty configuration file or option --interactive
92 INTERACTIVE=''
93 # }}}
94
95 # help text {{{
96 usage() {
97   echo "$PN - wrapper around debootstrap for installing Debian
98
99 Usage: $PN [options]
100
101 Bootstrap options:
102
103   -m, --mirror <URL>     Mirror which should be used for apt-get/aptitude.
104   -i, --iso <mnt>        Mountpoint where a Debian ISO is mounted to, for use
105                          instead of fetching packages from a mirror.
106   -r, --release <name>   Release of new Debian system (default: buster).
107   -t, --target <target>  Target partition (/dev/...) or directory where the
108                          system should be installed to.
109   -p, --mntpoint <mnt>   Mountpoint used for mounting the target system,
110                          has no effect if -t is given and represents a directory.
111       --debopt <params>  Extra parameters passed to the debootstrap command.
112       --interactive      Use interactive mode (frontend).
113       --nodebootstrap    Skip debootstrap, only do configuration to the target.
114       --grub <device>    Target for grub installation. Usage example: /dev/sda
115       --efi <device>     Target for EFI installation. Usage example: /dev/sda1
116       --arch <arch>      Set target architecture, use for installing i386 on amd64.
117       --filesystem <fs>  Filesystem that should be used when target is a partition
118                          or Virtual Machine (see --vmfile).
119       --force            Do not prompt for user acknowledgement.
120
121 Options for Virtual Machine deployment:
122
123       --vm               Set up a Virtual Machine on an existing block device
124                          instead of plainly installing to a partition or
125                          directory. Needs to be combined with --target.
126                          Example: --vm --target /dev/mapper/your-vm-disk
127       --vmfile           Like --vm, but install into a regular file (created by
128                          'qemu-img create -f raw ...') instead.
129                          Example: --vmfile --target /mnt/sda1/qemu.img
130       --vmsize <size>    Use specified size for size of VM file (default: 2G).
131                          Syntax as supported by qemu-img, like: --vmsize 3G
132
133 Configuration options:
134
135   -c, --config <file>      Use specified configuration file, defaults to
136                              /etc/debootstrap/config
137   -d, --confdir <path>     Place of config files for debootstrap, defaults
138                              to /etc/debootstrap
139       --packages <file>    Install packages defined in specified list file
140                              instead of using /etc/debootstrap/packages.
141       --nopackages         Skip installation of packages defined in
142                              /etc/debootstrap/packages
143       --nokernel           Skip installation of default kernel images.
144       --nointerfaces       Do not copy /etc/network/interfaces from host system
145                            to target system.
146                            (This option is automatically enabled when using --vmfile.)
147       --defaultinterfaces  Install a default /etc/network/interfaces file (enabling
148                            DHCP for eth0) instead of taking over config from host system.
149       --debconf <file>     Pre-seed packages using specified pre-seed db file.
150       --grmlrepos          Enable Grml's Debian repository (deb.grml.org).
151       --backportrepos      Enable Debian's backports repository (backports.debian.org).
152       --keep_src_list      Do not overwrite user provided apt sources.list.
153       --contrib            Enable 'contrib' in COMPONENTS (defaults to 'main' only).
154       --non-free           Enable non-free in COMPONENTS (defaults to 'main' only).
155       --hostname <name>    Hostname of Debian system.
156       --nopassword         Do not prompt for the root password.
157       --password <pwd>     Use specified password as password for user root.
158       --sshcopyid          Use locally available public keys to authorise root login on the target system.
159       --bootappend <line>  Add specified appendline to kernel whilst booting.
160       --chroot-scripts <d> Execute chroot scripts from specified directory.
161       --pre-scripts <dir>  Execute scripts from specified directory (before chroot-scripts).
162       --scripts <dir>      Execute scripts from specified directory (after chroot-scripts).
163       --remove-configs     Delete grml-debootstrap configuration files from installed system.
164
165 Other options:
166
167   -v, --verbose            Increase verbosity.
168       --debug              Execute in very verbose way.
169   -h, --help               Print this usage information and exit.
170   -V, --version            Show summary of options and exit.
171
172 Usage examples can be found in the grml-debootstrap manpage.
173 Send bugreports to the grml-team: bugs (at) grml.org || https://grml.org/bugs/
174 "
175 }
176
177 if [ "$1" = '-h' ] || [ "$1" = '-help' ] || [ "$1" = "--help" ] ; then
178    usage
179    echo 'Please notice that this script requires root permissions!'
180    exit 0
181 fi
182 # }}}
183
184 # early helper functions {{{
185 GOOD='\e[32;01m'
186 BAD='\e[31;01m'
187 WARN='\e[33;01m'
188 NORMAL='\e[0m'
189
190 einfo() {
191   einfon "$1\\n"
192   return 0
193 }
194
195 einfon() {
196   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
197   printf " %s*%s $*" "${GOOD}" "${NORMAL}"
198   LAST_E_CMD=einfon
199   return 0
200 }
201
202 ewarn() {
203   printf " %s*%s $*\\n" "${WARN}" "${NORMAL}"
204   return 0
205 }
206
207 eerror() {
208   [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
209   printf " %s*%s $*\\n" "${BAD}" "${NORMAL}" >&2
210   LAST_E_CMD=eerror
211   return 0
212 }
213
214 eend() {
215   local retval="${1:-0}"
216   shift
217   if [ "$retval" -gt 0 ]; then
218     printf " %s-> Failed (rc=%s)%s\\n" "${BAD}" "${retval}" "${NORMAL}"
219   fi
220   return "$retval"
221 }
222
223 check4root(){
224   if [ "$(id -u 2>/dev/null)" != 0 ] ; then
225     echo 1>&2 "Error: please run this script with uid 0 (root)." ; return 1
226   fi
227 }
228
229 check4progs(){
230   local RC=''
231   for arg in "$@" ; do
232     command -v "$arg" >/dev/null 2>&1 || RC="$arg"
233   done
234   if [ -n "$RC" ] ; then
235      echo "$RC not installed"
236      return 1
237   fi
238 }
239 # }}}
240
241 # helper functions {{{
242 cleanup() {
243   if [ -n "$CHROOT_VARIABLES" ] ; then
244     einfo "Removing ${CHROOT_VARIABLES}" ; rm "$CHROOT_VARIABLES" ; eend $?
245   fi
246
247   if [ -n "$STAGES" ] ; then
248     einfo "Removing ${STAGES}" ; rmdir "$STAGES" ; eend $?
249   fi
250
251   # Remove temporary mountpoint again
252   if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
253     rmdir "$MNTPOINT" 2>/dev/null
254   fi
255
256   # make sure $TARGET is not mounted when exiting grml-debootstrap
257   if [ -n "$MNTPOINT" ] ; then
258     if grep -q "$MNTPOINT" /proc/mounts ; then
259       # make sure nothing is left inside chroot so we can unmount it
260       for service in ssh mdadm ; do
261         if [ -x "${MNTPOINT}/etc/init.d/${service}" ] ; then
262           chroot "$MNTPOINT" "/etc/init.d/${service}" stop
263         fi
264       done
265
266       [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount -a >/dev/null 2>&1
267
268       # ugly, but make sure we really don't leave anything (/proc /proc and
269       # /dev /dev are intended, trying to work around timing issues, see #657023)
270       for ARG in /run/udev /sys /proc /proc /dev/pts /dev/pts /dev /dev ; do
271         [ -x "$MNTPOINT"/bin/umount ] && chroot "$MNTPOINT" umount $ARG >/dev/null 2>&1
272         umount "$MNTPOINT"/$ARG >/dev/null 2>&1
273       done
274
275       if [ -n "$ISODIR" ] ; then
276         [ -d "$MNTPOINT/$ISODIR" ] && umount "$MNTPOINT/$ISODIR" >/dev/null 2>&1
277       fi
278
279       if [ -n "$DIRECTORY" ] ; then
280         einfo "Not unmounting $MNTPOINT as you requested me to install into a directory of your own choice." ; eend 0
281       else
282         einfo "Unmounting $MNTPOINT"
283         umount "$MNTPOINT"
284         eend $?
285       fi
286
287       if [ -n "$STAGES" ] ; then
288         echo -n "Removing stages directory ${STAGES}: "
289         rm -rf "$STAGES" && echo 'done'
290       fi
291
292       # remove directory only if we used the default with process id inside the name
293       if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
294         einfo "Removing directory ${MNTPOINT}"
295         rmdir "$MNTPOINT"
296         eend $?
297       fi
298     fi
299   fi
300
301   if [ -n "${ORIG_TARGET}" ] ; then
302     einfo "Removing loopback mount of file ${ORIG_TARGET}."
303     kpartx -d "${ORIG_TARGET}"
304     # Workaround for a bug in kpartx which doesn't clean up properly,
305     # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
306     if dmsetup ls | grep -q "^${LOOP_PART} "; then
307       kpartx -d "/dev/${LOOP_DISK}" >/dev/null
308     fi
309     eend $?
310   fi
311 }
312
313 # we want to exit smoothly and clean:
314 bailout(){
315
316   cleanup
317
318   [ -n "$1" ] && EXIT="$1" || EXIT="1"
319   [ -n "$2" ] && einfo "Notice: remove $STAGES/$2 to reexecute the stage"
320
321   exit "$EXIT"
322 }
323 trap bailout HUP INT QUIT TERM
324
325 # we want to execute all the functions only once, simple check for it:
326 stage() {
327   if [ -n "$2" ] ; then
328      echo "$2" > "${STAGES}/${1}"
329      return 0
330   elif grep -q 'done' "${STAGES}/${1}" 2>/dev/null ; then
331      ewarn "Notice: stage $1 has been executed already, skipping execution therefore." ; eend 0
332      ewarn "  To reexecute it clean up the according directory inside $STAGES" ; eend 0
333      return 1
334   fi
335 }
336 # }}}
337
338 # make sure we have what we need {{{
339 check4progs "${DEBOOTSTRAP}" || bailout 1
340 # }}}
341
342 # source main configuration file {{{
343 if [ -r /etc/debootstrap/config ] ; then
344   # shellcheck disable=SC1091
345   . /etc/debootstrap/config
346 fi
347 # }}}
348
349 # cmdline handling {{{
350 CMDLINE_OPTS=mirror:,iso:,release:,target:,mntpoint:,debopt:,defaultinterfaces,interactive,nodebootstrap,nointerfaces,nokernel,nopackages,filesystem:,config:,confdir:,packages:,chroot-scripts:,scripts:,post-scripts:,pre-scripts:,debconf:,vm,vmfile,vmsize:,keep_src_list,hostname:,password:,nopassword,grmlrepos,backportrepos,bootappend:,grub:,efi:,arch:,insecure,verbose,help,version,force,debug,contrib,non-free,remove-configs,sshcopyid
351
352 _opt_temp=$(getopt --name grml-debootstrap -o +m:i:r:t:p:c:d:vhV --long \
353   $CMDLINE_OPTS -- "$@")
354
355 if [ $? != 0 ]; then
356   eerror "Try 'grml-debootstrap --help' for more information."; eend 1; exit 1
357 fi
358 eval set -- "$_opt_temp"
359
360 while :; do
361   case "$1" in
362
363   # == Bootstrap options
364   --mirror|-m)         # Mirror which should be used for apt-get/aptitude
365     shift; _opt_mirror="$1"
366     ;;
367   --iso|-i)            # Mountpoint where a Debian ISO is mounted to
368     shift; _opt_iso="$1"
369     ;;
370   --release|-r)        # Release of new Debian system
371     shift; _opt_release="$1"
372     ;;
373   --target|-t)         # Target partition (/dev/...) or directory
374     shift; _opt_target="$1"
375     ;;
376   --vm)                # Virtual machine image (no file)
377     _opt_vm="T"
378     ;;
379   --vmfile)            # Virtual machine file
380     _opt_vmfile="T"
381     ;;
382   --vmsize)            # size of Virtual machine file
383     shift; _opt_vmsize="$1"
384     ;;
385   --mntpoint|-p)       # Mountpoint used for mounting the target system
386     shift; _opt_mntpoint="$1"
387     ;;
388   --debopt)            # Extra parameters passed to the debootstrap command
389     shift; _opt_debopt="$1"
390     ;;
391   --filesystem)        # Filesystem that should be used
392     shift; _opt_filesystem="$1"
393     ;;
394   --interactive)       # Use interactive mode (frontend)
395     _opt_interactive=T
396     ;;
397   --nodebootstrap)     # Skip debootstrap, only do configuration to the target
398     _opt_nodebootstrap=T
399     ;;
400   --nopackages)        # Skip installation of packages defined in /etc/debootstrap/packages
401     _opt_nopackages=T
402     ;;
403   --arch)              # Target architecutre
404     shift; _opt_arch="$1"
405     ;;
406   # just for backwards compatibility
407   --insecure)
408     _opt_insecure=T
409     ;;
410   #
411
412   # == Configuration options
413   --config|-c)         # Use specified configuration file, defaults to /etc/debootstrap
414     shift; _opt_config="$1"
415     ;;
416   --confdir|-d)        # Place of config files for debootstrap, defaults to /etc/debootstrap
417     shift; _opt_confdir="$1"
418     ;;
419   --packages)          # Install packages defined in specified file
420     shift; _opt_packages="$1"
421     _opt_packages_set=T
422     ;;
423   --debconf)           # Pre-seed packages using specified file
424     shift; _opt_debconf="$1"
425     _opt_debconf_set=T
426     ;;
427   --pre-scripts)       # Execute scripts from specified directory (before chroot-scripts).
428     shift; _opt_pre_scripts="$1"
429     _opt_pre_scripts_set=T
430     ;;
431   --scripts)           # Execute scripts from specified directory [NOTE: deprecated, replaced via --post-scripts]
432     shift; _opt_scripts="$1"
433     _opt_scripts_set=T
434     ;;
435   --post-scripts)       # Execute scripts from specified directory
436     shift; _opt_post_scripts="$1"
437     _opt_post_scripts_set=T
438     ;;
439   --chroot-scripts)   # Execute chroot scripts from specified directory
440     shift; _opt_chroot_scripts="$1"
441     _opt_chroot_scripts_set=T
442     ;;
443   --keep_src_list)     # Do not overwrite user provided apt sources.list
444     _opt_keep_src_list=T
445     ;;
446   --hostname)          # Hostname of Debian system
447     shift; _opt_hostname="$1"
448     ;;
449   --password)          # Use specified password as password for user root
450     shift; _opt_password="$1"
451     ;;
452   --defaultinterfaces) # Install default /etc/network/interfaces
453     _opt_defaultinterfaces=T
454     ;;
455   --nointerfaces)      # Skip installation of /etc/network/interfaces
456     _opt_nointerfaces=T
457     ;;
458   --nokernel)          # Skip installation of default kernel images
459     _opt_nokernel=T
460     ;;
461   --nopassword)        # Skip password dialog
462     _opt_nopassword=T
463     ;;
464   --sshcopyid)         # Use locally available public keys to authorise root login on the target system
465     _opt_sshcopyid=T
466     ;;
467   --grmlrepos)         # Enable Grml repository
468     _opt_grmlrepos=T
469     ;;
470   --backportrepos)     # Enable Debian backports repository
471     _opt_backportrepos=T
472     ;;
473   --bootappend)        # Add specified appendline to kernel whilst booting
474     shift; _opt_bootappend="$1"
475     ;;
476   --grub)              # Target for grub installation. Use grub syntax for specifying
477     shift; _opt_grub="$1"
478     ;;
479   --efi)               # Target for EFI boot installation
480     shift; _opt_efi="$1"
481     ;;
482   --contrib)           # Add 'contrib' to list of components
483     _opt_contrib=T
484     ;;
485   --non-free)          # Add 'non-free' to list of components
486     _opt_non_free=T
487     ;;
488   --remove-configs)    # Drop config files from installed system
489     _opt_remove_configs=T
490     ;;
491
492   # == Other options
493   --verbose|-v)        # Increase verbosity
494     if [ "$_opt_verbose" ]; then
495       _opt_verbose=$( _opt_verbose + 1 )
496     else
497       _opt_verbose=1
498     fi
499     ;;
500   --debug)             # Execute in debug mode
501     _opt_debug=T
502     ;;
503   --help|-h)           # Print usage information and exit
504     _opt_help=T
505     ;;
506   --version|-V)        # Show version information and exit
507     _opt_version=T
508     ;;
509   --force)             # Do not prompt for user input
510     _opt_force=T
511     ;;
512   --)
513     shift; break
514     ;;
515   *)
516     eerror "Internal getopt error!"; eend 1 ; exit 1
517     ;;
518   esac
519   shift
520 done
521
522 # == business-logic of command line parameter-processing
523
524 # source configuration file in <confdir> if supplied. {{{
525 [ "$_opt_confdir" ] && {
526   CONFFILES=$_opt_confdir
527   einfo "Using config files under $CONFFILES/."
528   if ! [ -r "$CONFFILES/config" ] ; then
529     eerror "Error: config file $CONFFILES/config not found."; eend 1; bailout 1
530   fi
531   # shellcheck disable=SC1091 source=config
532   if ! . "$CONFFILES/config" ; then
533     eerror "Error reading config file $CONFFILES/config" ; eend 1 ; bailout 1
534   fi
535   # restore the command line parameter value
536   CONFFILES=$_opt_confdir
537 }
538 # }}}
539
540 [ "$_opt_mirror" ]              && MIRROR=$_opt_mirror
541 [ "$_opt_iso" ]                 && ISO=$_opt_iso
542 [ "$_opt_release" ]             && RELEASE=$_opt_release
543 [ "$_opt_target" ]              && TARGET=$_opt_target
544 [ "$_opt_vm" ]                  && VIRTUAL=1
545 [ "$_opt_vmfile" ]              && VMFILE=1 && VIRTUAL=1
546 [ "$_opt_vmsize" ]              && VMSIZE=$_opt_vmsize
547 [ "$_opt_mntpoint" ]            && MNTPOINT=$_opt_mntpoint
548 [ "$_opt_debopt" ]              && DEBOOTSTRAP_OPT=$_opt_debopt
549 [ "$_opt_interactive" ]         && INTERACTIVE=1
550 [ "$_opt_config" ]              && CONFIGFILE=$_opt_config
551 [ "$_opt_filesystem" ]          && MKFS="mkfs.$_opt_filesystem"
552 [ "$_opt_packages_set" ]        && PACKAGES='yes'
553 [ "$_opt_nopackages" ]          && PACKAGES=''
554 [ "$_opt_debconf_set" ]         && DEBCONF='yes'
555 [ "$_opt_post_scripts_set" ]    && POST_SCRIPTS='yes'
556 [ "$_opt_pre_scripts_set" ]     && PRE_SCRIPTS='yes'
557 [ "$_opt_chroot_scripts_set" ]  && CHROOT_SCRIPTS='yes'
558 [ "$_opt_keep_src_list" ]       && KEEP_SRC_LIST='yes'
559 [ "$_opt_grmlrepos" ]           && GRMLREPOS='yes'
560 [ "$_opt_backportrepos" ]       && BACKPORTREPOS='yes'
561 [ "$_opt_hostname" ]            && HOSTNAME=$_opt_hostname
562 [ "$_opt_password" ]            && ROOTPASSWORD=$_opt_password
563 [ "$_opt_nopassword" ]          && NOPASSWORD='yes'
564 [ "$_opt_defaultinterfaces" ]   && USE_DEFAULT_INTERFACES="true"
565 [ "$_opt_nointerfaces" ]        && NOINTERFACES="true"
566 [ "$_opt_nokernel" ]            && NOKERNEL="true"
567 [ "$_opt_sshcopyid" ]           && SSHCOPYID="true"
568 [ "$_opt_bootappend" ]          && BOOT_APPEND=$_opt_bootappend
569 [ "$_opt_grub" ]                && GRUB=$_opt_grub
570 [ "$_opt_efi" ]                 && EFI=$_opt_efi
571 [ "$_opt_arch" ]                && ARCH=$_opt_arch
572 [ "$_opt_insecure" ]            && echo "Warning: --insecure is deprecated, continuing anyway."
573 [ "$_opt_force" ]               && FORCE=$_opt_force
574 [ "$_opt_verbose" ]             && VERBOSE="-v"
575 [ "$_opt_debug" ]               && DEBUG="true"
576 [ "$_opt_remove_configs" ]      && REMOVE_CONFIGS="yes"
577
578 # make sure main is always included
579 [ -z "$COMPONENTS" ]            && COMPONENTS="main"
580 [ "$_opt_contrib" ]             && COMPONENTS="$COMPONENTS contrib"
581 [ "$_opt_non_free" ]            && COMPONENTS="$COMPONENTS non-free"
582
583 # command line option checks
584 if [ "$_opt_scripts_set" ] ; then
585   ewarn "Deprecation NOTE: --scripts option is deprecated, please switch to --post-scripts instead."
586   SCRIPTS='yes' # deprecated since grml-debootstrap >=0.71
587 fi
588
589 if [ "$_opt_grub" ] && [ "$_opt_vmfile" ] ; then
590   eerror "The --grub option is incompatible with --vmfile, please drop it from your command line."
591   eerror "The --grub option is unneeded as GRUB will be installed automatically."
592   eend 1
593   bailout 1
594 fi
595
596 if [ -n "$ISO" ] && [[ "$DEBOOTSTRAP" =~ mmdebstrap$ ]] ; then
597   eerror "The ISO option is incompatible with usage of mmdebstrap for bootstrapping."
598   eerror "Either drop the --iso ... option or use plain debootstrap instead."
599   eend 1
600   bailout 1
601 fi
602
603 if [ "$DEBUG" = "true" ] ; then
604   set -x
605 fi
606
607 [ "$_opt_help" ] && {
608   usage ; eend 0
609   eend 0
610   exit 0
611 }
612
613 [ "$_opt_version" ] && {
614   einfo "$PN - version $VERSION"
615   einfo "Report bugs via https://github.com/grml/grml-debootstrap/ or https://grml.org/bugs/"
616   eend 0
617   exit 0
618 }
619 # }}}
620
621 # check for root permissions {{{
622 if ! check4root ; then
623    echo "For usage instructions please execute '$PN --help'."
624    bailout 1
625 fi
626 # }}}
627
628 # make sure we have what we need {{{
629 if [ -n "$VIRTUAL" ] ; then
630   check4progs kpartx parted qemu-img || bailout 1
631 fi
632 # }}}
633
634 # source specified configuration file {{{
635 if [ -n "$CONFIGFILE" ] ; then
636   einfo "Reading specified config file $CONFIGFILE."
637   # shellcheck disable=SC1091 source=config
638   if ! . "$CONFIGFILE" ; then
639     eerror "Error reading config file $CONFIGFILE" ; eend 1 ; bailout 1
640   fi
641 fi
642 # }}}
643
644 # backwards compatibility checks {{{
645 if [ -n "$GROOT" ] ; then
646    eerror "Error: you seem to have \$GROOT configured."
647    eerror "This variable is no longer supported, please visit the"
648    eerror "grml-debootstrap documentation for details."
649    eend 1
650    bailout 1
651 fi
652
653 if echo "$GRUB" | grep -q '^hd' ; then
654    eerror "Error: this syntax for the grub configuration variable is no longer supported."
655    eerror "Please do not use hd... any longer but /dev/sdX instead."
656    eend 1
657    bailout 1
658 fi
659 # }}}
660
661 # welcome screen {{{
662 welcome_dialog()
663 {
664    dialog --title "$PN" --yesno "Welcome to the interactive configuration of ${PN}.
665 Do you want to continue installing Debian using this frontend?" 0 0 || bailout 0
666 }
667 # }}}
668
669 # ask for target {{{
670 prompt_for_target()
671 {
672   AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
673                sed 's/*//' | \
674                grep -v 'Extended$' | \
675                gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}'; ls /dev/md[0-9]* 2>/dev/null || true);
676
677   if [ -z "$AVAILABLE_PARTITIONS" ] ; then
678      dialog --title "$PN" --trim \
679      --msgbox "Sorry, no partitions found. Please configure your
680      harddisks (see /proc/partitions) using a tool like fdisk,
681      cfdisk, gpart, gparted,..." 0 0
682      bailout 1
683   fi
684
685   PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
686                      fs="$(blkid -s TYPE -o value "$i" 2>/dev/null)"
687                      [ -n "$fs" ] || fs='[no_filesystem_yet]'
688                      echo "$i" "$fs"
689                      unset fs
690                    done)
691
692   # shellcheck disable=SC2086
693   TARGET=$(dialog --title "$PN" --single-quoted --stdout \
694          --menu "Please select the target partition:" 0 0 0 \
695          $PARTITION_LIST)
696   [ $? -eq 0 ] || bailout 1
697 }
698 # }}}
699
700 # ask for bootmanager {{{
701 prompt_for_bootmanager()
702 {
703   ADDITIONAL_PARAMS=""
704
705   if echo "$TARGET" | grep -q "/dev/md" ; then
706      MBRPART="all disks of Software RAID $TARGET"
707   else
708      # figure out whole disk device
709      found=
710      for device in /dev/disk/by-id/*
711      do
712         [ "$(readlink -f "$device")" = "${TARGET}" ] || continue
713         found=1
714         break
715      done
716      # shellcheck disable=SC2001
717      [ -n "$found" ] && MBRDISK=$(echo "${device}" | sed -e 's/-part[0-9][0-9]*$//')
718      if [ -e "$MBRDISK" ]; then
719         MBRDISK=$(readlink -f "$MBRDISK")
720      else
721         # fall back to old behaviour
722         # shellcheck disable=SC2001
723         MBRDISK=$(echo "${TARGET}" | sed -e 's/[0-9][0-9]*$//')
724      fi
725
726      MBRPART="MBR of $MBRDISK"
727   fi
728
729   for device in cciss/c0d0 sda hda; do
730     if [ "/dev/$device" != "${MBRDISK}" ]; then
731       grep -q $device /proc/partitions && \
732       ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS:$device:install bootmanager grub into MBR of /dev/$device"
733     fi
734   done
735   ADDITIONAL_PARAMS=${ADDITIONAL_PARAMS#:}
736
737   OIFS="$IFS"; IFS=:
738
739   # shellcheck disable=SC2086
740   GETMBR=$(dialog --stdout --title "$PN" --default-item mbr \
741           --menu "Where do you want to install the bootmanager grub?" 0 0 0 \
742             mbr       "install bootmanager into $MBRPART" \
743             nowhere   "do not install bootmanager at all" \
744           ${ADDITIONAL_PARAMS})
745   [ $? -eq 0 ] || bailout 3
746   IFS="$OIFS"
747
748   case "$GETMBR" in
749     mbr)
750       # /dev/md0: has to be installed in MBR of /dev/md0 and not in /dev/md:
751       if echo "$TARGET" | grep -q "/dev/md" ; then
752         GRUB="$TARGET"
753       else
754         GRUB="$MBRDISK"
755       fi
756       ;;
757     hda)
758       GRUB="/dev/hda"
759       ;;
760     sda)
761       GRUB="/dev/sda"
762       ;;
763     nowhere)
764       GRUB=''
765       ;;
766   esac
767 }
768 # }}}
769
770 # ask for Debian release {{{
771 prompt_for_release()
772 {
773   [ -n "$RELEASE" ] && DEFAULT_RELEASE="$RELEASE" || DEFAULT_RELEASE='buster'
774   RELEASE="$(dialog --stdout --title "${PN}" --default-item $DEFAULT_RELEASE --menu \
775             "Please enter the Debian release you would like to use for installation:" \
776             0 50 8 \
777             lenny    Debian/5.0 \
778             squeeze  Debian/6.0 \
779             wheezy   Debian/7.0 \
780             jessie   Debian/8.0 \
781             stretch  Debian/9.0 \
782             buster   Debian/10.0 \
783             bullseye Debian/11.0 \
784             sid      Debian/unstable)"
785   [ $? -eq 0 ] || bailout
786 }
787 # }}}
788
789 # ask for hostname {{{
790 prompt_for_hostname()
791 {
792   HOSTNAME="$(dialog --stdout --title "${PN}" --inputbox \
793             "Please enter the hostname you would like to use for installation:" \
794             0 0 "$HOSTNAME")"
795   [ $? -eq 0 ] || bailout
796 }
797 # }}}
798
799 # ask for password {{{
800 prompt_for_password()
801 {
802   if [ "$_opt_nopassword" ] ; then
803     einfo "Skip asking for root password as requested."
804     return 0
805   fi
806
807   ROOTPW1='PW1'
808   ROOTPW2='PW2'
809   while [ "$ROOTPW1" != "$ROOTPW2" ]; do
810     ROOTPW1=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
811     "Please enter the password for the root account:" 10 60)
812     [ $? -eq 0 ] || bailout
813
814     ROOTPW2=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
815     "Please enter the password for the root account again for \
816     confirmation:" 10 60)
817     [ $? -eq 0 ] || bailout
818
819     if [ "$ROOTPW1" != "$ROOTPW2" ]; then
820       dialog --stdout --title "${PN}" --ok-label \
821         "Retry" --msgbox "Passwords do not match!" 10 60
822     fi
823   done
824   ROOTPASSWORD="$ROOTPW1"
825 }
826 # }}}
827
828 # ask for Debian mirror {{{
829 prompt_for_mirror()
830 {
831   [ -n "$ISO" ] && DEFAULT_MIRROR='local' || DEFAULT_MIRROR='net'
832
833   CHOOSE_MIRROR=$(dialog --stdout --title "$PN" --default-item $DEFAULT_MIRROR \
834           --menu "Where do you want to install from?" 0 0 0 \
835             net   "install via network (downloading from mirror)" \
836             local "install from local directory/mirror"
837           )
838   [ $? -eq 0 ] || bailout
839
840   if [ "$CHOOSE_MIRROR" = 'net' ] ; then
841      [ -n "$MIRROR" ] || MIRROR='http://deb.debian.org/debian'
842      MIRROR="$(dialog --stdout --title "${PN}" --inputbox \
843                "Please enter Debian mirror you would like to use for installing packages." \
844                0 0 $MIRROR)"
845      [ $? -eq 0 ] || bailout
846   else # CHOOSE_MIRROR == local
847      [ -n "$ISO" ] || ISO='/mnt/mirror'
848      ISO="$(dialog --stdout --title "${PN}" --inputbox \
849                "Please enter directory name you would like to use for installing packages." \
850                0 0 $ISO)"
851      [ $? -eq 0 ] || bailout
852   fi
853 }
854 # }}}
855
856 # software raid setup {{{
857 config_swraid_setup()
858 {
859 TMPFILE=$(mktemp)
860
861 # Currently we support only raid1:
862 RAIDLEVEL='raid1'
863
864 MD_LIST=$(for i in $(seq 0 9) ; do
865             awk '{print $4}' /proc/partitions | grep -q "md$i" || \
866             echo "/dev/md$i /dev/md$i"
867           done)
868
869 # shellcheck disable=SC2086
870 TARGET=$(dialog --stdout --title "$PN" --default-item /dev/md0 \
871 --menu "Which device do you want to use for ${RAIDLEVEL}?
872
873 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 \
874 $MD_LIST)
875 [ $? -eq 0 ] || bailout 20
876
877 AVAILABLE_PARTITIONS=$(LANG=C fdisk -l 2>/dev/null | \
878              sed 's/*//' | \
879              grep -v 'Extended$' | \
880              gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}')
881 [ -n "$AVAILABLE_PARTITIONS" ] || echo "Fatal error: no partitions available?"
882 PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
883                      echo "$i $(blkid -s TYPE -o value "$i" 2>/dev/null || echo '[no_filesystem_yet]') off"
884                  done)
885
886 # shellcheck disable=SC2086
887 dialog --title "$PN" --separate-output \
888        --checklist "Please select the partitions you would like to use for your $RAIDLEVEL on ${TARGET}:" 0 0 0 \
889        $PARTITION_LIST 2>"$TMPFILE"
890 [ $? -eq 0 ] || bailout
891 SELECTED_PARTITIONS="$(cat "$TMPFILE")"
892
893 NUM_PARTITIONS=0
894 while IFS= read -r i; do
895   NUM_PARTITIONS=$(( NUM_PARTITIONS + 1 ))
896 done < "$TMPFILE"
897
898 # force metadata version 0.90 for lenny so old grub can boot from this array.
899 METADATA_VERSION=""
900 if [ "$RELEASE" = "lenny" ]; then
901    METADATA_VERSION="-e0"
902 fi
903
904 ERRORFILE=$(mktemp)
905 # shellcheck disable=SC2086
906 yes | mdadm --create "${TARGET}" --level="${RAIDLEVEL}" \
907       --raid-devices="${NUM_PARTITIONS}" ${METADATA_VERSION} ${SELECTED_PARTITIONS} >/dev/null 2>$ERRORFILE
908 RC=$?
909 if [ "$RC" = 0 ] ; then
910    dialog --title "$PN" --msgbox \
911    "Creating $TARGET was successful." 0 0
912    rm -f "$TMPFILE" "$ERRORFILE"
913 else
914    dialog --title "$PN" --msgbox \
915    "There was an error setting up $TARGET:
916
917 $(cat "$ERRORFILE")
918
919 Exiting." 0 0
920    rm -f "$TMPFILE" "$ERRORFILE"
921    bailout 1
922 fi
923
924 }
925
926 prompt_for_swraid()
927 {
928 if dialog --stdout --title "$PN" \
929           --defaultno --yesno "Do you want to configure Software RAID?
930
931 Please notice that only RAID level 1 is supported by ${PN} currently. Configuration will take place using mdadm." 0 0 ; then
932   config_swraid_setup
933 fi
934 }
935 # }}}
936
937 # user should recheck his configuration {{{
938 # support full automatic installation:
939 checkforrun() {
940    dialog --timeout 10 --title "$PN" \
941           --yesno "Do you want to stop at this stage?
942
943 Notice: you are running ${PN} in non-interactive mode.
944 ${PN} will install Debian ${RELEASE} on ${TARGET}.
945 Last chance to quit. Timeout of 10 seconds running....
946
947 Do you want to stop now?" 0 0 2>/dev/null
948 }
949 # }}}
950
951 # format efi partition {{{
952 format_efi_partition() {
953   if [ -z "$EFI" ] ; then
954     return 0
955   fi
956
957   if ! [ -b "$EFI" ] ; then
958     eerror "Specified efi argument [$EFI] not a valid block device."
959     bailout 1
960   fi
961
962   if fsck.vfat -bn "$EFI" >/dev/null; then
963     einfo "EFI partition $EFI seems to have a FAT filesystem, not modifying." ; eend 0
964   else
965     einfo "EFI partition $EFI doesn't seem to be formatted, creating filesystem."
966     mkfs.fat -F32 -n "EFI System Partition" "$EFI"
967     RC=$?
968     if [ $RC -eq 0 ] ; then
969       eend 0
970     else
971       eerror "Error while creating filesystem on ${EFI}."
972       eend 1
973       bailout 1
974     fi
975   fi
976 }
977 # }}}
978
979 # check for EFI support or try to enable it {{{
980 efi_support() {
981   if lsmod | grep -q efivars ; then
982     einfo "EFI support detected." ; eend 0
983     return 0
984   fi
985
986   if modprobe efivars &>/dev/null ; then
987     einfo "EFI support enabled now." ; eend 0
988     return 0
989   fi
990
991   return 1
992 }
993 # }}}
994
995 # make sure the user is aware of the used configuration {{{
996 checkconfiguration()
997 {
998
999 if efi_support ; then
1000   if [ -z "$_opt_efi" ] ; then
1001     ewarn "EFI support detected but no --efi option given, please consider enabling it." ; eend 0
1002   fi
1003 else
1004   if [ -n "$_opt_efi" ] ; then
1005      eerror "EFI option used but no EFI support detected." ; eend 0
1006      bailout 1
1007   fi
1008 fi
1009
1010 if [ -n "$AUTOINSTALL" ] ; then
1011    if checkforrun ; then
1012       eerror "Exiting as requested" ; eend 0
1013       bailout 1
1014    fi
1015 elif [ -n "$INTERACTIVE" ] ; then
1016
1017    INFOTEXT="Please recheck configuration before execution:
1018    "
1019    [ -n "$TARGET" ]  && INFOTEXT="$INFOTEXT
1020    Target:          $TARGET"
1021    [ -n "$GRUB" ]    && INFOTEXT="$INFOTEXT
1022    Install grub:    $GRUB"
1023    [ -n "$EFI" ]    && INFOTEXT="$INFOTEXT
1024    Install efi:     $EFI"
1025    [ -n "$RELEASE" ] && INFOTEXT="$INFOTEXT
1026    Using release:   $RELEASE"
1027    [ -n "$HOSTNAME" ] && INFOTEXT="$INFOTEXT
1028    Using hostname:  $HOSTNAME"
1029    [ -n "$MIRROR" ]  && INFOTEXT="$INFOTEXT
1030    Using mirror:    $MIRROR"
1031    [ -n "$ISO" ]  && INFOTEXT="$INFOTEXT
1032    Using ISO:       $ISO"
1033    [ -n "$ARCH" ]  && INFOTEXT="$INFOTEXT
1034    Using arch:      $ARCH"
1035    [ -n "$CONFFILES" ] && INFOTEXT="$INFOTEXT
1036    Config files:    $CONFFILES"
1037
1038    INFOTEXT="$INFOTEXT
1039
1040 Is this ok for you? Notice: selecting 'No' will exit ${PN}."
1041
1042    dialog --title "$PN" --no-collapse \
1043           --yesno "$INFOTEXT" 0 0
1044    [ $? -eq 0 ] || bailout 0
1045
1046 else # if not running automatic installation display configuration and prompt for execution:
1047    einfo "$PN [${VERSION}] - Please recheck configuration before execution:"
1048    echo
1049    echo "   Target:          $TARGET"
1050
1051    # do not display if MNTPOINT is the default one
1052    case "$MNTPOINT" in /mnt/debootstrap*) ;; *) echo "   Mount point:     $MNTPOINT" ;; esac
1053
1054    if [ -n "$VIRTUAL" ] ; then
1055       echo "   Install grub:    yes"
1056    else
1057      [ -n "$GRUB" ]     && echo "   Install grub:    $GRUB" || echo "   Install grub:    no"
1058      [ -n "$EFI" ]      && echo "   Install efi:     $EFI"  || echo "   Install efi:     no"
1059    fi
1060
1061    [ -n "$RELEASE" ]   && echo "   Using release:   $RELEASE"
1062    [ -n "$HOSTNAME" ]  && echo "   Using hostname:  $HOSTNAME"
1063    [ -n "$MIRROR" ]    && echo "   Using mirror:    $MIRROR"
1064    [ -n "$ISO" ]       && echo "   Using ISO:       $ISO"
1065    [ -n "$ARCH" ]      && echo "   Using arch:      $ARCH"
1066    [ -n "$CONFFILES" ] && echo "   Config files:    $CONFFILES"
1067    if [ -n "$VIRTUAL" ] ; then
1068       echo "   Deploying as Virtual Machine."
1069       if [ -n "$VMSIZE" ] && [ -n "$VMFILE" ]; then
1070          echo "   Using Virtual Disk file with size of ${VMSIZE}."
1071       fi
1072    fi
1073
1074    if [ ! -t 0 ] && [ -z "$ROOTPASSWORD" ] && [ -z "$NOPASSWORD" ] ; then
1075       echo
1076       echo "   You do not have a TTY allocated, your password will be shown in"
1077       echo "   plaintext on the terminal! If you are using SSH, try its -t option!"
1078    fi
1079
1080    echo
1081    echo "   Important! Continuing will delete all data from ${TARGET}!"
1082
1083    if [ -n "$FORCE" ] ; then
1084      einfo "Skip user acknowledgement as requested via --force option."
1085    else
1086      echo
1087      einfon "Is this ok for you? [y/N] "
1088      read -r a
1089      if ! [ "$a" = 'y' ] || [ "$a" = 'Y' ] ; then
1090         eerror "Exiting as requested." ; eend 1
1091         bailout 1
1092      fi
1093    fi
1094 fi
1095 }
1096 # }}}
1097
1098 # interactive mode {{{
1099 interactive_mode()
1100 {
1101   check4progs dialog || bailout 1
1102
1103   welcome_dialog
1104
1105   prompt_for_release
1106
1107   prompt_for_swraid
1108
1109   prompt_for_target
1110
1111   prompt_for_bootmanager
1112
1113   prompt_for_hostname
1114
1115   prompt_for_password
1116
1117   prompt_for_mirror
1118 }
1119
1120 # run interactive mode if we didn't get the according configuration yet
1121 if [ -z "$TARGET" ] || [ -n "$INTERACTIVE" ] ; then
1122    # only target might be unset, so make sure the INTERACTIVE flag is set as well
1123    INTERACTIVE=1
1124    interactive_mode
1125 fi
1126 # }}}
1127
1128 # architecture setup {{{
1129 if [ -n "$ARCH" ] ; then
1130    ARCHCMD="--arch $ARCH"
1131    ARCHINFO=" (${ARCH})"
1132 else
1133    ARCH="$(dpkg --print-architecture)"
1134    ARCHCMD="--arch $ARCH"
1135    ARCHINFO=" (${ARCH})"
1136 fi
1137 # }}}
1138
1139 # It is not possible to build amd64 on i686. {{{
1140 CURRENT_ARCH="$(uname -m)"
1141 if [ "$CURRENT_ARCH" != "x86_64" ] ; then
1142    if [ "$ARCH" = "amd64" ] ; then
1143       eerror "It is not possible to build amd64 on $CURRENT_ARCH. Consider installing and booting the 'linux-image-amd64' kernel or using '--arch i386' instead." ; eend 1
1144       bailout 1
1145    fi
1146 fi
1147 # }}}
1148
1149 # Support for generic release codenames is unavailable. {{{
1150 if [ "$RELEASE" = "stable" ] || [ "$RELEASE" = "testing" ] ; then
1151    eerror "Generic release codenames (stable, testing) are unsupported. \
1152 Please use specific codenames such as stretch or buster." ; eend 1
1153    bailout 1
1154 fi
1155 # }}}
1156
1157 checkconfiguration
1158
1159 # finally make sure at least $TARGET is set [the partition for the new system] {{{
1160 if [ -n "$TARGET" ] ; then
1161    SHORT_TARGET="${TARGET##*/}"
1162 else
1163    eerror "Please adjust $CONFFILES/config or..."
1164    eerror "... use the interactive version for configuration before running ${0}" ; eend 1
1165    bailout 1
1166 fi
1167 # }}}
1168
1169 # stages setup {{{
1170 if [ -z "$STAGES" ] ; then
1171    STAGES="/var/cache/grml-debootstrap/stages_${SHORT_TARGET}"
1172    [ -d "$STAGES" ] || mkdir -p "$STAGES"
1173 fi
1174
1175 if [ -r "$STAGES"/grml-debootstrap ] ; then
1176    if grep -q 'done' "${STAGES}/grml-debootstrap" ; then
1177       eerror "Error: grml-debootstrap has been executed already, won't continue therefore."
1178       eerror "If you want to re-execute grml-debootstrap just manually remove ${STAGES}" ; eend 1
1179    fi
1180 fi
1181 # }}}
1182
1183 # partition handling {{{
1184 PARTITION=''
1185 DIRECTORY=''
1186
1187 set_target_directory(){
1188     # assume we are installing into a directory, don't run mkfs and grub related stuff therefore
1189     DIRECTORY=1
1190     MNTPOINT="$TARGET"
1191     MKFS=''
1192     TUNE2FS=''
1193     FSCK=''
1194     # make sure we normalise the path to an absolute directory name so something like:
1195     #  mkdir -p foo/a bar/a; (cd foo; grml-debootstrap -t a)&; (cd bar; grml-debootstrap -t a)&; wait
1196     # works
1197     TARGET="$(readlink -f "$TARGET")"
1198 }
1199
1200 if [ -b "$TARGET" ] || [ -n "$VIRTUAL" ] ; then
1201     PARTITION=1
1202 else
1203     # $TARGET was not detected as block device, but we do not want to create target directory in /dev/
1204     if [[ $TARGET == "/dev/"* ]]; then
1205       eerror "Error: Will not create target directory $TARGET in /dev."
1206       eerror "  Please check the partition(s) of the blockdevice."; eend 1
1207       bailout 1
1208     fi
1209     set_target_directory
1210 fi
1211 # }}}
1212
1213 # make sure we have the right syntax when using an iso image {{{
1214 if [ -n "$ISO" ] ; then
1215    case $ISO in
1216       file*) # do nothing
1217       ;;
1218       *)
1219       ISO=file:$ISO
1220       ;;
1221    esac
1222 fi
1223 ISODIR=${ISO##file:}
1224 ISODIR=${ISODIR%%/}
1225 # }}}
1226
1227 # Debian ISOs do not contain signed Release files {{{
1228 if [ -n "$ISO" ] ; then
1229     DEBOOTSTRAP_OPT="$DEBOOTSTRAP_OPT --no-check-gpg"
1230 fi
1231 # }}}
1232
1233 # create filesystem {{{
1234 mkfs() {
1235   if [ -n "$DIRECTORY" ] ; then
1236      einfo "Running grml-debootstrap on a directory, skipping mkfs stage."
1237      return 0
1238   fi
1239
1240   if grep -q "$TARGET" /proc/mounts ; then
1241     eerror "$TARGET already mounted, exiting to avoid possible damage. (Manually unmount $TARGET)" ; eend 1
1242     bailout 1
1243   fi
1244
1245   # mkfs.ext* might prompt with "/dev/sdX# contains a ext* file system
1246   # created on ... Proceed anyway? (y,n)" which we want to skip in force mode
1247   if [ -n "$MKFS" ] && [ -n "$FORCE" ] ; then
1248     case "$MKFS" in
1249       mkfs.ext*)
1250         einfo "Enabling force option (-F) for mkfs.ext* tool as requested via --force switch."
1251         MKFS_OPTS="$MKFS_OPTS -F"
1252         eend 0
1253
1254         ;;
1255     esac
1256   fi
1257
1258   # starting with e2fsprogs 1.43~WIP.2015.05.18-1 mkfs.ext4 enables the metadata_csum feature
1259   # by default, which requires a recent version of tune2fs on the target system then,
1260   # so disable this feature for older Debian releases where it's known to be unsupported
1261   if [ -n "$MKFS" ] && [ "$MKFS" = "mkfs.ext4" ] ; then
1262     case "$RELEASE" in
1263       lenny|squeeze|wheezy|jessie)
1264         # assume a more recent version if we can't identify the version via dpkg-query
1265         local e2fsprogs_version
1266         e2fsprogs_version="$(dpkg-query --show --showformat='${Version}' e2fsprogs 2>/dev/null || echo 1.44)"
1267         if [ -n "$e2fsprogs_version" ] && dpkg --compare-versions "$e2fsprogs_version" ge '1.43~WIP.2015.05.18-1' ; then
1268           einfo "Disabling metadata_csum feature for $MKFS as $RELEASE doesn't support it."
1269           MKFS_OPTS="$MKFS_OPTS -O ^metadata_csum"
1270           eend 0
1271         fi
1272         ;;
1273     esac
1274   fi
1275
1276   if [ -n "$MKFS" ] ; then
1277     einfo "Running $MKFS $MKFS_OPTS on $TARGET"
1278     # shellcheck disable=SC2086
1279     "$MKFS" $MKFS_OPTS "$TARGET" ; RC=$?
1280
1281     if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1282       if ! echo "$MKFS" | grep -q "mkfs.ext" ; then
1283         eerror "Not changing disk uuid for $TARGET because $MKFS doesn't seem to match for ext{2,3,4} file system"
1284         eend 1
1285         bailout 1
1286       else
1287         einfo "Changing disk uuid for $TARGET to fixed (non-random) value $DISK_IDENTIFIER using tune2fs"
1288         tune2fs "$TARGET" -U "$DISK_IDENTIFIER"
1289         eend $?
1290       fi
1291     fi
1292
1293     # make sure /dev/disk/by-uuid/... is up2date, otherwise grub
1294     # will fail to detect the uuid in the chroot
1295     if [ -n "$VIRTUAL" ] ; then
1296       einfo "Virtual environment doesn't require blockdev --rereadpt, skipping therefore"
1297     elif echo "$TARGET" | grep -q "/dev/md" ; then
1298       blockdev --rereadpt "${TARGET}"
1299     else
1300       # if we deploy to /dev/sdX# then let's see if /dev/sdX exists
1301       local main_device="${TARGET%%[0-9]*}"
1302       # sanity check to not try to e.g. access /dev/loop if we get /dev/loop0
1303       if [ -f "/sys/block/$(basename "${main_device}")/$(basename "${TARGET}")/dev" ] ; then
1304         blockdev --rereadpt "$main_device"
1305       else
1306         einfo "No underlying block device for $TARGET identified, skipping blockdev --rereadpt."
1307       fi
1308     fi
1309     # give the system 2 seconds, otherwise we might run into
1310     # race conditions :-/
1311     sleep 2
1312
1313     eend $RC
1314   fi
1315 }
1316 # }}}
1317
1318 # retrieve ID_FS_UUID {{{
1319 identify_target_uuid() {
1320   local device="$1"
1321
1322   if ! [ -b "$device" ] ; then
1323     return 1
1324   fi
1325
1326   eval "$(blkid -o udev "$1" 2>/dev/null)"
1327
1328   if [ -n "$ID_FS_UUID" ] ; then
1329     echo "$ID_FS_UUID"
1330   else
1331     return 1
1332   fi
1333 }
1334 # }}}
1335
1336 # identify TARGET_UUID {{{
1337 mountpoint_to_blockdevice() {
1338   TARGET_UUID=''
1339
1340   TARGET_UUID=$(identify_target_uuid "$TARGET" 2>/dev/null || true)
1341   if [ -n "$TARGET_UUID" ] ; then
1342     einfo "Identified UUID $TARGET_UUID for $TARGET"
1343     return 0
1344   fi
1345
1346   # $TARGET might be a mountpoint and not a blockdevice, search for according entry
1347   for file in /sys/block/*/*/dev ; do
1348     if grep -q "^$(mountpoint -d "${TARGET}")$" "$file" ; then
1349       local dev
1350       dev="${file%/dev}"
1351       dev="/dev/${dev##*/}"
1352       TARGET_UUID=$(identify_target_uuid "$dev" 2>/dev/null || true)
1353
1354       if [ -n "$TARGET_UUID" ] ; then
1355         einfo "Identified UUID $TARGET_UUID for $TARGET (via $file)"
1356         return 0
1357       fi
1358     fi
1359   done
1360 }
1361 # }}}
1362
1363 # modify filesystem settings {{{
1364 tunefs() {
1365   if [ -n "$TUNE2FS" ] && echo "$MKFS" | grep -q "mkfs.ext" ; then
1366      einfo "Disabling automatic filesystem check on $TARGET via tune2fs"
1367      $TUNE2FS "$TARGET"
1368      eend $?
1369   fi
1370 }
1371 # }}}
1372
1373 # mount the new partition or if it's a directory do nothing at all {{{
1374 mount_target() {
1375   if [ -n "$DIRECTORY" ] ; then
1376      einfo "Running grml-debootstrap on a directory, nothing to mount."
1377   else
1378      if grep -q "$TARGET" /proc/mounts ; then
1379         ewarn "$TARGET already mounted, continuing anyway." ; eend 0
1380      else
1381        if ! [ -d "${MNTPOINT}" ] ; then
1382           [ -n "$VIRTUAL" ] || mkdir -p "${MNTPOINT}"
1383        fi
1384        einfo "Mounting $TARGET to $MNTPOINT"
1385        mkdir -p "$MNTPOINT"
1386        mount -o rw,suid,dev "$TARGET" "$MNTPOINT"
1387        eend $?
1388      fi
1389   fi
1390   if [ -n "$ISODIR" ] ; then
1391      einfo "Mounting Debian image loopback to $MNTPOINT/$ISODIR."
1392      mkdir -p "$MNTPOINT/$ISODIR"
1393      mount --bind "$ISODIR" "$MNTPOINT/$ISODIR"
1394      eend $?
1395   fi
1396 }
1397 # }}}
1398
1399 # prepare VM image for usage with debootstrap {{{
1400 prepare_vm() {
1401   if [ -z "$VIRTUAL" ] ; then
1402      return 0 # be quiet by intention
1403   fi
1404
1405   if [ -b "$TARGET" ] && [ -n "$VMFILE" ] ; then
1406      eerror "Error: specified virtual disk target ($TARGET) is an existing block device."
1407      eend 1
1408      bailout 1
1409   fi
1410   if [ ! -b "$TARGET" ] && [ -z "$VMFILE" ] ; then
1411      eerror "Error: specified virtual disk target ($TARGET) does not exist yet."
1412      eend 1
1413      bailout 1
1414   fi
1415
1416   # make sure loop module is present and a usable loop device exists
1417   modprobe -q loop
1418   if ! losetup -f >/dev/null 2>&1; then
1419     eerror "Error finding usable loop device" ; eend 1
1420     bailout 1
1421   fi
1422
1423   # if dm-mod isn't available then kpartx will fail with
1424   # "Is device-mapper driver missing from kernel? [...]"
1425   modprobe -q dm-mod
1426   if ! grep -q 'device-mapper' /proc/misc >/dev/null 2>&1 ; then
1427     eerror "Device-mapper support missing in kernel." ; eend 1
1428     bailout 1
1429   fi
1430
1431   ORIG_TARGET="$TARGET" # store for later reuse
1432
1433   if [ -n "$VMFILE" ]; then
1434     qemu-img create -f raw "${TARGET}" "${VMSIZE}"
1435   fi
1436   parted -s "${TARGET}" 'mklabel msdos'
1437   if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
1438     einfo "Adjusting disk signature to a fixed (non-random) value"
1439     MBRTMPFILE=$(mktemp)
1440     dd if="${TARGET}" of="${MBRTMPFILE}" bs=512 count=1
1441     echo -en "\\x41\\x41\\x41\\x41" | dd of="${MBRTMPFILE}" conv=notrunc seek=440 bs=1
1442     dd if="${MBRTMPFILE}" of="${TARGET}" conv=notrunc
1443     eend $?
1444   fi
1445   parted -s "${TARGET}" 'mkpart primary ext4 2M -1'
1446   parted -s "${TARGET}" 'set 1 boot on'
1447
1448   DEVINFO=$(kpartx -asv "$TARGET") # e.g. 'add map loop0p1 (254:5): 0 20477 linear 7:0 3'
1449   if [ -z "${DEVINFO}" ] ; then
1450     eerror "Error setting up loopback device." ; eend 1
1451     bailout 1
1452   fi
1453
1454   # hopefully this always works as expected
1455   LOOP_PART="${DEVINFO##add map }" # 'loop0p1 (254:5): 0 20477 linear 7:0 3'
1456   LOOP_PART="${LOOP_PART// */}"    # 'loop0p1'
1457   LOOP_DISK="${LOOP_PART%p*}"      # 'loop0'
1458   export TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop1p1'
1459
1460   if [ -z "$TARGET" ] ; then
1461      eerror "Error: target could not be set to according /dev/mapper/* device." ; eend 1
1462      bailout 1
1463   fi
1464 }
1465 # }}}
1466
1467 # make VM image bootable {{{
1468 grub_install() {
1469   if [ -z "${VIRTUAL}" ] ; then
1470      return 0
1471   fi
1472   if [ "${GRUB_INSTALL}" != "yes" ] ; then
1473     einfo "Not installing GRUB as requested via \$GRUB_INSTALL=$GRUB_INSTALL"
1474     return 0
1475   fi
1476
1477   if ! mount "${TARGET}" "${MNTPOINT}" ; then
1478     eerror "Error: Mounting ${TARGET} failed, can not continue." ; eend 1
1479     bailout 1
1480   fi
1481
1482   mount -t proc none "${MNTPOINT}"/proc
1483   mount -t sysfs none "${MNTPOINT}"/sys
1484   mount -t devtmpfs udev "${MNTPOINT}"/dev
1485   mount -t devpts devpts "${MNTPOINT}"/dev/pts
1486
1487 # Has chroot-script installed GRUB to MBR using grub-install (successfully), already?
1488 # chroot-script skips installation for unset ${GRUB}
1489 if [[ -z "${GRUB}" ]] || ! dd if="${GRUB}" bs=512 count=1 2>/dev/null | cat -v | grep -Fq GRUB; then
1490   einfo "Installing Grub as bootloader."
1491
1492   if ! chroot "${MNTPOINT}" dpkg --list grub-pc 2>/dev/null | grep -q '^ii' ; then
1493     echo "Notice: grub-pc package not present yet, installing it therefore."
1494     # shellcheck disable=SC2086
1495     DEBIAN_FRONTEND=$DEBIAN_FRONTEND chroot "$MNTPOINT" apt-get -y install $DPKG_OPTIONS grub-pc
1496   fi
1497
1498   mkdir -p "${MNTPOINT}/boot/grub"
1499   if ! [ -d "${MNTPOINT}"/usr/lib/grub/i386-pc/ ] ; then
1500      eerror "Error: grub not installed inside Virtual Machine. Can not install bootloader." ; eend 1
1501      bailout 1
1502   fi
1503
1504   case "$RELEASE" in
1505     lenny|squeeze|wheezy)
1506       cp "${MNTPOINT}"/usr/lib/grub/i386-pc/* "${MNTPOINT}/boot/grub/"
1507       ;;
1508     *)
1509       cp -a "${MNTPOINT}"/usr/lib/grub/i386-pc "${MNTPOINT}/boot/grub/"
1510       ;;
1511   esac
1512   dd if="${MNTPOINT}/usr/lib/grub/i386-pc/boot.img" of="${ORIG_TARGET}" conv=notrunc bs=440 count=1
1513   chroot "${MNTPOINT}" grub-mkimage -O i386-pc -p "(hd0,msdos1)/boot/grub" -o /tmp/core.img biosdisk part_msdos ext2
1514   dd if="${MNTPOINT}/tmp/core.img" of="${ORIG_TARGET}" conv=notrunc seek=1
1515   rm -f "${MNTPOINT}/tmp/core.img"
1516 fi
1517
1518   einfo "Updating grub configuration file."
1519   if [ -n "$BOOT_APPEND" ] ; then
1520      sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" "${MNTPOINT}"/etc/default/grub
1521   fi
1522   chroot "${MNTPOINT}" update-grub
1523
1524   case "$RELEASE" in
1525     jessie)
1526       einfo "Applying workaround for GRUB font path bug in jessie (Debian #787685)."
1527       mkdir -p "${MNTPOINT}/boot/grub/fonts/"
1528       cp "${MNTPOINT}/usr/share/grub/unicode.pf2" "${MNTPOINT}/boot/grub/fonts/"
1529       ;;
1530   esac
1531
1532   if grep -q '^GRUB_DISABLE_LINUX_UUID=.*true' "${MNTPOINT}"/etc/default/grub 2>/dev/null ; then
1533     ewarn "GRUB_DISABLE_LINUX_UUID is set to true in /etc/default/grub, not adjusting root= in grub.cfg."
1534     ewarn "Please note that your system might NOT be able to properly boot."
1535   else
1536     einfo "Adjusting grub.cfg for successful boot sequence."
1537     sed -i "s;root=[^ ]\\+;root=UUID=$TARGET_UUID;" "${MNTPOINT}"/boot/grub/grub.cfg
1538   fi
1539
1540   umount "${MNTPOINT}"/proc
1541   umount "${MNTPOINT}"/sys
1542   umount "${MNTPOINT}"/dev/pts
1543   try_umount 3 "${MNTPOINT}"/dev
1544
1545 }
1546 # }}}
1547
1548 # unmount VM image {{{
1549 umount_target() {
1550   if [ -z "${VIRTUAL}" ] ; then
1551      return 0
1552   fi
1553
1554   umount "${MNTPOINT}"
1555   kpartx -d "${ORIG_TARGET}" >/dev/null
1556   # Workaround for a bug in kpartx which doesn't clean up properly,
1557   # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
1558   if dmsetup ls | grep -q "^${LOOP_PART} "; then
1559     kpartx -d "/dev/${LOOP_DISK}" >/dev/null
1560   fi
1561 }
1562 # }}}
1563
1564 # install main chroot {{{
1565 debootstrap_system() {
1566   if [ "$_opt_nodebootstrap" ]; then
1567      einfo "Skipping debootstrap as requested."
1568      return
1569   fi
1570
1571   if grep -q "$MNTPOINT" /proc/mounts || [ -n "$DIRECTORY" ] ; then
1572     :
1573   else
1574     eerror "Error: $MNTPOINT not mounted, can not continue."
1575     eend 1 ; exit 1
1576   fi
1577
1578   if [ -n "$ISO" ] ; then
1579     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${ISO}"
1580     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $ISO"
1581     # shellcheck disable=SC2086
1582     "$DEBOOTSTRAP" $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$ISO"
1583     RC=$?
1584   else
1585     einfo "Running $DEBOOTSTRAP $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${MIRROR}"
1586     einfo "Executing: $DEBOOTSTRAP $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $MIRROR"
1587     # shellcheck disable=SC2086
1588     "$DEBOOTSTRAP" $ARCHCMD $KEYRING $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$MIRROR"
1589     RC=$?
1590   fi
1591
1592   if [ $RC -ne 0 ] ; then
1593     if [ -r "$MNTPOINT/debootstrap/debootstrap.log" ] && \
1594       [ -s "$MNTPOINT/debootstrap/debootstrap.log" ] ; then
1595       einfo "Presenting last ten lines of debootstrap.log:"
1596       tail -10 "${MNTPOINT}"/debootstrap/debootstrap.log
1597       einfo "End of debootstrap.log"
1598     fi
1599   fi
1600
1601   eend $RC
1602 }
1603 # }}}
1604
1605 # prepare chroot via chroot-script {{{
1606 preparechroot() {
1607   einfo "Preparing chroot system"
1608
1609   # provide variables to chroot system
1610   CHROOT_VARIABLES="/var/cache/grml-debootstrap/variables_${SHORT_TARGET}"
1611   touch "$CHROOT_VARIABLES"
1612   chmod 600 "$CHROOT_VARIABLES" # make sure nobody except root can read it
1613   echo "# Configuration of ${PN}"                                                                                   > "$CHROOT_VARIABLES"
1614   # Resorting to sed(1) for escaping since "VAR='${VAR//\'/\'\\\'\'}'" does not work with all versions of Bash,
1615   #   e.g. not with 4.2.37(1)-release (a.k.a 4.2+dfsg-0.1+deb7u3) of Debian wheezy
1616   [ -n "$ARCH" ]                && echo "ARCH='$(sed "s,','\\\\'',g" <<<"${ARCH}")'"                               >> "$CHROOT_VARIABLES"
1617   [ -n "$BACKPORTREPOS" ]       && echo "BACKPORTREPOS='$(sed "s,','\\\\'',g" <<<"${BACKPORTREPOS}")'"             >> "$CHROOT_VARIABLES"
1618   [ -n "$CHROOT_SCRIPTS" ]      && echo "CHROOT_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${CHROOT_SCRIPTS}")'"           >> "$CHROOT_VARIABLES"
1619   [ -n "$COMPONENTS" ]          && echo "COMPONENTS='$(sed "s,','\\\\'',g" <<<"${COMPONENTS}")'"                   >> "$CHROOT_VARIABLES"
1620   [ -n "$CONFFILES" ]           && echo "CONFFILES='$(sed "s,','\\\\'',g" <<<"${CONFFILES}")'"                     >> "$CHROOT_VARIABLES"
1621   [ -n "$DEBCONF" ]             && echo "DEBCONF='$(sed "s,','\\\\'',g" <<<"${DEBCONF}")'"                         >> "$CHROOT_VARIABLES"
1622   [ -n "$DEBIAN_FRONTEND" ]     && echo "DEBIAN_FRONTEND='$(sed "s,','\\\\'',g" <<<"${DEBIAN_FRONTEND}")'"         >> "$CHROOT_VARIABLES"
1623   [ -n "$DEBOOTSTRAP" ]         && echo "DEBOOTSTRAP='$(sed "s,','\\\\'',g" <<<"${DEBOOTSTRAP}")'"                 >> "$CHROOT_VARIABLES"
1624   [ -n "$DEFAULT_LOCALES" ]     && echo "DEFAULT_LOCALES='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LOCALES}")'"         >> "$CHROOT_VARIABLES"
1625   [ -n "$DEFAULT_LANGUAGE" ]    && echo "DEFAULT_LANGUAGE='$(sed "s,','\\\\'',g" <<<"${DEFAULT_LANGUAGE}")'"       >> "$CHROOT_VARIABLES"
1626   [ -n "$EXTRAPACKAGES" ]       && echo "EXTRAPACKAGES='$(sed "s,','\\\\'',g" <<<"${EXTRAPACKAGES}")'"             >> "$CHROOT_VARIABLES"
1627   [ -n "$EFI" ]                 && echo "EFI='$(sed "s,','\\\\'',g" <<<"${EFI}")'"                                 >> "$CHROOT_VARIABLES"
1628   [ -n "$FALLBACK_MIRROR" ]     && echo "FALLBACK_MIRROR='$(sed "s,','\\\\'',g" <<<"${FALLBACK_MIRROR}")'"         >> "$CHROOT_VARIABLES"
1629   [ -n "$FORCE" ]               && echo "FORCE='$(sed "s,','\\\\'',g" <<<"${FORCE}")'"                             >> "$CHROOT_VARIABLES"
1630   [ -n "$GRMLREPOS" ]           && echo "GRMLREPOS='$(sed "s,','\\\\'',g" <<<"${GRMLREPOS}")'"                     >> "$CHROOT_VARIABLES"
1631   [ -n "$GRUB" ]                && echo "GRUB='$(sed "s,','\\\\'',g" <<<"${GRUB}")'"                               >> "$CHROOT_VARIABLES"
1632   [ -n "$HOSTNAME" ]            && echo "HOSTNAME='$(sed "s,','\\\\'',g" <<<"${HOSTNAME}")'"                       >> "$CHROOT_VARIABLES"
1633   [ -n "$INITRD" ]              && echo "INITRD='$(sed "s,','\\\\'',g" <<<"${INITRD}")'"                           >> "$CHROOT_VARIABLES"
1634   [ -n "$INSTALL_NOTES" ]       && echo "INSTALL_NOTES='$(sed "s,','\\\\'',g" <<<"${INSTALL_NOTES}")'"             >> "$CHROOT_VARIABLES"
1635   [ -n "$ISODIR" ]              && echo "ISODIR='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                              >> "$CHROOT_VARIABLES"
1636   [ -n "$ISO" ]                 && echo "ISO='$(sed "s,','\\\\'',g" <<<"${ISO}")'"                                 >> "$CHROOT_VARIABLES"
1637   [ -n "$KEEP_SRC_LIST" ]       && echo "KEEP_SRC_LIST='$(sed "s,','\\\\'',g" <<<"${KEEP_SRC_LIST}")'"             >> "$CHROOT_VARIABLES"
1638   [ -n "$LOCALES" ]             && echo "LOCALES='$(sed "s,','\\\\'',g" <<<"${LOCALES}")'"                         >> "$CHROOT_VARIABLES"
1639   [ -n "$MIRROR" ]              && echo "MIRROR='$(sed "s,','\\\\'',g" <<<"${MIRROR}")'"                           >> "$CHROOT_VARIABLES"
1640   [ -n "$MKFS" ]                && echo "MKFS='$(sed "s,','\\\\'',g" <<<"${MKFS}")'"                               >> "$CHROOT_VARIABLES"
1641   [ -n "$NOPASSWORD" ]          && echo "NOPASSWORD=\"true\""                                                      >> "$CHROOT_VARIABLES"
1642   [ -n "$NOKERNEL" ]            && echo "NOKERNEL=\"true\""                                                        >> "$CHROOT_VARIABLES"
1643   [ -n "$PACKAGES" ]            && echo "PACKAGES='$(sed "s,','\\\\'',g" <<<"${PACKAGES}")'"                       >> "$CHROOT_VARIABLES"
1644   [ -n "$POST_SCRIPTS" ]        && echo "POST_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${POST_SCRIPTS}")'"               >> "$CHROOT_VARIABLES"
1645   [ -n "$PRE_SCRIPTS" ]         && echo "PRE_SCRIPTS='$(sed "s,','\\\\'',g" <<<"${PRE_SCRIPTS}")'"                 >> "$CHROOT_VARIABLES"
1646   [ -n "$RECONFIGURE" ]         && echo "RECONFIGURE='$(sed "s,','\\\\'',g" <<<"${RECONFIGURE}")'"                 >> "$CHROOT_VARIABLES"
1647   [ -n "$RELEASE" ]             && echo "RELEASE='$(sed "s,','\\\\'',g" <<<"${RELEASE}")'"                         >> "$CHROOT_VARIABLES"
1648   [ -n "$RM_APTCACHE" ]         && echo "RM_APTCACHE='$(sed "s,','\\\\'',g" <<<"${RM_APTCACHE}")'"                 >> "$CHROOT_VARIABLES"
1649   [ -n "$ROOTPASSWORD" ]        && echo "ROOTPASSWORD='$(sed "s,','\\\\'',g" <<<"${ROOTPASSWORD}")'"               >> "$CHROOT_VARIABLES"
1650   [ -n "$SCRIPTS" ]             && echo "SCRIPTS='$(sed "s,','\\\\'',g" <<<"${SCRIPTS}")'"                         >> "$CHROOT_VARIABLES"
1651   [ -n "$SECURE" ]              && echo "SECURE='$(sed "s,','\\\\'',g" <<<"${SECURE}")'"                           >> "$CHROOT_VARIABLES"
1652   [ -n "$SELECTED_PARTITIONS" ] && echo "SELECTED_PARTITIONS='$(sed "s,','\\\\'',g" <<<"${SELECTED_PARTITIONS}")'" >> "$CHROOT_VARIABLES"
1653   [ -n "$TARGET" ]              && echo "TARGET='$(sed "s,','\\\\'',g" <<<"${TARGET}")'"                           >> "$CHROOT_VARIABLES"
1654   [ -n "$UPGRADE_SYSTEM" ]      && echo "UPGRADE_SYSTEM='$(sed "s,','\\\\'',g" <<<"${UPGRADE_SYSTEM}")'"           >> "$CHROOT_VARIABLES"
1655   [ -n "$TARGET_UUID" ]         && echo "TARGET_UUID='$(sed "s,','\\\\'',g" <<<"${TARGET_UUID}")'"                 >> "$CHROOT_VARIABLES"
1656   [ -n "$TIMEZONE" ]            && echo "TIMEZONE='$(sed "s,','\\\\'',g" <<<"${TIMEZONE}")'"                       >> "$CHROOT_VARIABLES"
1657   [ -n "$TUNE2FS" ]             && echo "TUNE2FS='$(sed "s,','\\\\'',g" <<<"${TUNE2FS}")'"                         >> "$CHROOT_VARIABLES"
1658   [ -n "$VMSIZE" ]              && echo "VMSIZE='$(sed "s,','\\\\'',g" <<<"${VMSIZE}")'"                           >> "$CHROOT_VARIABLES"
1659
1660   cp $VERBOSE "${CONFFILES}"/chroot-script "${MNTPOINT}"/bin/chroot-script
1661   chmod 755 "${MNTPOINT}"/bin/chroot-script
1662   [ -d "$MNTPOINT"/etc/debootstrap/ ] || mkdir "$MNTPOINT"/etc/debootstrap/
1663
1664   # make sure we have our files for later use via chroot-script
1665   cp $VERBOSE "${CONFFILES}/config"           "${MNTPOINT}"/etc/debootstrap/
1666   # make sure we adjust the configuration variables accordingly:
1667   sed -i "s#RELEASE=.*#RELEASE=\"$RELEASE\"#" "${MNTPOINT}"/etc/debootstrap/config
1668   sed -i "s#TARGET=.*#TARGET=\"$TARGET\"#"    "${MNTPOINT}"/etc/debootstrap/config
1669   sed -i "s#GRUB=.*#GRUB=\"$GRUB\"#"          "${MNTPOINT}"/etc/debootstrap/config
1670
1671   # install notes:
1672   if [ -n "$INSTALL_NOTES" ] ; then
1673      [ -r "$INSTALL_NOTES" ] && cp "$INSTALL_NOTES" "${MNTPOINT}"/etc/debootstrap/
1674   fi
1675
1676   # package selection:
1677   if [ "$PACKAGES" = 'yes' ] ; then
1678     cp $VERBOSE "${_opt_packages:-$CONFFILES/packages}" \
1679       "${MNTPOINT}"/etc/debootstrap/packages
1680   fi
1681
1682   # debconf preseeding:
1683   _opt_debconf=${_opt_debconf:-$CONFFILES/debconf-selections}
1684   [ -f "${_opt_debconf}" ] && [ "$DEBCONF" = 'yes' ] && \
1685     cp $VERBOSE "${_opt_debconf}" "${MNTPOINT}"/etc/debootstrap/debconf-selections
1686
1687   # copy scripts that should be executed inside the chroot:
1688   _opt_chroot_scripts=${_opt_chroot_scripts:-$CONFFILES/chroot-scripts/}
1689   [ -d "$_opt_chroot_scripts" ] && [ "$CHROOT_SCRIPTS" = 'yes' ] && {
1690     mkdir -p "${MNTPOINT}"/etc/debootstrap/chroot-scripts
1691     cp -a $VERBOSE "${_opt_chroot_scripts}"/* "${MNTPOINT}"/etc/debootstrap/chroot-scripts/
1692   }
1693
1694   # notice: do NOT use $CHROOT_VARIABLES inside chroot but statically file instead!
1695   cp $VERBOSE "${CHROOT_VARIABLES}" "${MNTPOINT}"/etc/debootstrap/variables
1696
1697   cp $VERBOSE -a -L "${CONFFILES}"/extrapackages/ "${MNTPOINT}"/etc/debootstrap/
1698
1699   # make sure we can access network [relevant for cdebootstrap/mmdebstrap]
1700   [ -f "${MNTPOINT}"/etc/resolv.conf ] || cp $VERBOSE /etc/resolv.conf "${MNTPOINT}"/etc/resolv.conf
1701
1702   # setup default locales
1703   [ -n "$LOCALES" ] && cp $VERBOSE "${CONFFILES}"/locale.gen "${MNTPOINT}"/etc/locale.gen
1704
1705   # MAKEDEV is just a forking bomb crap, let's do it on our own instead :)
1706   ( cd "${MNTPOINT}"/dev && tar zxf /etc/debootstrap/devices.tar.gz )
1707
1708   # copy any existing files to chroot
1709   [ -d "${CONFFILES}"/bin   ] && cp $VERBOSE -a -L "${CONFFILES}"/bin/*   "${MNTPOINT}"/bin/
1710   [ -d "${CONFFILES}"/boot  ] && cp $VERBOSE -a -L "${CONFFILES}"/boot/*  "${MNTPOINT}"/boot/
1711   [ -d "${CONFFILES}"/etc   ] && cp $VERBOSE -a -L "${CONFFILES}"/etc/*   "${MNTPOINT}"/etc/
1712   [ -d "${CONFFILES}"/sbin  ] && cp $VERBOSE -a -L "${CONFFILES}"/sbin/*  "${MNTPOINT}"/sbin/
1713   [ -d "${CONFFILES}"/share ] && cp $VERBOSE -a -L "${CONFFILES}"/share/* "${MNTPOINT}"/share/
1714   [ -d "${CONFFILES}"/usr   ] && cp $VERBOSE -a -L "${CONFFILES}"/usr/*   "${MNTPOINT}"/usr/
1715   [ -d "${CONFFILES}"/var   ] && cp $VERBOSE -a -L "${CONFFILES}"/var/*   "${MNTPOINT}"/var/
1716
1717   # network setup
1718   DEFAULT_INTERFACES="# /etc/network/interfaces - generated by grml-debootstrap
1719
1720 # Include files from /etc/network/interfaces.d when using
1721 # ifupdown v0.7.44 or newer:
1722 #source-directory /etc/network/interfaces.d
1723
1724 auto lo
1725 iface lo inet loopback
1726
1727 allow-hotplug eth0
1728 iface eth0 inet dhcp
1729 "
1730
1731   # add dhcp setting for Predictable Network Interface Names
1732   if [ -x /bin/udevadm ]; then
1733     tmpfile=$(mktemp)
1734     for interface in /sys/class/net/*; do
1735       udevadm info --query=all --path="${interface}" > "${tmpfile}"
1736       # skip virtual devices, like bridges, vboxnet,...
1737       if grep -q 'P: /devices/virtual/net/' "${tmpfile}" ; then
1738         continue
1739       fi
1740
1741       # iterate over possible naming policies by precedence (see udev/net/link-config.c),
1742       # use and stop on first match to have same behavior as udev's link_config_apply()
1743       for property in ID_NET_NAME_FROM_DATABASE ID_NET_NAME_ONBOARD ID_NET_NAME_SLOT ID_NET_NAME_PATH ID_NET_NAME_MAC ; do
1744         if grep -q "${property}" "${tmpfile}" ; then
1745           interface=$(grep "${property}" "${tmpfile}" | sed -n -e "s/E: ${property}=\([^\$*]\)/\1/p")
1746           DEFAULT_INTERFACES="${DEFAULT_INTERFACES}
1747 allow-hotplug ${interface}
1748 iface ${interface} inet dhcp
1749 "
1750           break
1751         fi
1752       done
1753     done
1754     rm -f "${tmpfile}"
1755   fi
1756
1757   if [ -n "$NOINTERFACES" ] ; then
1758     einfo "Not installing /etc/network/interfaces as requested via --nointerfaces option" ; eend 0
1759   elif [ -n "$USE_DEFAULT_INTERFACES" ] ; then
1760     einfo "Installing default /etc/network/interfaces as requested via --defaultinterfaces options."
1761     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1762     eend $?
1763   elif [ -n "$VIRTUAL" ] ; then
1764     einfo "Setting up Virtual Machine, installing default /etc/network/interfaces"
1765     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1766     eend $?
1767   elif [ -r /etc/network/interfaces ] ; then
1768     einfo "Copying /etc/network/interfaces from host to target system"
1769     cp $VERBOSE /etc/network/interfaces "${MNTPOINT}/etc/network/interfaces"
1770     eend $?
1771   else
1772     ewarn "Couldn't read /etc/network/interfaces, installing default /etc/network/interfaces"
1773     echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
1774     eend $?
1775   fi
1776
1777   # install config file providing some example entries
1778   if [ -r /etc/network/interfaces.examples ] && [ ! -r "$MNTPOINT/etc/network/interfaces.examples" ] ; then
1779      cp /etc/network/interfaces.examples "$MNTPOINT/etc/network/interfaces.examples"
1780   fi
1781
1782   if [ -n "${SSHCOPYID}" ] ; then
1783     if ssh-add -L >/dev/null 2>&1 ; then
1784       einfo "Use locally available public keys to authorise root login on the target system as requested via --sshcopyid option."
1785       mkdir -p "${MNTPOINT}"/root/.ssh
1786       chmod 0700 "${MNTPOINT}"/root/.ssh
1787       if ssh-add -L >> "${MNTPOINT}"/root/.ssh/authorized_keys ; then
1788         eend 0
1789       else
1790         eerror "Error: executing 'ssh-add -L' failed."
1791         eend 1
1792         bailout 1
1793       fi
1794     else
1795       eerror "Could not open a connection to your authentication agent or the agent has no identites."
1796       eend 1
1797       bailout 1
1798     fi
1799   fi
1800
1801   if [ -d /run/udev ] ; then
1802     einfo "Setting up bind-mount /run/udev"
1803     mkdir -p "${MNTPOINT}"/run/udev
1804     mount --bind /run/udev "${MNTPOINT}"/run/udev
1805     eend $?
1806   fi
1807
1808   eend 0
1809 }
1810 # }}}
1811
1812 # execute all scripts in /etc/debootstrap/pre-scripts/ {{{
1813 execute_pre_scripts() {
1814   # make sure hostname is set even before chroot-script get executed
1815   echo "$HOSTNAME" > "$MNTPOINT"/etc/hostname
1816
1817   # make sure we have $MNTPOINT available for our scripts
1818   export MNTPOINT
1819
1820   if [ -d "$_opt_pre_scripts" ] || [ "$PRE_SCRIPTS" = 'yes' ] ; then
1821     [ -d "$_opt_pre_scripts" ] && pre_scripts="$_opt_pre_scripts" || pre_scripts="${CONFFILES}/pre-scripts/"
1822     for script in "${pre_scripts}"/* ; do
1823       if [ -x "$script" ] ; then
1824         einfo "Executing pre-script $script"
1825         "$script" ; eend $?
1826       fi
1827     done
1828   fi
1829 }
1830 # }}}
1831
1832 # execute all scripts in /etc/debootstrap/post-scripts/ {{{
1833 execute_post_scripts() {
1834   # make sure we have $MNTPOINT and HOSTNAME available for our scripts
1835   export MNTPOINT
1836   export TARGET_HOSTNAME=$HOSTNAME
1837
1838   if [ -d "$_opt_scripts" ] || [ "$SCRIPTS" = 'yes' ] ; then
1839     # legacy support for /etc/debootstrap/scripts/
1840     [ -d "$_opt_scripts" ] && post_scripts="$_opt_scripts" || post_scripts="${CONFFILES}/scripts/"
1841     ewarn "Deprecation NOTE: --scripts/SCRIPTS are deprecated, please switch to --post-scripts/POST_SCRIPTS instead."
1842   elif [ -d "$_opt_post_scripts" ] || [ "$POST_SCRIPTS" = 'yes' ] ; then
1843     [ -d "$_opt_post_scripts" ] && post_scripts="$_opt_post_scripts" || post_scripts="${CONFFILES}/post-scripts/"
1844   fi
1845
1846   if [ -n "$post_scripts" ] ; then
1847     for script in "${post_scripts}"/* ; do
1848       if [ -x "$script" ] ; then
1849         einfo "Executing post-script $script"
1850         "$script" ; eend $?
1851       fi
1852     done
1853   fi
1854 }
1855 # }}}
1856
1857 # unmount mountpoint {{{
1858 try_umount() {
1859   local tries=$1
1860   local mountpoint="$2"
1861
1862   for (( try=1; try<=tries; try++ )); do
1863     if [[ ${try} -eq ${tries} ]]; then
1864       # Last time, show errors this time
1865       umount "${mountpoint}" && return 0
1866     else
1867       # Not last time, hide errors until fatal
1868       if umount "${mountpoint}" 2>/dev/null ; then
1869         return 0
1870       else
1871         sleep 1
1872       fi
1873     fi
1874   done
1875   return 1  # Tried enough
1876 }
1877 # }}}
1878
1879 # execute chroot-script {{{
1880 chrootscript() {
1881   if ! [ -r "$MNTPOINT/bin/chroot-script" ] ; then
1882     mount_target
1883   fi
1884
1885   if ! [ -x "$MNTPOINT/bin/chroot-script" ] ; then
1886     eerror "Fatal: $MNTPOINT/bin/chroot-script could not be found."
1887     eend 1
1888   else
1889     einfo "Executing chroot-script now"
1890     mount -t devtmpfs udev "${MNTPOINT}"/dev
1891     mount -t devpts devpts "${MNTPOINT}"/dev/pts
1892     if [ "$DEBUG" = "true" ] ; then
1893       chroot "$MNTPOINT" /bin/bash -x /bin/chroot-script ; RC=$?
1894     else
1895       chroot "$MNTPOINT" /bin/chroot-script ; RC=$?
1896     fi
1897     try_umount 3 "$MNTPOINT"/dev/pts
1898     try_umount 3 "$MNTPOINT"/dev
1899     eend $RC
1900   fi
1901
1902   # finally get rid of chroot-script again, there's no good reason to
1903   # keep it on the installed system
1904   if grep -q GRML_CHROOT_SCRIPT_MARKER "${MNTPOINT}/bin/chroot-script" ; then
1905     einfo "Removing chroot-script again"
1906     rm -f "${MNTPOINT}/bin/chroot-script"
1907     eend $?
1908   else
1909     einfo "Keeping chroot-script as string GRML_CHROOT_SCRIPT_MARKER could not be found"
1910     eend 0
1911   fi
1912 }
1913 # }}}
1914
1915 # unmount $MNTPOINT {{{
1916 umount_chroot() {
1917
1918   # display installation notes:
1919   if [ -n "$INSTALL_NOTES" ] ; then
1920      [ -r "${MNTPOINT}/${INSTALL_NOTES}" ] && cat "${MNTPOINT}/${INSTALL_NOTES}"
1921   fi
1922
1923   if [ -n "$ISODIR" ] ; then
1924      if grep -q "$ISODIR" /proc/mounts ; then
1925         einfo "Unmount $MNTPOINT/$ISODIR"
1926         umount "$MNTPOINT/$ISODIR"
1927         eend $?
1928      fi
1929   fi
1930
1931   if grep -q "$MNTPOINT" /proc/mounts ; then
1932     if mountpoint "${MNTPOINT}"/run/udev &>/dev/null ; then
1933       einfo "Unmounting bind-mount /run/udev"
1934       umount "${MNTPOINT}"/run/udev
1935       eend $?
1936     fi
1937
1938      if [ -n "$PARTITION" ] ; then
1939         einfo "Unmount $MNTPOINT"
1940         umount "$MNTPOINT"
1941         eend $?
1942      fi
1943   fi
1944 }
1945 # }}}
1946
1947 # execute filesystem check {{{
1948 fscktool() {
1949  if [ -n "$VIRTUAL" ] ; then
1950    einfo "Skipping filesystem check because we deploy a virtual machine."
1951    return 0
1952  fi
1953
1954  if [ "$FSCK" = 'yes' ] ; then
1955    [ -n "$FSCKTOOL" ] || FSCKTOOL="fsck.${MKFS#mkfs.}"
1956    einfo "Checking filesystem on $TARGET using $FSCKTOOL"
1957    "$FSCKTOOL" "$TARGET"
1958    eend $?
1959  fi
1960 }
1961 # }}}
1962
1963 # get rid of grml-debootstrap config files {{{
1964 remove_configs() {
1965   if [ "$REMOVE_CONFIGS" != "yes" ] ; then
1966     return 0
1967   fi
1968
1969   if ! mountpoint "${MNTPOINT}" >/dev/null 2>&1 ; then
1970     ewarn "Target ${MNTPOINT} doesn't seem to be mounted, can't remove configuration files." ; eend 0
1971     return 0
1972   fi
1973
1974   einfo "Removing configuration files from installed system as requested via --remove-configs / REMOVE_CONFIGS."
1975   rm -rf "${MNTPOINT}"/etc/debootstrap/
1976   eend $?
1977 }
1978 # }}}
1979
1980 # now execute all the functions {{{
1981 for i in format_efi_partition prepare_vm mkfs tunefs \
1982          mount_target mountpoint_to_blockdevice debootstrap_system \
1983          preparechroot execute_pre_scripts chrootscript execute_post_scripts \
1984          remove_configs umount_chroot grub_install umount_target fscktool ; do
1985     if stage "${i}" ; then
1986       if "$i" ; then
1987         stage "${i}" 'done' && rm -f "${STAGES}/${i}"
1988       else
1989         bailout 2 "$i"
1990       fi
1991     fi
1992 done
1993
1994 cleanup
1995 # }}}
1996
1997 # end dialog of autoinstallation {{{
1998 if [ -n "$AUTOINSTALL" ] ; then
1999    if dialog --title "${PN}" --pause "Finished execution of ${PN}.
2000 Automatically rebooting in 10 seconds.
2001
2002 Choose Cancel to skip rebooting." 10 60 10 ; then
2003      noeject noprompt reboot
2004   fi
2005 else
2006    einfo "Finished execution of ${PN}. Enjoy your Debian system." ; eend 0
2007 fi
2008 # }}}
2009
2010 ## END OF FILE #################################################################
2011 # vim: ai tw=100 expandtab foldmethod=marker shiftwidth=2