#!/bin/bash
# Filename:      grml-debootstrap
# Purpose:       wrapper around debootstrap for installing plain Debian via Grml
# Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
# Bug-Reports:   see https://grml.org/bugs/
# License:       This file is licensed under the GPL v2+
################################################################################
# shellcheck disable=SC2001,SC2181

# error_handler {{{
error_handler() {
   last_exit_code="$?"
   last_bash_command="$BASH_COMMAND"
   echo "Unexpected non-zero exit code $last_exit_code in ${BASH_SOURCE[*]} at line ${BASH_LINENO[*]} detected!
last bash command: $last_bash_command"
   if [ -r "$MNTPOINT/debootstrap/debootstrap.log" ] && \
          [ -s "$MNTPOINT/debootstrap/debootstrap.log" ] ; then
       einfo "Presenting last ten lines of debootstrap.log:"
       tail -10 "${MNTPOINT}"/debootstrap/debootstrap.log
       einfo "End of debootstrap.log"
   fi
   ## Check if "bailout" function is already available.
   if command -v bailout >/dev/null 2>&1; then
      bailout 1
   else
      exit 1
   fi
}

set -e
set -E
set -o pipefail
trap "error_handler" ERR
# }}}

# variables {{{
PN="$(basename "$0")"
if [[ -d "$(dirname "$(command -v "$0")")"/.git ]]; then
  VERSION="$(git --git-dir "$(dirname "$(command -v "$0")")"/.git describe | sed 's|^v||')"
else
  VERSION="$(dpkg-query --show --showformat='${Version}' "$PN")"
fi
VERSION="${VERSION:-unknown}"
MNTPOINT="/mnt/debootstrap.$$"

# defaults
[ -n "$CHROOT_SCRIPTS" ] || CHROOT_SCRIPTS='yes'
[ -n "$CONFFILES" ] || CONFFILES='/etc/debootstrap'
[ -n "$DEBCONF" ] || DEBCONF='yes'
[ -n "$DEBIAN_FRONTEND" ] || DEBIAN_FRONTEND='noninteractive'
[ -n "$DEFAULT_LANGUAGE" ] || DEFAULT_LANGUAGE='en_US:en'
[ -n "$DEFAULT_LOCALES" ] || DEFAULT_LOCALES='en_US.UTF-8'
[ -n "$DISK_IDENTIFIER" ] || DISK_IDENTIFIER='26ada0c0-1165-4098-884d-aafd2220c2c6'
[ -n "$EXTRAPACKAGES" ] || EXTRAPACKAGES='yes'
[ -n "$FALLBACK_MIRROR" ] || FALLBACK_MIRROR='http://deb.debian.org/debian'
[ -n "$FIXED_DISK_IDENTIFIERS" ] || FIXED_DISK_IDENTIFIERS="no"
[ -n "$FORCE" ] || FORCE=''
[ -n "$HOSTNAME" ] || HOSTNAME='grml'
[ -n "$INITRD" ] || INITRD='yes'
[ -n "$INITRD_GENERATOR" ] || INITRD_GENERATOR='initramfs-tools'
[ -n "$INITRD_GENERATOR_OPTS" ] || INITRD_GENERATOR_OPTS=''
[ -n "$INSTALL_NOTES" ] || INSTALL_NOTES='/etc/debootstrap/install_notes'
[ -n "$LOCALES" ] || LOCALES='yes'
[ -n "$MIRROR" ] || MIRROR="$FALLBACK_MIRROR"
[ -n "$MKFS" ] || MKFS='mkfs.ext4'
[ -n "$MKFS_OPTS" ] || MKFS_OPTS=''
[ -n "$PACKAGES" ] || PACKAGES='yes'
[ -n "$POST_SCRIPTS" ] || POST_SCRIPTS='yes'
[ -n "$PRE_SCRIPTS" ] || PRE_SCRIPTS='yes'
[ -n "$RECONFIGURE" ] || RECONFIGURE='console-data'
[ -n "$RELEASE" ] || RELEASE='trixie'
[ -n "$RM_APTCACHE" ] || RM_APTCACHE='yes'
[ -n "$SCRIPTS" ] || SCRIPTS='no' # deprecated, replaced by POST_SCRIPTS
[ -n "$SECURE" ] || SECURE='yes'
[ -n "$TIMEZONE" ] || TIMEZONE='Europe/Vienna'
[ -n "$TUNE2FS" ] || TUNE2FS='tune2fs -c0 -i0'
[ -n "$UPGRADE_SYSTEM" ] || UPGRADE_SYSTEM='yes'
[ -n "$VMSIZE" ] || VMSIZE="2G"
[ -n "$GRUB_INSTALL" ] || GRUB_INSTALL='yes'

# make sure interactive mode is only executed when
# using an empty configuration file or option --interactive
INTERACTIVE=''
# }}}

# help text {{{
usage() {
  echo "$PN - wrapper around debootstrap for installing Debian

Usage: $PN [options]

Bootstrap options:

  -m, --mirror <URL>     Mirror which should be used for apt-get/aptitude.
  -r, --release <name>   Release of new Debian system (default: bullseye).
  -t, --target <target>  Target partition (/dev/...) or directory where the
                         system should be installed to.
  -p, --mntpoint <mnt>   Mountpoint used for mounting the target system,
                         has no effect if -t is given and represents a directory.
      --debopt <params>  Extra parameters passed to the debootstrap command.
      --interactive      Use interactive mode (frontend).
      --nodebootstrap    Skip debootstrap, only do configuration to the target.
      --grub <device>    Target for grub installation. Usage example: /dev/sda
      --efi <device>     Target for EFI installation. Usage example: /dev/sda1
      --arch <arch>      Set target architecture.
      --filesystem <fs>  Filesystem that should be used when target is a partition
                         or Virtual Machine (see --vmfile).
      --force            Do not prompt for user acknowledgement.

Options for Virtual Machine deployment:

      --vm               Set up a Virtual Machine on an existing block device
                         instead of plainly installing to a partition or
                         directory. Needs to be combined with --target.
                         Example: --vm --target /dev/mapper/your-vm-disk
      --vmfile           Like --vm, but install into a regular file (created by
                         'qemu-img create -f raw ...') instead.
                         Example: --vmfile --target /mnt/sda1/qemu.img
      --vmsize <size>    Use specified size for size of VM file (default: 2G).
                         Syntax as supported by qemu-img, like: --vmsize 3G
      --vmefi            Create an EFI boot partition for the VM.

Configuration options:

  -c, --config <file>      Use specified configuration file, defaults to
                             /etc/debootstrap/config
  -d, --confdir <path>     Place of config files for debootstrap, defaults
                             to /etc/debootstrap
      --packages <file>    Install packages defined in specified list file
                             instead of using /etc/debootstrap/packages.
      --nopackages         Skip installation of packages defined in
                             /etc/debootstrap/packages
      --nokernel           Skip installation of default kernel images.
      --nointerfaces       Do not copy /etc/network/interfaces from host system
                           to target system.
                           (This option is automatically enabled when using --vmfile.)
      --defaultinterfaces  Install a default /etc/network/interfaces file (enabling
                           DHCP for eth0) instead of taking over config from host system.
      --debconf <file>     Pre-seed packages using specified pre-seed db file.
      --grmlrepos          Enable Grml's Debian repository (deb.grml.org).
      --backportrepos      Enable Debian's backports repository (backports.debian.org).
      --keep_src_list      Do not overwrite user provided apt sources.list.
      --contrib            Enable 'contrib' in COMPONENTS (defaults to 'main' only).
      --non-free           Enable non-free / non-free-firmware in COMPONENTS (defaults to 'main' only).
      --hostname <name>    Hostname of Debian system.
      --nopassword         Do not prompt for the root password.
      --password <pwd>     Use specified password as password for user root.
      --sshcopyauth        Use ${HOME}/.ssh/authorized_keys to authorise root login on the target system.
      --sshcopyid          Use locally available public keys to authorise root login on the target system.
      --bootappend <line>  Add specified appendline to kernel whilst booting.
      --chroot-scripts <d> Execute chroot scripts from specified directory.
      --pre-scripts <dir>  Execute scripts from specified directory (before chroot-scripts).
      --scripts <dir>      Execute scripts from specified directory (after chroot-scripts).
      --remove-configs     Delete grml-debootstrap configuration files from installed system.

Other options:

  -v, --verbose            Increase verbosity.
      --debug              Execute in very verbose way.
  -h, --help               Print this usage information and exit.
  -V, --version            Show summary of options and exit.

Usage examples can be found in the grml-debootstrap manpage.
Send bugreports to the grml-team: bugs (at) grml.org || https://grml.org/bugs/
"
}

if [ "$1" = '-h' ] || [ "$1" = '-help' ] || [ "$1" = "--help" ] ; then
   usage
   echo 'Please notice that this script requires root permissions!'
   exit 0
fi
# }}}

# early helper functions {{{
# skip colors when running within a dumb terminal
if [ "${TERM}" = "dumb" ] ; then
  GOOD=
  BAD=
  WARN=
  NORMAL=
else
  GOOD='[32;01m'
  BAD='[31;01m'
  WARN='[33;01m'
  NORMAL='[0m'
fi

einfo() {
  einfon "$1\\n"
  return 0
}

einfon() {
  [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
  printf " %s*%s $*" "${GOOD}" "${NORMAL}"
  LAST_E_CMD=einfon
  return 0
}

ewarn() {
  printf " %s*%s $*\\n" "${WARN}" "${NORMAL}"
  return 0
}

eerror() {
  [ "${RC_ENDCOL}" != "yes" ] && [ "${LAST_E_CMD}" = "ebegin" ] && echo
  printf " %s*%s $*\\n" "${BAD}" "${NORMAL}" >&2
  LAST_E_CMD=eerror
  return 0
}

eend() {
  local retval="${1:-0}"
  shift
  if [ "$retval" -gt 0 ]; then
    printf " %s-> Failed (rc=%s)%s\\n" "${BAD}" "${retval}" "${NORMAL}"
  fi
  return "$retval"
}

check4root(){
  if [ "$(id -u 2>/dev/null)" != 0 ] ; then
    echo 1>&2 "Error: please run this script with uid 0 (root)." ; return 1
  fi
}

check4progs(){
  local RC=''
  for arg in "$@" ; do
    command -v "$arg" >/dev/null 2>&1 || RC="$arg"
  done
  if [ -n "$RC" ] ; then
     echo "$RC not installed"
     return 1
  fi
}
# }}}

# unmount mountpoint {{{
try_umount() {
  local tries=$1
  local mountpoint="$2"

  if ! mountpoint "$mountpoint" &>/dev/null ; then
    return 0
  fi

  for (( try=1; try<=tries; try++ )); do
    if [[ ${try} -eq ${tries} ]]; then
      # Last time, show errors this time
      umount "${mountpoint}" && return 0
    else
      # Not last time, hide errors until fatal
      if umount "${mountpoint}" 2>/dev/null ; then
        return 0
      else
        sleep 1
      fi
    fi
  done
  return 1  # Tried enough
}
# }}}

# helper functions {{{
cleanup() {
  if [ -n "$CHROOT_VARIABLES" ] ; then
    einfo "Removing ${CHROOT_VARIABLES}" ; rm "$CHROOT_VARIABLES" || eend $?
  fi

  if [ -n "$STAGES" ] ; then
    einfo "Removing ${STAGES}" ; rmdir "$STAGES" || eend $?
  fi

  try_umount 3 "${MNTPOINT}"/boot/efi

  # Remove temporary mountpoint again
  if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
    if [ -d "$MNTPOINT" ] ; then
      rmdir "$MNTPOINT" || true
    fi
  fi

  # make sure $TARGET is not mounted when exiting grml-debootstrap
  if [ -n "$MNTPOINT" ] ; then
    if grep -q "$MNTPOINT" /proc/mounts ; then
      # make sure nothing is left inside chroot so we can unmount it
      for service in ssh mdadm ; do
        if [ -x "${MNTPOINT}/etc/init.d/${service}" ] ; then
          clean_chroot "$MNTPOINT" "/etc/init.d/${service}" stop
        fi
      done

      [ -x "$MNTPOINT"/bin/umount ] && { clean_chroot "$MNTPOINT" umount -a >/dev/null 2>&1 || true; }

      # ugly, but make sure we really don't leave anything (/proc /proc and
      # /dev /dev are intended, trying to work around timing issues, see #657023)
      for ARG in /run/udev /sys /proc /proc /dev/pts /dev/pts /dev /dev ; do
        [ -x "$MNTPOINT"/bin/umount ] && { clean_chroot "$MNTPOINT" umount $ARG >/dev/null 2>&1 || true; }
        umount "$MNTPOINT"/$ARG >/dev/null 2>&1 || true
      done

      if [ -n "$DIRECTORY" ] ; then
        einfo "Not unmounting $MNTPOINT as you requested me to install into a directory of your own choice."
      else
        einfo "Unmounting $MNTPOINT"
        try_umount 3 "$MNTPOINT"
      fi

      if [ -n "$STAGES" ] ; then
        echo -n "Removing stages directory ${STAGES}: "
        rm -rf "$STAGES" && echo 'done'
      fi

      # remove directory only if we used the default with process id inside the name
      if echo "$MNTPOINT" | grep -q '/mnt/debootstrap\.' ; then
        if [ -d "$MNTPOINT" ] ; then
          einfo "Removing directory ${MNTPOINT}"
          rmdir "$MNTPOINT" || eend $?
        fi
      fi
    fi
  fi

  if [ -n "${ORIG_TARGET}" ] ; then
    einfo "Removing loopback mount of file ${ORIG_TARGET}."
    kpartx -d "${ORIG_TARGET}" || eend $?
    # Workaround for a bug in kpartx which doesn't clean up properly,
    # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
    if dmsetup ls | grep -q "^${LOOP_PART} "; then
      kpartx -d "/dev/${LOOP_DISK}" >/dev/null || eend $?
    fi
  fi
}

# we want to exit smoothly and clean:
bailout(){
  eend "$1" || true

  cleanup

  [ -n "$1" ] && EXIT="$1" || EXIT="1"
  [ -n "$2" ] && einfo "Notice: remove $STAGES/$2 to reexecute the stage"

  exit "$EXIT"
}
trap bailout HUP INT QUIT TERM

# we want to execute all the functions only once, simple check for it:
stage() {
  if [ -n "$2" ] ; then
     echo "$2" > "${STAGES}/${1}"
     return 0
  elif grep -q 'done' "${STAGES}/${1}" 2>/dev/null ; then
     ewarn "Notice: stage $1 has been executed already, skipping execution therefore."
     ewarn "  To reexecute it clean up the according directory inside $STAGES"
     return 1
  fi
}
# }}}

# source main configuration file {{{
if [ -r /etc/debootstrap/config ] ; then
  bash -n /etc/debootstrap/config
  # shellcheck disable=SC1091
  . /etc/debootstrap/config
fi
# }}}

# cmdline handling {{{
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:,vmefi,keep_src_list,hostname:,password:,nopassword,grmlrepos,backportrepos,bootappend:,grub:,efi:,arch:,insecure,verbose,help,version,force,debug,contrib,non-free,remove-configs,sshcopyid,sshcopyauth

if ! _opt_temp=$(getopt --name grml-debootstrap -o +m:i:r:t:p:c:d:vhV --long \
  $CMDLINE_OPTS -- "$@"); then
  eerror "Try 'grml-debootstrap --help' for more information."
  bailout 1
fi
eval set -- "$_opt_temp"

while :; do
  case "$1" in

  # == Bootstrap options
  --mirror|-m)         # Mirror which should be used for apt-get/aptitude
    shift; _opt_mirror="$1"
    ;;
  --release|-r)        # Release of new Debian system
    shift; _opt_release="$1"
    ;;
  --target|-t)         # Target partition (/dev/...) or directory
    shift; _opt_target="$1"
    ;;
  --vm)                # Virtual machine image (no file)
    _opt_vm="T"
    ;;
  --vmfile)            # Virtual machine file
    _opt_vmfile="T"
    ;;
  --vmsize)            # size of Virtual machine file
    shift; _opt_vmsize="$1"
    ;;
  --vmefi)            # Create an EFI boot partition for the VM
    _opt_vmefi="T"
    ;;
  --mntpoint|-p)       # Mountpoint used for mounting the target system
    shift; _opt_mntpoint="$1"
    ;;
  --debopt)            # Extra parameters passed to the debootstrap command
    shift; _opt_debopt="$1"
    ;;
  --filesystem)        # Filesystem that should be used
    shift; _opt_filesystem="$1" ; FILESYSTEM="${_opt_filesystem}"
    ;;
  --interactive)       # Use interactive mode (frontend)
    _opt_interactive=T
    ;;
  --nodebootstrap)     # Skip debootstrap, only do configuration to the target
    _opt_nodebootstrap=T
    ;;
  --nopackages)        # Skip installation of packages defined in /etc/debootstrap/packages
    _opt_nopackages=T
    ;;
  --arch)              # Target architecutre
    shift; _opt_arch="$1"
    ;;
  # just for backwards compatibility
  --insecure)
    _opt_insecure=T
    ;;
  #

  # == Configuration options
  --config|-c)         # Use specified configuration file, defaults to /etc/debootstrap
    shift; _opt_config="$1"
    ;;
  --confdir|-d)        # Place of config files for debootstrap, defaults to /etc/debootstrap
    shift; _opt_confdir="$1"
    ;;
  --packages)          # Install packages defined in specified file
    shift; _opt_packages="$1"
    _opt_packages_set=T
    ;;
  --debconf)           # Pre-seed packages using specified file
    shift; _opt_debconf="$1"
    _opt_debconf_set=T
    ;;
  --pre-scripts)       # Execute scripts from specified directory (before chroot-scripts).
    shift; _opt_pre_scripts="$1"
    _opt_pre_scripts_set=T
    ;;
  --scripts)           # Execute scripts from specified directory [NOTE: deprecated, replaced via --post-scripts]
    shift; _opt_scripts="$1"
    _opt_scripts_set=T
    ;;
  --post-scripts)       # Execute scripts from specified directory
    shift; _opt_post_scripts="$1"
    _opt_post_scripts_set=T
    ;;
  --chroot-scripts)   # Execute chroot scripts from specified directory
    shift; _opt_chroot_scripts="$1"
    _opt_chroot_scripts_set=T
    ;;
  --keep_src_list)     # Do not overwrite user provided apt sources.list
    _opt_keep_src_list=T
    ;;
  --hostname)          # Hostname of Debian system
    shift; _opt_hostname="$1"
    ;;
  --password)          # Use specified password as password for user root
    shift; _opt_password="$1"
    ;;
  --defaultinterfaces) # Install default /etc/network/interfaces
    _opt_defaultinterfaces=T
    ;;
  --nointerfaces)      # Skip installation of /etc/network/interfaces
    _opt_nointerfaces=T
    ;;
  --nokernel)          # Skip installation of default kernel images
    _opt_nokernel=T
    ;;
  --nopassword)        # Skip password dialog
    _opt_nopassword=T
    ;;
  --sshcopyid)         # Use locally available public keys to authorise root login on the target system
    _opt_sshcopyid=T
    ;;
  --sshcopyauth)       # Use .ssh/authorized_keys to authorise root login on the target system
    _opt_sshcopyauth=T
    ;;
  --grmlrepos)         # Enable Grml repository
    _opt_grmlrepos=T
    ;;
  --backportrepos)     # Enable Debian backports repository
    _opt_backportrepos=T
    ;;
  --bootappend)        # Add specified appendline to kernel whilst booting
    shift; _opt_bootappend="$1"
    ;;
  --grub)              # Target for grub installation. Use grub syntax for specifying
    shift; _opt_grub="$1"
    ;;
  --efi)               # Target for EFI boot installation
    shift; _opt_efi="$1"
    ;;
  --contrib)           # Add 'contrib' to list of components
    _opt_contrib=T
    ;;
  --non-free)          # Add 'non-free' to list of components
    _opt_non_free=T
    ;;
  --remove-configs)    # Drop config files from installed system
    _opt_remove_configs=T
    ;;

  # == Other options
  --verbose|-v)        # Increase verbosity
    if [ "$_opt_verbose" ]; then
      _opt_verbose=$( _opt_verbose + 1 )
    else
      _opt_verbose=1
    fi
    ;;
  --debug)             # Execute in debug mode
    _opt_debug=T
    ;;
  --help|-h)           # Print usage information and exit
    _opt_help=T
    ;;
  --version|-V)        # Show version information and exit
    _opt_version=T
    ;;
  --force)             # Do not prompt for user input
    _opt_force=T
    ;;
  --)
    shift; break
    ;;
  *)
    eerror "Internal getopt error!"; eend 1 ; exit 1
    ;;
  esac
  shift
done

# == business-logic of command line parameter-processing

# source configuration file in <confdir> if supplied. {{{
[ "$_opt_confdir" ] && {
  CONFFILES=$_opt_confdir
  einfo "Using config files under $CONFFILES/."
  if ! [ -r "$CONFFILES/config" ] ; then
    eerror "Error: config file $CONFFILES/config not found."; bailout 1
  fi
  # shellcheck disable=SC1091 source=config
  if ! . "$CONFFILES/config" ; then
    eerror "Error reading config file $CONFFILES/config" ; bailout 1
  fi
  # restore the command line parameter value
  CONFFILES=$_opt_confdir
}
# }}}

[ "$_opt_mirror" ]              && MIRROR=$_opt_mirror
[ "$_opt_release" ]             && RELEASE=$_opt_release
[ "$_opt_target" ]              && TARGET=$_opt_target
[ "$_opt_vm" ]                  && VIRTUAL=1
[ "$_opt_vmfile" ]              && VMFILE=1 && VIRTUAL=1
[ "$_opt_vmsize" ]              && VMSIZE=$_opt_vmsize
[ "$_opt_vmefi" ]               && VMEFI=1
[ "$_opt_mntpoint" ]            && MNTPOINT=$_opt_mntpoint
[ "$_opt_debopt" ]              && DEBOOTSTRAP_OPT=$_opt_debopt
[ "$_opt_interactive" ]         && INTERACTIVE=1
[ "$_opt_config" ]              && CONFIGFILE=$_opt_config
[ "$_opt_filesystem" ]          && MKFS="mkfs.$_opt_filesystem"
[ "$_opt_packages_set" ]        && PACKAGES='yes'
[ "$_opt_nopackages" ]          && PACKAGES=''
[ "$_opt_debconf_set" ]         && DEBCONF='yes'
[ "$_opt_post_scripts_set" ]    && POST_SCRIPTS='yes'
[ "$_opt_pre_scripts_set" ]     && PRE_SCRIPTS='yes'
[ "$_opt_chroot_scripts_set" ]  && CHROOT_SCRIPTS='yes'
[ "$_opt_keep_src_list" ]       && KEEP_SRC_LIST='yes'
[ "$_opt_grmlrepos" ]           && GRMLREPOS='yes'
[ "$_opt_backportrepos" ]       && BACKPORTREPOS='yes'
[ "$_opt_hostname" ]            && HOSTNAME=$_opt_hostname
[ "$_opt_password" ]            && ROOTPASSWORD=$_opt_password
[ "$_opt_nopassword" ]          && NOPASSWORD='yes'
[ "$_opt_defaultinterfaces" ]   && USE_DEFAULT_INTERFACES="true"
[ "$_opt_nointerfaces" ]        && NOINTERFACES="true"
[ "$_opt_nokernel" ]            && NOKERNEL="true"
[ "$_opt_sshcopyid" ]           && SSHCOPYID="true"
[ "$_opt_sshcopyauth" ]         && SSHCOPYAUTH="true"
[ "$_opt_bootappend" ]          && BOOT_APPEND=$_opt_bootappend
[ "$_opt_grub" ]                && GRUB=$_opt_grub
[ "$_opt_efi" ]                 && EFI=$_opt_efi
[ "$_opt_arch" ]                && ARCH=$_opt_arch
[ "$_opt_insecure" ]            && echo "Warning: --insecure is deprecated, continuing anyway."
[ "$_opt_force" ]               && FORCE=$_opt_force
[ "$_opt_verbose" ]             && VERBOSE="true"
[ "$_opt_debug" ]               && DEBUG="true"
[ "$_opt_remove_configs" ]      && REMOVE_CONFIGS="yes"

# make sure main is always included
[ -z "$COMPONENTS" ]            && COMPONENTS="main"
[ "$_opt_contrib" ]             && COMPONENTS="$COMPONENTS contrib"

case "${RELEASE}" in
  buster|bullseye)
    [ "$_opt_non_free" ] && COMPONENTS="$COMPONENTS non-free"
    ;;
  *)
    [ "$_opt_non_free" ] && COMPONENTS="$COMPONENTS non-free-firmware non-free"
    ;;
esac

# command line option checks
if [ "$_opt_scripts_set" ] ; then
  ewarn "Deprecation NOTE: --scripts option is deprecated, please switch to --post-scripts instead."
  SCRIPTS='yes' # deprecated since grml-debootstrap >=0.71
fi

if [ "$_opt_grub" ] && [ "$_opt_vmfile" ] ; then
  eerror "The --grub option is incompatible with --vmfile, please drop it from your command line."
  eerror "The --grub option is unneeded as GRUB will be installed automatically (unless GRUB_INSTALL='no')."
  bailout 1
fi

if [ "${_opt_sshcopyid}" ] && [ "${_opt_sshcopyauth}" ] ; then
  eerror "The --sshcopyid option is incompatible with --sshcopyauth, please drop either of them from your command line."
  bailout 1
fi

if [ -n "$DEBOOTSTRAP" ]; then
  ewarn "The DEBOOTSTRAP setting is deprecated and will be ignored. Please remove it from your configuration."
fi

if [ "$DEBUG" = "true" ] ; then
  set -x
fi

[ "$_opt_help" ] && {
  usage
  exit 0
}

[ "$_opt_version" ] && {
  einfo "$PN - version $VERSION"
  einfo "Report bugs via https://github.com/grml/grml-debootstrap/ or https://grml.org/bugs/"
  exit 0
}
# }}}

# check for root permissions {{{
if ! check4root ; then
   echo "For usage instructions please execute '$PN --help'."
   bailout 1
fi
# }}}

# make sure we have what we need {{{
check4progs mmdebstrap || bailout 1

if [ -n "$VIRTUAL" ] ; then
  check4progs kpartx parted qemu-img || bailout 1
fi
# }}}

# source specified configuration file {{{
if [ -n "$CONFIGFILE" ] ; then
  einfo "Reading specified config file $CONFIGFILE."
  bash -n "$CONFIGFILE"
  # shellcheck disable=SC1091 source=config
  if ! . "$CONFIGFILE" ; then
    eerror "Error reading config file $CONFIGFILE" ; bailout 1
  fi
fi
# }}}

# backwards compatibility checks {{{
if [ -n "$GROOT" ] ; then
   eerror "Error: you seem to have \$GROOT configured."
   eerror "This variable is no longer supported, please visit the"
   eerror "grml-debootstrap documentation for details."
   bailout 1
fi

if echo "$GRUB" | grep -q '^hd' ; then
   eerror "Error: this syntax for the grub configuration variable is no longer supported."
   eerror "Please do not use hd... any longer but /dev/sdX instead."
   bailout 1
fi
# }}}

# welcome screen {{{
welcome_dialog()
{
   dialog --title "$PN" --yesno "Welcome to the interactive configuration of ${PN}.
Do you want to continue installing Debian using this frontend?" 0 0 || bailout 0
}
# }}}

# ask for target {{{
prompt_for_target()
{
  AVAILABLE_PARTITIONS=$(LC_ALL=C fdisk -l 2>/dev/null | \
               sed 's/*//' | \
               grep -v 'Extended$' | \
               gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}'; ls /dev/md[0-9]* 2>/dev/null || true);

  if [ -z "$AVAILABLE_PARTITIONS" ] ; then
     dialog --title "$PN" --trim \
     --msgbox "Sorry, no partitions found. Please configure your
     harddisks (see /proc/partitions) using a tool like fdisk,
     cfdisk, gpart, gparted,..." 0 0 || bailout 1
  fi

  PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
                     fs="$(blkid -s TYPE -o value "$i" 2>/dev/null || true)"
                     [ -n "$fs" ] || fs='[no_filesystem_yet]'
                     echo "$i" "$fs"
                     unset fs
                   done)

  # shellcheck disable=SC2086
  TARGET=$(dialog --title "$PN" --single-quoted --stdout \
         --menu "Please select the target partition:" 0 0 0 \
         $PARTITION_LIST) || bailout 1
}
# }}}

# ask for bootmanager {{{
prompt_for_bootmanager()
{
  ADDITIONAL_PARAMS=""

  if echo "$TARGET" | grep -q "/dev/md" ; then
     MBRPART="all disks of Software RAID $TARGET"
  else
     # figure out whole disk device
     found=
     for device in /dev/disk/by-id/*
     do
        [ "$(readlink -f "$device")" = "${TARGET}" ] || continue
        found=1
        break
     done
     # shellcheck disable=SC2001
     [ -n "$found" ] && MBRDISK=$(echo "${device}" | sed -e 's/-part[0-9][0-9]*$//')
     if [ -e "$MBRDISK" ]; then
        MBRDISK=$(readlink -f "$MBRDISK")
     else
        # fall back to old behaviour
        # shellcheck disable=SC2001
        MBRDISK=$(echo "${TARGET}" | sed -e 's/[0-9][0-9]*$//')
     fi

     MBRPART="MBR of $MBRDISK"
  fi

  for device in cciss/c0d0 sda hda; do
    if [ "/dev/$device" != "${MBRDISK}" ]; then
      grep -q $device /proc/partitions && \
      ADDITIONAL_PARAMS="$ADDITIONAL_PARAMS:$device:install bootmanager grub into MBR of /dev/$device"
    fi
  done
  ADDITIONAL_PARAMS=${ADDITIONAL_PARAMS#:}

  OIFS="$IFS"; IFS=:

  # shellcheck disable=SC2086
  GETMBR=$(dialog --stdout --title "$PN" --default-item mbr \
          --menu "Where do you want to install the bootmanager grub?" 0 0 0 \
            mbr       "install bootmanager into $MBRPART" \
            nowhere   "do not install bootmanager at all" \
          ${ADDITIONAL_PARAMS}) || bailout 3
  IFS="$OIFS"

  case "$GETMBR" in
    mbr)
      # /dev/md0: has to be installed in MBR of /dev/md0 and not in /dev/md:
      if echo "$TARGET" | grep -q "/dev/md" ; then
        GRUB="$TARGET"
      else
        GRUB="$MBRDISK"
      fi
      ;;
    hda)
      GRUB="/dev/hda"
      ;;
    sda)
      GRUB="/dev/sda"
      ;;
    nowhere)
      GRUB=''
      ;;
  esac
}
# }}}

# ask for Debian release {{{
prompt_for_release()
{
  local default_value="$RELEASE"
  RELEASE="$(dialog --stdout --title "${PN}" --default-item "$default_value" --menu \
            "Please enter the Debian release you would like to use for installation:" \
            0 50 8 \
            buster   Debian/10 \
            bullseye Debian/11 \
            bookworm Debian/12 \
            trixie   Debian/13 \
            sid      Debian/unstable)" \
            || bailout
}
# }}}

# ask for hostname {{{
prompt_for_hostname()
{
  HOSTNAME="$(dialog --stdout --title "${PN}" --inputbox \
            "Please enter the hostname you would like to use for installation:" \
            0 0 "$HOSTNAME")" || bailout
}
# }}}

# ask for password {{{
prompt_for_password()
{
  if [ "$_opt_nopassword" ] ; then
    einfo "Skip asking for root password as requested."
    return 0
  fi

  ROOTPW1='PW1'
  ROOTPW2='PW2'
  while [ "$ROOTPW1" != "$ROOTPW2" ]; do
    ROOTPW1=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
    "Please enter the password for the root account:" 10 60) || bailout

    ROOTPW2=$(dialog --insecure --stdout --title "${PN}" --passwordbox \
    "Please enter the password for the root account again for \
    confirmation:" 10 60) || bailout

    if [ "$ROOTPW1" != "$ROOTPW2" ]; then
      dialog --stdout --title "${PN}" --ok-label \
        "Retry" --msgbox "Passwords do not match!" 10 60
    fi
  done
  ROOTPASSWORD="$ROOTPW1"
}
# }}}

# ask for Debian mirror {{{
prompt_for_mirror()
{
  [ -n "$MIRROR" ] || MIRROR='http://deb.debian.org/debian'
  MIRROR="$(dialog --stdout --title "${PN}" --inputbox \
            "Please enter Debian mirror you would like to use for installing packages." \
            0 0 "$MIRROR")" || bailout
}
# }}}

# software raid setup {{{
config_swraid_setup()
{
TMPFILE=$(mktemp)

# Currently we support only raid1:
RAIDLEVEL='raid1'

MD_LIST=$(for i in $(seq 0 9) ; do
            awk '{print $4}' /proc/partitions | grep -q "md$i" || \
            echo "/dev/md$i /dev/md$i"
          done)

# shellcheck disable=SC2086
TARGET=$(dialog --stdout --title "$PN" --default-item /dev/md0 \
--menu "Which device do you want to use for ${RAIDLEVEL}?

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 \
$MD_LIST) || bailout 20

AVAILABLE_PARTITIONS=$(LC_ALL=C fdisk -l 2>/dev/null | \
             sed 's/*//' | \
             grep -v 'Extended$' | \
             gawk -v num=0 -v ORS=' ' '/^\/dev\// {print $1}')
[ -n "$AVAILABLE_PARTITIONS" ] || echo "Fatal error: no partitions available?"
PARTITION_LIST=$(for i in $AVAILABLE_PARTITIONS ; do
                     echo "$i $(blkid -s TYPE -o value "$i" 2>/dev/null || echo '[no_filesystem_yet]') off"
                 done)

# shellcheck disable=SC2086
dialog --title "$PN" --separate-output \
       --checklist "Please select the partitions you would like to use for your $RAIDLEVEL on ${TARGET}:" 0 0 0 \
       $PARTITION_LIST 2>"$TMPFILE" || bailout

SELECTED_PARTITIONS="$(cat "$TMPFILE")"

NUM_PARTITIONS=0
while IFS= read -r i; do
  NUM_PARTITIONS=$(( NUM_PARTITIONS + 1 ))
done < "$TMPFILE"

ERRORFILE=$(mktemp)

local RC=0
# shellcheck disable=SC2086
yes | mdadm --create "${TARGET}" --level="${RAIDLEVEL}" \
      --raid-devices="${NUM_PARTITIONS}" ${SELECTED_PARTITIONS} >/dev/null 2>$ERRORFILE || RC=$?

if [ "$RC" = 0 ] ; then
   dialog --title "$PN" --msgbox \
   "Creating $TARGET was successful." 0 0
   rm -f "$TMPFILE" "$ERRORFILE"
else
   dialog --title "$PN" --msgbox \
   "There was an error setting up $TARGET:

$(cat "$ERRORFILE")

Exiting." 0 0
   rm -f "$TMPFILE" "$ERRORFILE"
   bailout 1
fi

}

prompt_for_swraid()
{
if dialog --stdout --title "$PN" \
          --defaultno --yesno "Do you want to configure Software RAID?

Please notice that only RAID level 1 is supported by ${PN} currently. Configuration will take place using mdadm." 0 0 ; then
  config_swraid_setup
fi
}
# }}}

# format efi partition {{{
format_efi_partition() {
  if [ -z "$EFI" ] ; then
    return 0
  fi

  if ! [ -b "$EFI" ] ; then
    eerror "Specified efi argument [$EFI] not a valid block device."
    bailout 1
  fi

  if fsck.vfat -bn "$EFI" >/dev/null; then
    einfo "EFI partition $EFI seems to have a FAT filesystem, not modifying."
  else
    einfo "EFI partition $EFI doesn't seem to be formatted, creating filesystem."
    if ! mkfs.fat -F32 -n "EFI" "$EFI" ; then
      eerror "Error while creating filesystem on ${EFI}."
      bailout 1
    fi
  fi
}
# }}}

# check for EFI support or try to enable it {{{
efi_support() {
  local efivars_loaded=false
  # this is for kernels versions before v3.10, which didn't provide efivarfs yet
  if modprobe efivars &>/dev/null ; then
    efivars_loaded=true
  fi
  # kernel versions v3.10 and newer usually provide efivarfs
  if modprobe efivarfs &>/dev/null ; then
    efivars_loaded=true
  fi

  if [ -d /sys/firmware/efi ] ; then
    einfo "EFI support detected."
    return 0
  fi

  if ! [ -d /sys/firmware/efi ] && [ "${efivars_loaded:-}" = "true" ] ; then
    einfo "EFI support detected, but system seems to be running in BIOS mode."
  fi

  # The user may have a legitimate reason to do an EFI installation on a BIOS
  # system (for instance if doing a hybrid-bootable installation), so don't
  # return 1 here.
}
# }}}

# make sure the user is aware of the used configuration {{{
checkconfiguration()
{

if [ -z "$VIRTUAL" ] ; then
  efi_support
  if [ -z "$_opt_efi" ] ; then
    ewarn "EFI support detected but no --efi option given, please consider enabling it."
  fi
fi

if [ -n "$INTERACTIVE" ] ; then

   INFOTEXT="Please recheck configuration before execution:
   "
   [ -n "$TARGET" ]  && INFOTEXT="$INFOTEXT
   Target:          $TARGET"
   [ -n "$GRUB" ]    && INFOTEXT="$INFOTEXT
   Install grub:    $GRUB"
   [ -n "$EFI" ]    && INFOTEXT="$INFOTEXT
   Install efi:     $EFI"
   [ -n "$RELEASE" ] && INFOTEXT="$INFOTEXT
   Using release:   $RELEASE"
   [ -n "$HOSTNAME" ] && INFOTEXT="$INFOTEXT
   Using hostname:  $HOSTNAME"
   [ -n "$MIRROR" ]  && INFOTEXT="$INFOTEXT
   Using mirror:    $MIRROR"
   [ -n "$ARCH" ]  && INFOTEXT="$INFOTEXT
   Using arch:      $ARCH"
   [ -n "$CONFFILES" ] && INFOTEXT="$INFOTEXT
   Config files:    $CONFFILES"

   INFOTEXT="$INFOTEXT

Is this ok for you? Notice: selecting 'No' will exit ${PN}."

   dialog --title "$PN" --no-collapse \
          --yesno "$INFOTEXT" 0 0 || bailout 0

else # if not running automatic installation display configuration and prompt for execution:
   einfo "$PN [${VERSION}] - Please recheck configuration before execution:"
   echo
   echo "   Target:          $TARGET"

   # do not display if MNTPOINT is the default one
   case "$MNTPOINT" in /mnt/debootstrap*) ;; *) echo "   Mount point:     $MNTPOINT" ;; esac

   if [ -n "$VIRTUAL" ] && [ "$GRUB_INSTALL" = 'yes' ] ; then
      echo "   Install grub:    yes"
      [ -n "$VMEFI" ]   && echo "   Install efi:     yes"   || echo "   Install efi:     no"
   else
     [ -n "$GRUB" ]     && echo "   Install grub:    $GRUB" || echo "   Install grub:    no"
     [ -n "$EFI" ]      && echo "   Install efi:     $EFI"  || echo "   Install efi:     no"
   fi

   [ -n "$RELEASE" ]   && echo "   Using release:   $RELEASE"
   [ -n "$HOSTNAME" ]  && echo "   Using hostname:  $HOSTNAME"
   [ -n "$MIRROR" ]    && echo "   Using mirror:    $MIRROR"
   [ -n "$ARCH" ]      && echo "   Using arch:      $ARCH"
   [ -n "$CONFFILES" ] && echo "   Config files:    $CONFFILES"
   if [ -n "$VIRTUAL" ] ; then
      echo "   Deploying as Virtual Machine."
      if [ -n "$VMSIZE" ] && [ -n "$VMFILE" ]; then
         echo "   Using Virtual Disk file with size of ${VMSIZE}."
      fi
   fi

   if [ ! -t 0 ] && [ -z "$ROOTPASSWORD" ] && [ -z "$NOPASSWORD" ] ; then
      echo
      echo "   You do not have a TTY allocated, your password will be shown in"
      echo "   plaintext on the terminal! If you are using SSH, try its -t option!"
   fi

   echo
   echo "   Important! Continuing will delete all data from ${TARGET}!"

   if [ -n "$FORCE" ] ; then
     einfo "Skip user acknowledgement as requested via --force option."
   else
     echo
     einfon "Is this ok for you? [y/N] "
     read -r a
     if ! [ "$a" = 'y' ] || [ "$a" = 'Y' ] ; then
        eerror "Exiting as requested."
        bailout 1
     fi
   fi
fi
}
# }}}

# interactive mode {{{
interactive_mode()
{
  check4progs dialog || bailout 1

  welcome_dialog

  prompt_for_release

  prompt_for_swraid

  prompt_for_target

  prompt_for_bootmanager

  prompt_for_hostname

  prompt_for_password

  prompt_for_mirror
}

# run interactive mode if we didn't get the according configuration yet
if [ -z "$TARGET" ] || [ -n "$INTERACTIVE" ] ; then
   # only target might be unset, so make sure the INTERACTIVE flag is set as well
   INTERACTIVE=1
   interactive_mode
fi
# }}}

# architecture setup {{{
if [ -n "$ARCH" ] ; then
   ARCHCMD="--arch $ARCH"
   ARCHINFO=" (${ARCH})"
else
   ARCH="$(dpkg --print-architecture)"
   ARCHCMD="--arch $ARCH"
   ARCHINFO=" (${ARCH})"
fi

if [ -z "${ARCH:-}" ] ; then
  eerror 'Architecture neither set (environment variable ARCH), nor could be automatically identified (using dpkg).'
  eerror 'Consider setting the --arch ... option.'
  bailout 1
fi
# }}}

# Only support certain architectures. {{{
if [[ "$ARCH" != "amd64" ]] && [[ "$ARCH" != "arm64" ]] ; then
  eerror "Unsupported architecture: ${ARCH}. Only amd64, arm64 are supported by grml-debootstrap."
  bailout 1
fi
# }}}

# Support for generic release codenames is unavailable. {{{
if [ "$RELEASE" = "stable" ] || [ "$RELEASE" = "testing" ] ; then
   eerror "Generic release codenames (stable, testing) are unsupported. \
Please use specific codenames such as bookworm or trixie."
   bailout 1
fi
# }}}

checkconfiguration

# finally make sure at least $TARGET is set [the partition for the new system] {{{
if [ -n "$TARGET" ] ; then
   SHORT_TARGET="${TARGET##*/}"
else
   eerror "Please adjust $CONFFILES/config or..."
   eerror "... use the interactive version for configuration before running ${0}"
   bailout 1
fi
# }}}

# stages setup {{{
if [ -z "$STAGES" ] ; then
   STAGES="/var/cache/grml-debootstrap/stages_${SHORT_TARGET}"
   [ -d "$STAGES" ] || mkdir -p "$STAGES"
fi

if [ -r "$STAGES"/grml-debootstrap ] ; then
   if grep -q 'done' "${STAGES}/grml-debootstrap" ; then
      eerror "Error: grml-debootstrap has been executed already, won't continue therefore."
      eerror "If you want to re-execute grml-debootstrap just manually remove ${STAGES}"
   fi
fi
# }}}

# partition handling {{{
PARTITION=''
DIRECTORY=''

set_target_directory(){
    # assume we are installing into a directory, don't run mkfs and grub related stuff therefore
    DIRECTORY=1
    MNTPOINT="$TARGET"
    MKFS=''
    TUNE2FS=''
    FSCK=''
    # make sure we normalise the path to an absolute directory name so something like:
    #  mkdir -p foo/a bar/a; (cd foo; grml-debootstrap -t a)&; (cd bar; grml-debootstrap -t a)&; wait
    # works
    TARGET="$(readlink -f "$TARGET")"
}

if [ -b "$TARGET" ] || [ -n "$VIRTUAL" ] ; then
    PARTITION=1
else
    # $TARGET was not detected as block device, but we do not want to create target directory in /dev/
    if [[ $TARGET == "/dev/"* ]]; then
      eerror "Error: Will not create target directory $TARGET in /dev."
      eerror "  Please check the partition(s) of the blockdevice."
      bailout 1
    fi
    set_target_directory
fi
# }}}

# create filesystem {{{
mkfs() {
  if [ -n "$DIRECTORY" ] ; then
     einfo "Running grml-debootstrap on a directory, skipping mkfs stage."
     return 0
  fi

  if grep -q "$TARGET" /proc/mounts ; then
    eerror "$TARGET already mounted, exiting to avoid possible damage. (Manually unmount $TARGET)"
    bailout 1
  fi

  # mkfs.ext* might prompt with "/dev/sdX# contains a ext* file system
  # created on ... Proceed anyway? (y,n)" which we want to skip in force mode
  if [ -n "$MKFS" ] && [ -n "$FORCE" ] ; then
    case "$MKFS" in
      mkfs.ext*)
        einfo "Enabling force option (-F) for mkfs.ext* tool as requested via --force switch."
        MKFS_OPTS="$MKFS_OPTS -F"
        ;;
    esac
  fi

  if [ -n "$MKFS" ] && [ "$MKFS" = "mkfs.ext4" ] ; then
    # Detect modern mkfs.ext4 features, and disable them if the kernel or fsck
    # on the target release will be too old to support them.
    local e2fsprogs_version
    e2fsprogs_version="$(dpkg-query --show --showformat='${Version}' e2fsprogs 2>/dev/null || echo 1.44)"

    local mkfs_supports_metadata_csum_seed=''
    if [ -n "$e2fsprogs_version" ] && dpkg --compare-versions "$e2fsprogs_version" ge '1.43' ; then
      mkfs_supports_metadata_csum_seed=1
    fi
    local mkfs_supports_orphan_file=''
    if [ -n "$e2fsprogs_version" ] && dpkg --compare-versions "$e2fsprogs_version" ge '1.47.0-1' ; then
      mkfs_supports_orphan_file=1
    fi

    case "$RELEASE" in
      bullseye|buster)
        if [ "$mkfs_supports_metadata_csum_seed" = 1 ]; then
          einfo "Disabling $MKFS feature as OS Release $RELEASE does not support it: metadata_csum_seed"
          MKFS_OPTS="$MKFS_OPTS -O ^metadata_csum_seed"
        fi
        if [ "$mkfs_supports_orphan_file" = 1 ]; then
          einfo "Disabling $MKFS feature as OS Release $RELEASE does not support it: orphan_file"
          MKFS_OPTS="$MKFS_OPTS -O ^orphan_file"
        fi
        ;;
    esac
  fi

  if [ -n "$MKFS" ] ; then
    einfo "Running $MKFS $MKFS_OPTS on $TARGET"
    # shellcheck disable=SC2086
    "$MKFS" $MKFS_OPTS "$TARGET"

    if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
      if ! echo "$MKFS" | grep -q "mkfs.ext" ; then
        eerror "Not changing disk uuid for $TARGET because $MKFS doesn't seem to match for ext{2,3,4} file system"
        bailout 1
      else
        einfo "Changing disk uuid for $TARGET to fixed (non-random) value $DISK_IDENTIFIER using tune2fs"
        tune2fs "$TARGET" -U "$DISK_IDENTIFIER" </dev/null
      fi
    fi

    if [ -n "$VIRTUAL" ] && [ -n "$EFI_TARGET" ]; then
      einfo "Creating FAT filesystem on $EFI_TARGET"
      mkfs.fat -F32 -n "EFI" "$EFI_TARGET"
    fi

    # make sure /dev/disk/by-uuid/... is up2date, otherwise grub
    # will fail to detect the uuid in the chroot
    if [ -n "$VIRTUAL" ] ; then
      einfo "Virtual environment doesn't require blockdev --rereadpt, skipping therefore"
    elif echo "$TARGET" | grep -q "/dev/md" ; then
      blockdev --rereadpt "${TARGET}"
    else
      # if we deploy to /dev/sdX# then let's see if /dev/sdX exists
      local main_device="${TARGET%%[0-9]*}"
      # sanity check to not try to e.g. access /dev/loop if we get /dev/loop0
      if ! [ -f "/sys/block/$(basename "${main_device}")/$(basename "${TARGET}")/dev" ] ; then
        einfo "No underlying block device for $TARGET identified, skipping blockdev --rereadpt."
      else
        udevadm settle
        # ensure we give blockdev up to 30 seconds/retries
        local timeout=30
        local success=0
        while [ "$timeout" -gt 0 ] ; do
          ((timeout--))
          if blockdev --rereadpt "${main_device}" ; then
            success=1
            break
          else
            ewarn "Failed to reread partition table of ${main_device} [${timeout} retries left]"
            sleep 1
          fi
        done

        if [ "${success}" = "0" ] ; then
          eerror "Error: failed to reread partition table, giving up."
          bailout 1
        fi
      fi
    fi
    # give the system 2 seconds, otherwise we might run into
    # race conditions :-/
    sleep 2

  fi
}
# }}}

# retrieve ID_FS_UUID {{{
identify_target_uuid() {
  local device="$1"

  if ! [ -b "$device" ] ; then
    return 1
  fi

  eval "$(blkid -o udev "$1" 2>/dev/null)"

  if [ -n "$ID_FS_UUID" ] ; then
    echo "$ID_FS_UUID"
  else
    return 1
  fi
}
# }}}

# identify TARGET_UUID {{{
mountpoint_to_blockdevice() {
  TARGET_UUID=''

  TARGET_UUID=$(identify_target_uuid "$TARGET" 2>/dev/null || true)
  if [ -n "$TARGET_UUID" ] ; then
    einfo "Identified UUID $TARGET_UUID for $TARGET"
    return 0
  fi

  # $TARGET might be a mountpoint and not a blockdevice, search for according entry
  for file in /sys/block/*/*/dev ; do
    if grep -q "^$(mountpoint -d "${TARGET}")$" "$file" ; then
      local dev
      dev="${file%/dev}"
      dev="/dev/${dev##*/}"
      TARGET_UUID=$(identify_target_uuid "$dev" 2>/dev/null || true)

      if [ -n "$TARGET_UUID" ] ; then
        einfo "Identified UUID $TARGET_UUID for $TARGET (via $file)"
        return 0
      fi
    fi
  done
}
# }}}

# modify filesystem settings {{{
tunefs() {
  if [ -n "$TUNE2FS" ] && echo "$MKFS" | grep -q "mkfs.ext" ; then
     einfo "Disabling automatic filesystem check on $TARGET via tune2fs"
     $TUNE2FS "$TARGET" </dev/null
  fi
}
# }}}

# mount the new partition or if it's a directory do nothing at all {{{
mount_target() {
  if [ -n "$DIRECTORY" ] ; then
     einfo "Running grml-debootstrap on a directory, nothing to mount."
  else
     if grep -q "$TARGET" /proc/mounts ; then
        ewarn "$TARGET already mounted, continuing anyway."
     else
       if ! [ -d "${MNTPOINT}" ] ; then
          [ -n "$VIRTUAL" ] || mkdir -p "${MNTPOINT}"
       fi
       einfo "Mounting $TARGET to $MNTPOINT"
       mkdir -p "$MNTPOINT"
       mount -o rw,suid,dev "$TARGET" "$MNTPOINT"
     fi
  fi
}
# }}}

# prepare VM image for usage with debootstrap {{{
prepare_vm() {
  if [ -z "$VIRTUAL" ] ; then
     return 0 # be quiet by intention
  fi

  if [ -b "$TARGET" ] && [ -n "$VMFILE" ] ; then
     eerror "Error: specified virtual disk target ($TARGET) is an existing block device."
     bailout 1
  fi
  if [ ! -b "$TARGET" ] && [ -z "$VMFILE" ] ; then
     eerror "Error: specified virtual disk target ($TARGET) does not exist yet."
     bailout 1
  fi

  # make sure loop module is present and a usable loop device exists
  modprobe loop || true
  if ! losetup -f >/dev/null 2>&1; then
    eerror "Error finding usable loop device"
    bailout 1
  fi

  # if dm-mod isn't available then kpartx will fail with
  # "Is device-mapper driver missing from kernel? [...]"
  modprobe dm-mod || true
  if ! grep -q 'device-mapper' /proc/misc >/dev/null 2>&1 ; then
    eerror "Device-mapper support missing in kernel."
    bailout 1
  fi

  ORIG_TARGET="$TARGET" # store for later reuse

  case "$ARCH" in
    i386|amd64) true;;
    arm64)      VMEFI=1;;
  esac

  if [ -n "$VMFILE" ]; then
    qemu-img create -f raw "${TARGET}" "${VMSIZE}"
  fi
  if [ -n "$VMEFI" ]; then
    parted -s "${TARGET}" 'mklabel gpt'
    parted -s "${TARGET}" 'mkpart ESP fat32 1MiB 101MiB'
    parted -s "${TARGET}" 'set 1 boot on'
    if [ "$ARCH" = 'arm64' ] || [ "$ARCH" = 'i386' ]; then
      # No need for a bios_grub parttion on ARM64 or i386
      parted -s "${TARGET}" 'mkpart primary ext4 101MiB 100%'
    else
      parted -s "${TARGET}" 'mkpart bios_grub 101MiB 102MiB'
      parted -s "${TARGET}" 'set 2 bios_grub on'
      parted -s "${TARGET}" 'mkpart primary ext4 102MiB 100%'
    fi
  else
    parted -s "${TARGET}" 'mklabel msdos'
    if [ "$FIXED_DISK_IDENTIFIERS" = "yes" ] ; then
      einfo "Adjusting disk signature to a fixed (non-random) value"
      MBRTMPFILE=$(mktemp)
      dd if="${TARGET}" of="${MBRTMPFILE}" bs=512 count=1
      echo -en "\\x41\\x41\\x41\\x41" | dd of="${MBRTMPFILE}" conv=notrunc seek=440 bs=1
      dd if="${MBRTMPFILE}" of="${TARGET}" conv=notrunc
    fi
    parted -s "${TARGET}" 'mkpart primary ext4 4MiB 100%'
    parted -s "${TARGET}" 'set 1 boot on'
  fi

  DEVINFO=$(kpartx -asv "$TARGET") # e.g. 'add map loop0p1 (254:5): 0 20477 linear 7:0 3' - will be multi-line for EFI VMs
  if [ -z "${DEVINFO}" ] ; then
    eerror "Error setting up loopback device."
    bailout 1
  fi

  # hopefully this always works as expected
  LOOP_PART="${DEVINFO##add map }" # 'loop0p1 (254:5): 0 20477 linear 7:0 3'
  LOOP_PART="${LOOP_PART// */}"    # 'loop0p1'
  if [ -n "$VMEFI" ]; then
    export EFI_TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop0p1'
    if [ "$ARCH" = 'arm64' ] || [ "$ARCH" = 'i386' ]; then
      LOOP_PART="${LOOP_PART%p1}p2"
    else
      LOOP_PART="${LOOP_PART%p1}p3"
    fi
  fi
  LOOP_DISK="${LOOP_PART%p*}"      # 'loop0'
  export TARGET="/dev/mapper/$LOOP_PART" # '/dev/mapper/loop0p1'

  if [ -z "$TARGET" ] ; then
     eerror "Error: target could not be set to according /dev/mapper/* device."
     bailout 1
  fi
}
# }}}

# make VM image bootable {{{
grub_install() {
  if [ -z "${VIRTUAL}" ] ; then
     return 0
  fi
  if [ "${GRUB_INSTALL}" != "yes" ] ; then
    einfo "Not installing GRUB as requested via \$GRUB_INSTALL=$GRUB_INSTALL"
    return 0
  fi

  if ! mount "${TARGET}" "${MNTPOINT}" ; then
    eerror "Error: Mounting ${TARGET} failed, can not continue."
    bailout 1
  fi

  mount -t proc none "${MNTPOINT}"/proc
  mount -t sysfs none "${MNTPOINT}"/sys
  mount -t devtmpfs udev "${MNTPOINT}"/dev
  mount -t devpts devpts "${MNTPOINT}"/dev/pts

  # Has chroot-script installed GRUB to MBR using grub-install (successfully), already?
  # chroot-script skips installation for unset ${GRUB}
  if [[ -z "${GRUB}" ]] || ! dd if="${GRUB}" bs=512 count=1 2>/dev/null | cat -v | grep -Fq GRUB; then
    einfo "Installing Grub as bootloader."

    local grub_pc_package_name=''

    # ARM64 uses EFI-only, and doesn't need a GRUB package. For i386, we only
    # install the BIOS bootloader if we're not using EFI (since grub-pc and
    # grub-efi-ia32 can't be co-installed). For amd64, we install grub-cloud
    # which will pull in grub-pc-bin, so we don't need to explicitly install a
    # BIOS bootloader for it when using EFI.
    if [ -z "$VMEFI" ]; then
      grub_pc_package_name='grub-pc'
    fi

    if [ -n "${grub_pc_package_name}" ]; then
      if ! clean_chroot "${MNTPOINT}" dpkg --list "${grub_pc_package_name}" 2>/dev/null | grep -q '^ii' ; then
        echo "Notice: ${grub_pc_package_name} package not present yet, installing it therefore."
        clean_chroot "$MNTPOINT" DEBIAN_FRONTEND=$DEBIAN_FRONTEND apt-get -y --no-install-recommends install $DPKG_OPTIONS "${grub_pc_package_name}"
      fi
    fi

    if [ -n "$VMEFI" ]; then
      mkdir -p "${MNTPOINT}"/boot/efi
      mount -t vfat "${EFI_TARGET}" "${MNTPOINT}"/boot/efi

      efi_id="$(
        if [ -f "${MNTPOINT}"/etc/default/grub ]; then
          source "${MNTPOINT}"/etc/default/grub
        fi
        for file in "${MNTPOINT}"/etc/default/grub.d/*.cfg; do
          if [ -f "${file}" ]; then
            source "${file}"
          fi
        done
        if [ "${GRUB_DISTRIBUTOR}" != "" ]; then
          echo "${GRUB_DISTRIBUTOR}"
        else
          echo 'Debian'
        fi
      )"

      if ! clean_chroot "${MNTPOINT}" dpkg --list shim-signed 2>/dev/null | grep -q '^ii' ; then
        echo "Notice: shim-signed package not present yet, installing it therefore."
        # shellcheck disable=SC2086
        clean_chroot "${MNTPOINT}" DEBIAN_FRONTEND=$DEBIAN_FRONTEND apt-get -y --no-install-recommends install $DPKG_OPTIONS shim-signed
      fi

      # The EFI bootloader will automatically be installed to the proper location when the
      # corresponding grub-efi-ARCH package is installed.
      if [ "${ARCH}" = "arm64" ]; then
        clean_chroot "$MNTPOINT" debconf-set-selections <<< 'grub-efi-arm64 grub2/force_efi_extra_removable boolean true'
        if ! clean_chroot "${MNTPOINT}" dpkg --list grub-efi-arm64-signed 2>/dev/null | grep -q '^ii' ; then
          echo "Notice: grub-efi-arm64-signed package not present yet, installing it therefore."
          # shellcheck disable=SC2086
          clean_chroot "$MNTPOINT" DEBIAN_FRONTEND=$DEBIAN_FRONTEND apt-get -y --no-install-recommends install $DPKG_OPTIONS grub-efi-arm64-signed grub-efi-arm64
        fi
        clean_chroot "$MNTPOINT" grub-install --target=arm64-efi --efi-directory=/boot/efi --uefi-secure-boot --bootloader-id="${efi_id}" --force-extra-removable "/dev/$LOOP_DISK"
      elif [ "${ARCH}" = "i386" ]; then
        clean_chroot "$MNTPOINT" debconf-set-selections <<< 'grub-efi-ia32 grub2/force_efi_extra_removable boolean true'
        if ! clean_chroot "${MNTPOINT}" dpkg --list grub-efi-ia32-signed 2>/dev/null | grep -q '^ii' ; then
          echo "Notice: grub-efi-ia32-signed package not present yet, installing it therefore."
          # shellcheck disable=SC2086
          clean_chroot "$MNTPOINT" DEBIAN_FRONTEND=$DEBIAN_FRONTEND apt-get -y --no-install-recommends install $DPKG_OPTIONS grub-efi-ia32-signed grub-efi-ia32
        fi
        clean_chroot "$MNTPOINT" grub-install --target=i386-efi --efi-directory=/boot/efi --uefi-secure-boot --bootloader-id="${efi_id}" --force-extra-removable "/dev/$LOOP_DISK"
      else
        if ! clean_chroot "${MNTPOINT}" dpkg --list grub-cloud-amd64 2>/dev/null | grep -q '^ii' ; then
          echo "Notice: grub-cloud-amd64 package not present yet, installing it therefore."
          # shellcheck disable=SC2086
          clean_chroot "$MNTPOINT" DEBIAN_FRONTEND=$DEBIAN_FRONTEND apt-get -y --no-install-recommends install $DPKG_OPTIONS grub-cloud-amd64
        fi
        # grub-cloud pulls in all the needed deps. We don't use it to install
        # GRUB initially, but we do need it to update GRUB, so we have to
        # touch /etc/grub.d/enable_cloud.
        mkdir -p "${MNTPOINT}"/etc/grub.d
        touch "${MNTPOINT}"/etc/grub.d/enable_cloud
        clean_chroot "$MNTPOINT" grub-install --target=x86_64-efi --efi-directory=/boot/efi --uefi-secure-boot --bootloader-id="${efi_id}" --force-extra-removable "/dev/$LOOP_DISK"
        clean_chroot "$MNTPOINT" grub-install --target=i386-pc "/dev/$LOOP_DISK"
      fi
    else
      clean_chroot "$MNTPOINT" grub-install --target=i386-pc "/dev/$LOOP_DISK"
    fi
  fi

  # workaround for Debian bug #918590 with lvm + udev:
  # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
  if [ -d /run/udev ] ; then
    einfo "Setting up bind-mount /run/udev"
    mkdir -p "${MNTPOINT}"/run/udev
    mount --bind /run/udev "${MNTPOINT}"/run/udev
  fi

  if [ -n "${BOOT_APPEND}" ] ; then
    echo "Adding BOOT_APPEND configuration ['${BOOT_APPEND}'] to /etc/default/grub."
    sed -i "/GRUB_CMDLINE_LINUX_DEFAULT/ s#\"\$# ${BOOT_APPEND}\"#" "${MNTPOINT}/etc/default/grub"
  fi

  einfo "Updating grub configuration file."
  clean_chroot "${MNTPOINT}" update-grub
  clean_chroot "${MNTPOINT}" sync

  if grep -q '^GRUB_DISABLE_LINUX_UUID=.*true' "${MNTPOINT}"/etc/default/grub 2>/dev/null ; then
    ewarn "GRUB_DISABLE_LINUX_UUID is set to true in /etc/default/grub, not adjusting root= in grub.cfg."
    ewarn "Please note that your system might NOT be able to properly boot."
  fi

  # workaround for Debian bug #918590 with lvm + udev:
  # WARNING: Device /dev/... not initialized in udev database even after waiting 10000000 microseconds
  try_umount 3 "${MNTPOINT}"/run/udev

  try_umount 3 "${MNTPOINT}"/proc
  try_umount 3 "${MNTPOINT}"/sys
  try_umount 3 "${MNTPOINT}"/dev/pts
  try_umount 3 "${MNTPOINT}"/dev

  try_umount 3 "${MNTPOINT}"/boot/efi

}
# }}}

# unmount VM image {{{
umount_target() {
  if [ -z "${VIRTUAL}" ] ; then
     return 0
  fi

  try_umount 3 "${MNTPOINT}"/boot/efi

  try_umount 3 "${MNTPOINT}"
  kpartx -d "${ORIG_TARGET}" >/dev/null
  # Workaround for a bug in kpartx which doesn't clean up properly,
  # see Debian Bug #891077 and Github-PR grml/grml-debootstrap#112
  if dmsetup ls | grep -q "^${LOOP_PART} "; then
    kpartx -d "/dev/${LOOP_DISK}" >/dev/null
  fi
}
# }}}

# install main chroot {{{
debootstrap_system() {
  if [ "$_opt_nodebootstrap" ]; then
     einfo "Skipping debootstrap as requested."
     return
  fi

  if grep -q "$MNTPOINT" /proc/mounts || [ -n "$DIRECTORY" ] ; then
    :
  else
    eerror "Error: $MNTPOINT not mounted, can not continue."
    eend 1 ; exit 1
  fi

  local bootstrap_include
  # Support https mirrors.
  bootstrap_include='--include=ca-certificates'

  einfo "Running mmdebstrap $DEBOOTSTRAP_OPT for release ${RELEASE}${ARCHINFO} using ${MIRROR}"
  einfo "Executing: mmdebstrap --skip=cleanup/apt --skip=check/empty $bootstrap_include $ARCHCMD $DEBOOTSTRAP_OPT $RELEASE $MNTPOINT $MIRROR"
  # shellcheck disable=SC2086
  mmdebstrap --skip=cleanup/apt --skip=check/empty "$bootstrap_include" $ARCHCMD $DEBOOTSTRAP_OPT "$RELEASE" "$MNTPOINT" "$MIRROR"
}
# }}}

# clean_chroot {{{
clean_chroot() {
  # inside the chroot system locales might not be available, so use minimum:
  local -a env_vars=(
    "LC_ALL=C"
    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  )

  # List of additional environment variables to include if set
  local -a additional_vars=("http_proxy" "https_proxy" "ALL_PROXY")

  # Loop through the additional environment variables and add them if set
  for var in "${additional_vars[@]}"; do
    if [[ -n "${!var}" ]]; then
      env_vars+=("$var=${!var}")
    fi
  done

  # Capture additional environment variables passed as arguments.
  for var in "$@"; do
    if [[ "$var" == *=* ]]; then
      env_vars+=("$var")
    else
      break
    fi
  done

  # First argument is the chroot directory.
  local chroot_dir="$1"

  # Remaining arguments are for the command to be executed in the chroot environment.
  local chroot_command=("${@:2}")

  # Run chroot, then env -i with the specified environment variables inside the chroot
  chroot "$chroot_dir" env -i "${env_vars[@]}" "${chroot_command[@]}"
}
# }}}

# prepare chroot via chroot-script {{{
preparechroot() {
  einfo "Preparing chroot system"

  # provide variables to chroot system
  CHROOT_VARIABLES="/var/cache/grml-debootstrap/variables_${SHORT_TARGET}"
  touch "$CHROOT_VARIABLES"
  chmod 600 "$CHROOT_VARIABLES" # make sure nobody except root can read it
  echo "# Configuration of ${PN}"                                                                                   > "$CHROOT_VARIABLES"
  [ -n "$ARCH" ]                      && echo "ARCH='${ARCH//\'/\'\\\'\'}'"                                         >> "$CHROOT_VARIABLES"
  [ -n "$BACKPORTREPOS" ]             && echo "BACKPORTREPOS='${BACKPORTREPOS//\'/\'\\\'\'}'"                       >> "$CHROOT_VARIABLES"
  [ -n "$BOOT_APPEND" ]               && echo "BOOT_APPEND='${BOOT_APPEND//\'/\'\\\'\'}'"                           >> "$CHROOT_VARIABLES"
  [ -n "$CHROOT_SCRIPTS" ]            && echo "CHROOT_SCRIPTS='${CHROOT_SCRIPTS//\'/\'\\\'\'}'"                     >> "$CHROOT_VARIABLES"
  [ -n "$COMPONENTS" ]                && echo "COMPONENTS='${COMPONENTS//\'/\'\\\'\'}'"                             >> "$CHROOT_VARIABLES"
  [ -n "$CONFFILES" ]                 && echo "CONFFILES='${CONFFILES//\'/\'\\\'\'}'"                               >> "$CHROOT_VARIABLES"
  [ -n "$DEBCONF" ]                   && echo "DEBCONF='${DEBCONF//\'/\'\\\'\'}'"                                   >> "$CHROOT_VARIABLES"
  [ -n "$DEBIAN_FRONTEND" ]           && echo "DEBIAN_FRONTEND='${DEBIAN_FRONTEND//\'/\'\\\'\'}'"                   >> "$CHROOT_VARIABLES"
  [ -n "$DEFAULT_LOCALES" ]           && echo "DEFAULT_LOCALES='${DEFAULT_LOCALES//\'/\'\\\'\'}'"                   >> "$CHROOT_VARIABLES"
  [ -n "$DEFAULT_LANGUAGE" ]          && echo "DEFAULT_LANGUAGE='${DEFAULT_LANGUAGE//\'/\'\\\'\'}'"                 >> "$CHROOT_VARIABLES"
  [ -n "$EXTRAPACKAGES" ]             && echo "EXTRAPACKAGES='${EXTRAPACKAGES//\'/\'\\\'\'}'"                       >> "$CHROOT_VARIABLES"
  [ -n "$EFI" ]                       && echo "EFI='${EFI//\'/\'\\\'\'}'"                                           >> "$CHROOT_VARIABLES"
  [ -n "$FALLBACK_MIRROR" ]           && echo "FALLBACK_MIRROR='${FALLBACK_MIRROR//\'/\'\\\'\'}'"                   >> "$CHROOT_VARIABLES"
  [ -n "$FILESYSTEM" ]                && echo "FILESYSTEM='${FILESYSTEM//\'/\'\\\'\'}'"                             >> "$CHROOT_VARIABLES"
  [ -n "$FORCE" ]                     && echo "FORCE='${FORCE//\'/\'\\\'\'}'"                                       >> "$CHROOT_VARIABLES"
  [ -n "$GRMLREPOS" ]                 && echo "GRMLREPOS='${GRMLREPOS//\'/\'\\\'\'}'"                               >> "$CHROOT_VARIABLES"
  [ -n "$GRUB" ]                      && echo "GRUB='${GRUB//\'/\'\\\'\'}'"                                         >> "$CHROOT_VARIABLES"
  [ -n "$HOSTNAME" ]                  && echo "HOSTNAME='${HOSTNAME//\'/\'\\\'\'}'"                                 >> "$CHROOT_VARIABLES"
  [ -n "$INITRD" ]                    && echo "INITRD='${INITRD//\'/\'\\\'\'}'"                                     >> "$CHROOT_VARIABLES"
  [ -n "$INITRD_GENERATOR" ]          && echo "INITRD_GENERATOR='${INITRD_GENERATOR//\'/\'\\\'\'}'"                 >> "$CHROOT_VARIABLES"
  [ -n "$INITRD_GENERATOR_OPTS" ]     && echo "INITRD_GENERATOR_OPTS='${INITRD_GENERATOR_OPTS//\'/\'\\\'\'}'"       >> "$CHROOT_VARIABLES"
  [ -n "$INSTALL_NOTES" ]             && echo "INSTALL_NOTES='${INSTALL_NOTES//\'/\'\\\'\'}'"                       >> "$CHROOT_VARIABLES"
  [ -n "$KEEP_SRC_LIST" ]             && echo "KEEP_SRC_LIST='${KEEP_SRC_LIST//\'/\'\\\'\'}'"                       >> "$CHROOT_VARIABLES"
  [ -n "$LOCALES" ]                   && echo "LOCALES='${LOCALES//\'/\'\\\'\'}'"                                   >> "$CHROOT_VARIABLES"
  [ -n "$MIRROR" ]                    && echo "MIRROR='${MIRROR//\'/\'\\\'\'}'"                                     >> "$CHROOT_VARIABLES"
  [ -n "$MKFS" ]                      && echo "MKFS='${MKFS//\'/\'\\\'\'}'"                                         >> "$CHROOT_VARIABLES"
  [ -n "$NOPASSWORD" ]                && echo "NOPASSWORD=\"true\""                                                 >> "$CHROOT_VARIABLES"
  [ -n "$NOKERNEL" ]                  && echo "NOKERNEL=\"true\""                                                   >> "$CHROOT_VARIABLES"
  [ -n "$PACKAGES" ]                  && echo "PACKAGES='${PACKAGES//\'/\'\\\'\'}'"                                 >> "$CHROOT_VARIABLES"
  [ -n "$POST_SCRIPTS" ]              && echo "POST_SCRIPTS='${POST_SCRIPTS//\'/\'\\\'\'}'"                         >> "$CHROOT_VARIABLES"
  [ -n "$PRE_SCRIPTS" ]               && echo "PRE_SCRIPTS='${PRE_SCRIPTS//\'/\'\\\'\'}'"                           >> "$CHROOT_VARIABLES"
  [ -n "$RECONFIGURE" ]               && echo "RECONFIGURE='${RECONFIGURE//\'/\'\\\'\'}'"                           >> "$CHROOT_VARIABLES"
  [ -n "$RELEASE" ]                   && echo "RELEASE='${RELEASE//\'/\'\\\'\'}'"                                   >> "$CHROOT_VARIABLES"
  [ -n "$RM_APTCACHE" ]               && echo "RM_APTCACHE='${RM_APTCACHE//\'/\'\\\'\'}'"                           >> "$CHROOT_VARIABLES"
  [ -n "$ROOTPASSWORD" ]              && echo "ROOTPASSWORD='${ROOTPASSWORD//\'/\'\\\'\'}'"                         >> "$CHROOT_VARIABLES"
  [ -n "$SCRIPTS" ]                   && echo "SCRIPTS='${SCRIPTS//\'/\'\\\'\'}'"                                   >> "$CHROOT_VARIABLES"
  [ -n "$SECURE" ]                    && echo "SECURE='${SECURE//\'/\'\\\'\'}'"                                     >> "$CHROOT_VARIABLES"
  [ -n "$SELECTED_PARTITIONS" ]       && echo "SELECTED_PARTITIONS='${SELECTED_PARTITIONS//\'/\'\\\'\'}'"           >> "$CHROOT_VARIABLES"
  [ -n "$TARGET" ]                    && echo "TARGET='${TARGET//\'/\'\\\'\'}'"                                     >> "$CHROOT_VARIABLES"
  [ -n "$UPGRADE_SYSTEM" ]            && echo "UPGRADE_SYSTEM='${UPGRADE_SYSTEM//\'/\'\\\'\'}'"                     >> "$CHROOT_VARIABLES"
  [ -n "$TARGET_UUID" ]               && echo "TARGET_UUID='${TARGET_UUID//\'/\'\\\'\'}'"                           >> "$CHROOT_VARIABLES"
  [ -n "$TIMEZONE" ]                  && echo "TIMEZONE='${TIMEZONE//\'/\'\\\'\'}'"                                 >> "$CHROOT_VARIABLES"
  [ -n "$TUNE2FS" ]                   && echo "TUNE2FS='${TUNE2FS//\'/\'\\\'\'}'"                                   >> "$CHROOT_VARIABLES"
  [ -n "$VMSIZE" ]                    && echo "VMSIZE='${VMSIZE//\'/\'\\\'\'}'"                                     >> "$CHROOT_VARIABLES"

  cp ${VERBOSE:+-v} "${CONFFILES}"/chroot-script "${MNTPOINT}"/bin/chroot-script
  chmod 755 "${MNTPOINT}"/bin/chroot-script
  [ -d "$MNTPOINT"/etc/debootstrap/ ] || mkdir "$MNTPOINT"/etc/debootstrap/

  # make sure we have our files for later use via chroot-script
  cp ${VERBOSE:+-v} "${CONFFILES}/config"     "${MNTPOINT}"/etc/debootstrap/
  # make sure we adjust the configuration variables accordingly:
  sed -i "s#RELEASE=.*#RELEASE=\"$RELEASE\"#" "${MNTPOINT}"/etc/debootstrap/config
  sed -i "s#TARGET=.*#TARGET=\"$TARGET\"#"    "${MNTPOINT}"/etc/debootstrap/config
  sed -i "s#GRUB=.*#GRUB=\"$GRUB\"#"          "${MNTPOINT}"/etc/debootstrap/config

  # install notes:
  if [ -n "$INSTALL_NOTES" ] ; then
     [ -r "$INSTALL_NOTES" ] && cp "$INSTALL_NOTES" "${MNTPOINT}"/etc/debootstrap/
  fi

  # package selection:
  if [ "$PACKAGES" = 'yes' ] ; then
    PACKAGES_FILE="packages"

    cp ${VERBOSE:+-v} "${_opt_packages:-$CONFFILES/$PACKAGES_FILE}" \
      "${MNTPOINT}/etc/debootstrap/${PACKAGES_FILE}"
  fi

  # debconf preseeding:
  _opt_debconf=${_opt_debconf:-$CONFFILES/debconf-selections}
  [ -f "${_opt_debconf}" ] && [ "$DEBCONF" = 'yes' ] && \
    cp ${VERBOSE:+-v} "${_opt_debconf}" "${MNTPOINT}"/etc/debootstrap/debconf-selections

  # copy scripts that should be executed inside the chroot:
  _opt_chroot_scripts=${_opt_chroot_scripts:-$CONFFILES/chroot-scripts/}
  [ -d "$_opt_chroot_scripts" ] && [ "$CHROOT_SCRIPTS" = 'yes' ] && {
    mkdir -p "${MNTPOINT}"/etc/debootstrap/chroot-scripts
    cp -a ${VERBOSE:+-v} "${_opt_chroot_scripts}"/* "${MNTPOINT}"/etc/debootstrap/chroot-scripts/
  }

  # notice: do NOT use $CHROOT_VARIABLES inside chroot but statically file instead!
  cp ${VERBOSE:+-v} "${CHROOT_VARIABLES}" "${MNTPOINT}"/etc/debootstrap/variables

  cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/extrapackages/ "${MNTPOINT}"/etc/debootstrap/

  # make sure we can access network [relevant for mmdebstrap]
  [ -f "${MNTPOINT}"/etc/resolv.conf ] || cp ${VERBOSE:+-v} /etc/resolv.conf "${MNTPOINT}"/etc/resolv.conf

  # setup default locales
  [ -n "$LOCALES" ] && cp ${VERBOSE:+-v} "${CONFFILES}"/locale.gen "${MNTPOINT}"/etc/locale.gen

  # copy any existing files to chroot
  [ -d "${CONFFILES}"/bin   ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/bin/*   "${MNTPOINT}"/bin/
  [ -d "${CONFFILES}"/boot  ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/boot/*  "${MNTPOINT}"/boot/
  [ -d "${CONFFILES}"/etc   ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/etc/*   "${MNTPOINT}"/etc/
  [ -d "${CONFFILES}"/sbin  ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/sbin/*  "${MNTPOINT}"/sbin/
  [ -d "${CONFFILES}"/share ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/share/* "${MNTPOINT}"/share/
  [ -d "${CONFFILES}"/usr   ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/usr/*   "${MNTPOINT}"/usr/
  [ -d "${CONFFILES}"/var   ] && cp ${VERBOSE:+-v} -a -L "${CONFFILES}"/var/*   "${MNTPOINT}"/var/

  # network setup
  DEFAULT_INTERFACES="# interfaces(5) file used by ifup(8) and ifdown(8)
# generated by grml-debootstrap.

# Include files from /etc/network/interfaces.d:
source /etc/network/interfaces.d/*

auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet dhcp
"

  # add dhcp setting for Predictable Network Interface Names
  if [ -x /bin/udevadm ]; then
    tmpfile=$(mktemp)
    for interface in /sys/class/net/*; do
      udevadm info --query=all --path="${interface}" > "${tmpfile}"
      # skip virtual devices, like bridges, vboxnet,...
      if grep -q 'P: /devices/virtual/net/' "${tmpfile}" ; then
        continue
      fi

      # iterate over possible naming policies by precedence (see udev/net/link-config.c),
      # use and stop on first match to have same behavior as udev's link_config_apply()
      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
        if grep -q "${property}" "${tmpfile}" ; then
          interface=$(grep "${property}" "${tmpfile}" | sed -n -e "s/E: ${property}=\([^\$*]\)/\1/p")
          DEFAULT_INTERFACES="${DEFAULT_INTERFACES}
allow-hotplug ${interface}
iface ${interface} inet dhcp
"
          break
        fi
      done
    done
    rm -f "${tmpfile}"
  fi

  if [ -n "$NOINTERFACES" ] ; then
    einfo "Not installing /etc/network/interfaces as requested via --nointerfaces option"
  elif [ -n "$USE_DEFAULT_INTERFACES" ] ; then
    einfo "Installing default /etc/network/interfaces as requested via --defaultinterfaces options."
    mkdir -p "${MNTPOINT}/etc/network"
    echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
  elif [ -n "$VIRTUAL" ] ; then
    einfo "Setting up Virtual Machine, installing default /etc/network/interfaces"
    mkdir -p "${MNTPOINT}/etc/network"
    echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
  elif [ -r /etc/network/interfaces ] ; then
    einfo "Copying /etc/network/interfaces from host to target system"
    mkdir -p "${MNTPOINT}/etc/network"
    cp ${VERBOSE:+-v} /etc/network/interfaces "${MNTPOINT}/etc/network/interfaces"
  else
    ewarn "Couldn't read /etc/network/interfaces, installing default /etc/network/interfaces"
    mkdir -p "${MNTPOINT}/etc/network"
    echo "$DEFAULT_INTERFACES" > "${MNTPOINT}/etc/network/interfaces"
  fi

  # install config file providing some example entries
  if [ -r /etc/network/interfaces.examples ] && [ ! -r "$MNTPOINT/etc/network/interfaces.examples" ] ; then
    mkdir -p "${MNTPOINT}/etc/network"
    cp /etc/network/interfaces.examples "$MNTPOINT/etc/network/interfaces.examples"
  fi

  if [ -n "${SSHCOPYID}" ] ; then
    AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-$HOME/.ssh/authorized_keys}
    AUTHORIZED_KEYS_TARGET=${AUTHORIZED_KEYS_TARGET:-$MNTPOINT/root/.ssh/}
    if ssh-add -L >/dev/null 2>&1 ; then
      einfo "Use locally available public keys to authorise root login on the target system as requested via --sshcopyid option."
      mkdir -p "${MNTPOINT}"/root/.ssh
      chmod 0700 "${MNTPOINT}"/root/.ssh
      if ! ssh-add -L >> "${MNTPOINT}"/root/.ssh/authorized_keys ; then
        eerror "Error: executing 'ssh-add -L' failed."
        bailout 1
      fi
    elif [ -f "$AUTHORIZED_KEYS_SOURCE" ]; then
      einfo "copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' as requested via --sshcopyid option."
      mkdir -p "$AUTHORIZED_KEYS_TARGET"
      chmod 0700 "$AUTHORIZED_KEYS_TARGET"
      if ! cp "$AUTHORIZED_KEYS_SOURCE" "$AUTHORIZED_KEYS_TARGET" ; then
        eerror "Error: copying '$AUTHORIZED_KEYS_SOURCE' to '$AUTHORIZED_KEYS_TARGET' failed"
        bailout 1
      fi
    else
      eerror "Error: Could not open a connection to your authentication agent or the agent has no identities."
      bailout 1
    fi
  fi

  if [ -n "${SSHCOPYAUTH}" ] ; then
    AUTHORIZED_KEYS_SOURCE=${AUTHORIZED_KEYS_SOURCE:-${HOME}/.ssh/authorized_keys}

    if ! [ -f "${AUTHORIZED_KEYS_SOURCE}" ]; then
      eerror "Error: could not read '${AUTHORIZED_KEYS_SOURCE}' for setting up SSH key login."
      bailout 1
    fi

    AUTHORIZED_KEYS_TARGET="${MNTPOINT}/root/.ssh/"
    einfo "Copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' as requested via --sshcopyauth option."
    mkdir -p "${AUTHORIZED_KEYS_TARGET}"
    chmod 0700 "${AUTHORIZED_KEYS_TARGET}"
    if ! cp "${AUTHORIZED_KEYS_SOURCE}" "${AUTHORIZED_KEYS_TARGET}" ; then
      eerror "Error: copying '${AUTHORIZED_KEYS_SOURCE}' to '${AUTHORIZED_KEYS_TARGET}' failed."
      bailout 1
    fi
  fi

  if [ -d /run/udev ] ; then
    einfo "Setting up bind-mount /run/udev"
    mkdir -p "${MNTPOINT}"/run/udev
    mount --bind /run/udev "${MNTPOINT}"/run/udev
  fi
}
# }}}

# execute all scripts in /etc/debootstrap/pre-scripts/ {{{
execute_pre_scripts() {
  # make sure hostname is set even before chroot-script get executed
  echo "$HOSTNAME" > "$MNTPOINT"/etc/hostname

  # make sure we have $MNTPOINT available for our scripts
  export MNTPOINT

  if [ -d "$_opt_pre_scripts" ] || [ "$PRE_SCRIPTS" = 'yes' ] ; then
    [ -d "$_opt_pre_scripts" ] && pre_scripts="$_opt_pre_scripts" || pre_scripts="${CONFFILES}/pre-scripts/"
    for script in "${pre_scripts}"/* ; do
      if [ -x "$script" ] ; then
        einfo "Executing pre-script $script"
        "$script"
      fi
    done
  fi
}
# }}}

# execute all scripts in /etc/debootstrap/post-scripts/ {{{
execute_post_scripts() {
  # make sure we have $MNTPOINT and HOSTNAME available for our scripts
  export MNTPOINT
  export TARGET_HOSTNAME=$HOSTNAME

  if [ -d "$_opt_scripts" ] || [ "$SCRIPTS" = 'yes' ] ; then
    # legacy support for /etc/debootstrap/scripts/
    [ -d "$_opt_scripts" ] && post_scripts="$_opt_scripts" || post_scripts="${CONFFILES}/scripts/"
    ewarn "Deprecation NOTE: --scripts/SCRIPTS are deprecated, please switch to --post-scripts/POST_SCRIPTS instead."
  elif [ -d "$_opt_post_scripts" ] || [ "$POST_SCRIPTS" = 'yes' ] ; then
    [ -d "$_opt_post_scripts" ] && post_scripts="$_opt_post_scripts" || post_scripts="${CONFFILES}/post-scripts/"
  fi

  if [ -n "$post_scripts" ] ; then
    for script in "${post_scripts}"/* ; do
      if [ -x "$script" ] ; then
        einfo "Executing post-script $script"
        "$script"
      fi
    done
  fi
}
# }}}

# execute chroot-script {{{
chrootscript() {
  if ! [ -r "$MNTPOINT/bin/chroot-script" ] ; then
    mount_target
  fi

  if ! [ -x "$MNTPOINT/bin/chroot-script" ] ; then
    eerror "Fatal: $MNTPOINT/bin/chroot-script could not be found."
    eend 1
  else
    einfo "Executing chroot-script now"
    mount -t devtmpfs udev "${MNTPOINT}"/dev
    mount -t devpts devpts "${MNTPOINT}"/dev/pts
    if [ "$DEBUG" = "true" ] ; then
      clean_chroot "$MNTPOINT" /bin/bash -x /bin/chroot-script
    else
      clean_chroot "$MNTPOINT" /bin/chroot-script
    fi
    try_umount 3 "$MNTPOINT"/dev/pts
    try_umount 3 "$MNTPOINT"/dev
  fi

  # finally get rid of chroot-script again, there's no good reason to
  # keep it on the installed system
  if grep -q GRML_CHROOT_SCRIPT_MARKER "${MNTPOINT}/bin/chroot-script" ; then
    einfo "Removing chroot-script again"
    rm -f "${MNTPOINT}/bin/chroot-script"
  else
    einfo "Keeping chroot-script as string GRML_CHROOT_SCRIPT_MARKER could not be found"
  fi
}
# }}}

# unmount $MNTPOINT {{{
umount_chroot() {

  # display installation notes:
  if [ -n "$INSTALL_NOTES" ] ; then
     [ -r "${MNTPOINT}/${INSTALL_NOTES}" ] && cat "${MNTPOINT}/${INSTALL_NOTES}"
  fi

  try_umount 3 "${MNTPOINT}"/run/udev

  if [ -n "$PARTITION" ] ; then
     try_umount 3 "$MNTPOINT"
  fi
}
# }}}

# execute filesystem check {{{
fscktool() {
 if [ -n "$VIRTUAL" ] ; then
   einfo "Skipping filesystem check because we deploy a virtual machine."
   return 0
 fi

 if [ "$FSCK" = 'yes' ] ; then
   [ -n "$FSCKTOOL" ] || FSCKTOOL="fsck.${MKFS#mkfs.}"
   einfo "Checking filesystem on $TARGET using $FSCKTOOL"
   "$FSCKTOOL" "$TARGET"
 fi
}
# }}}

# get rid of grml-debootstrap config files {{{
remove_configs() {
  if [ "$REMOVE_CONFIGS" != "yes" ] ; then
    return 0
  fi

  if ! mountpoint "${MNTPOINT}" >/dev/null 2>&1 ; then
    ewarn "Target ${MNTPOINT} doesn't seem to be mounted, can't remove configuration files."
    return 0
  fi

  einfo "Removing configuration files from installed system as requested via --remove-configs / REMOVE_CONFIGS."
  rm -rf "${MNTPOINT}"/etc/debootstrap/
}
# }}}

# now execute all the functions {{{
for i in format_efi_partition prepare_vm mkfs tunefs \
         mount_target mountpoint_to_blockdevice debootstrap_system \
         preparechroot execute_pre_scripts chrootscript execute_post_scripts \
         remove_configs umount_chroot grub_install umount_target fscktool ; do
    if stage "${i}" ; then
      "$i"
      stage "${i}" 'done'
      rm -f "${STAGES}/${i}"
    fi
done

cleanup
# }}}

einfo "Finished execution of ${PN}. Enjoy your Debian system."

## END OF FILE #################################################################
# vim: ai tw=100 expandtab foldmethod=marker shiftwidth=2
