#!/bin/bash
# Filename:      /etc/debootstrap/chroot-script
# Purpose:       script executed in chroot when installing Debian via grml-debootstrap
# 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.
################################################################################
# GRML_CHROOT_SCRIPT_MARKER - do not remove this line unless you want to keep
# this script as /bin/chroot-script on your new installed system
################################################################################
# shellcheck disable=SC2317  # shellcheck has trouble understanding the code flow in this file

# 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"
   exit 1
}

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

bash -n /etc/debootstrap/config
# shellcheck source=config
. /etc/debootstrap/config    || exit 1
bash -n /etc/debootstrap/variables
# shellcheck source=tests/shellcheck-stub-debootstrap-variables
. /etc/debootstrap/variables || exit 1

[ -r /proc/1 ] || mount -t proc none /proc
[ -r /sys/kernel ] || mount -t sysfs none /sys

# variable checks {{{

# use aptitude only if it's available
if [ -x /usr/bin/aptitude ] ; then
   APTUPDATE="aptitude update $DPKG_OPTIONS"
   APTINSTALL="aptitude -y --without-recommends install $DPKG_OPTIONS"
   APTUPGRADE="aptitude -y safe-upgrade $DPKG_OPTIONS"
else
   APTINSTALL="apt-get -y --no-install-recommends install $DPKG_OPTIONS"
   APTUPDATE="apt-get update $DPKG_OPTIONS"
   APTUPGRADE="apt-get -y upgrade $DPKG_OPTIONS"
fi

if [ -z "$STAGES" ] ; then
   STAGES='/etc/debootstrap/stages'
   [ -d "$STAGES" ] || mkdir -p "$STAGES"
fi
# }}}

# helper functions {{{
stage() {
  if [ -n "$2" ] ; then
     echo "$2" > "$STAGES/$1"
     return 0
  elif grep -q 'done' "$STAGES/$1" 2>/dev/null ; then
     echo "   [*] Notice: stage $1 has been executed already, skipping execution therefore.">&2
     return 1
  fi
  echo "   Executing stage ${1}"
  return 0
}

askpass() {
  # read -s emulation for dash. result is in $resp.
  set -o noglob
  [ -t 0 ] && stty -echo
  read -r resp
  [ -t 0 ] && stty echo
  set +o noglob
}
# }}}

# mark existing packages as automatically installed {{{
markauto() {
  case "$RELEASE" in
    buster|bullseye)
      # apt-mark is unavailable or does not support all used patterns.
      return
      ;;
  esac

  # Mark most leaf packages as automatically installed.
  # Later in the systems life, apt autoremove will remove them if possible.
  apt-mark auto '~i !~M ?not(?priority(required)) ?not(?priority(important)) ?not(?priority(standard))'
}
# }}}

# define chroot mirror {{{
chrootmirror() {
  if [ "$KEEP_SRC_LIST" = "yes" ] ; then
    echo "KEEP_SRC_LIST has been enabled, skipping chrootmirror stage."
    return
  fi

  if [ -z "$COMPONENTS" ] ; then
    COMPONENTS='main'
  fi
  echo "Using repository components $COMPONENTS"

  if [ -n "$MIRROR" ] ; then
    echo "Adjusting sources.list for mirror (${MIRROR})."
    echo "deb $MIRROR $RELEASE $COMPONENTS" > /etc/apt/sources.list
  fi

  # add security.debian.org:
  case "$RELEASE" in
    unstable|sid) ;;  # no security pool available
    buster)
      echo "Adding security.debian.org to sources.list."
      echo "deb http://security.debian.org ${RELEASE}/updates $COMPONENTS" >> /etc/apt/sources.list
      ;;
    *)
      # bullseye and newer releases use a different repository layout, see
      # https://lists.debian.org/debian-devel-announce/2019/07/msg00004.html
      echo "Adding security.debian.org/debian-security to sources.list."
      echo "deb http://security.debian.org/debian-security ${RELEASE}-security $COMPONENTS" >> /etc/apt/sources.list
      ;;
  esac
}
# }}}

# remove local chroot mirror {{{
remove_chrootmirror() {
  if [ "$KEEP_SRC_LIST" = "yes" ] ; then
    echo "KEEP_SRC_LIST has been enabled, skipping remove_chrootmirror stage."
    return
  fi

  if [ -n "$MIRROR" ] && echo "$MIRROR" | grep -q 'file:' ; then
    echo "Removing local mirror (${MIRROR}) from sources.list."
    TMP_MIRROR="${MIRROR//\//\\\/}"
    sed -i "/deb $TMP_MIRROR $RELEASE $COMPONENTS/ D" /etc/apt/sources.list
    echo "Adding fallback mirror entry (${FALLBACK_MIRROR}) to sources.list instead."
    echo "deb $FALLBACK_MIRROR $RELEASE $COMPONENTS" >> /etc/apt/sources.list
  fi
}
# }}}

# set up grml repository {{{
grmlrepos() {
  if [ -z "$GRMLREPOS" ] ; then
    return 0
  fi

  # user might have provided their own apt sources configuration
  if [ -r /etc/apt/sources.list.d/grml.list ] ; then
    echo "File /etc/apt/sources.list.d/grml.list exists already, not modifying."
  else
    echo "Setting up /etc/apt/sources.list.d/grml.list."
    cat > /etc/apt/sources.list.d/grml.list << EOF
# grml: stable repository:
  deb     [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-stable main
  deb-src [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-stable main

# grml: testing/development repository:
  deb     [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-testing main
  deb-src [signed-by=/usr/share/keyrings/grml-archive-keyring.gpg] http://deb.grml.org/ grml-testing main
EOF
  fi

  # make sure we install packages from Grml's pool only if not available from Debian
  if [ -r /etc/apt/preferences.d/grml.pref ] ; then
    echo "File /etc/apt/preferences.d/grml.pref exists already, not modifying."
  else
    echo "Setting up /etc/apt/preferences.d/grml.pref."
    cat > /etc/apt/preferences.d/grml.pref << EOF
Explanation: use Grml repository only after Debian ones
Package: *
Pin: origin deb.grml.org
Pin-Priority: 100
EOF
  fi

  apt-get update -o Acquire::AllowInsecureRepositories=1
  apt-get -y --allow-unauthenticated install grml-keyring
  apt-get update

  if [ "$(dpkg-query -f "\${db:Status-Status} \${db:Status-Eflag}" -W grml-keyring 2>/dev/null)" != 'installed ok' ]; then
    echo "Error: installation of grml-keyring failed." >&2
    exit 1
  fi
}
# }}}

# feature to provide Debian backports repos {{{
backportrepos() {
  if [ -n "$BACKPORTREPOS" ] ; then
    cat >> /etc/apt/sources.list.d/backports.list << EOF
# debian backports: ${RELEASE}-backports repository:
deb     ${MIRROR} ${RELEASE}-backports main
deb-src ${MIRROR} ${RELEASE}-backports main
EOF
  fi
}
# }}}

# set up kernel-img.conf {{{
kernelimg_conf() {
  if ! [ -r /etc/kernel-img.conf ] ; then
     echo "Setting up /etc/kernel-img.conf"
     cat > /etc/kernel-img.conf << EOF
# Kernel Image management overrides
# See kernel-img.conf(5) for details
do_initrd = Yes
do_symlinks = Yes
EOF
  fi
}
# }}}

# make sure services do not start up {{{
install_policy_rcd() {
  if ! [ -r /usr/sbin/policy-rc.d ] ; then
     export POLICYRCD=1
     cat > /usr/sbin/policy-rc.d << EOF
#!/bin/sh
# Installed by grml-debootstrap chroot-script.
exit 101
EOF
     chmod 775 /usr/sbin/policy-rc.d
  fi
}
# }}}

# make sure we have an up2date system {{{
upgrade_system() {
  if [ "$UPGRADE_SYSTEM" = "yes" ] ; then
    echo "Running update + upgrade"
    $APTUPDATE
    DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTUPGRADE
  else
    echo "Not running update + upgrade as \$UPDATE_AND_UPGRADE is not set to 'yes'."
  fi
}

# }}}
# remove now useless apt cache {{{
remove_apt_cache() {
  if [ "$RM_APTCACHE" = 'yes' ] ; then
    echo "Cleaning apt cache."
    # shellcheck disable=SC2086
    apt-get clean $DPKG_OPTIONS
  else
    echo "Not cleaning apt cache as \$RM_APTCACHE is unset."
  fi
}
# }}}

# install additional packages {{{
packages() {
  # Pre-seed the debconf database with answers. Each question will be marked
  # as seen to prevent debconf from asking the question interactively.
  [ -f /etc/debootstrap/debconf-selections ] && {
    echo "Preseeding the debconf database, some lines might be skipped..."
    debconf-set-selections < /etc/debootstrap/debconf-selections
  }

  if [ "$PACKAGES" = 'yes' ] ; then
    PACKAGES_FILE="/etc/debootstrap/packages"

    if ! [ -r "${PACKAGES_FILE}" ] ; then
      echo "Error: ${PACKAGES_FILE} (inside chroot) not found, exiting." >&2
      exit 1
    else
      $APTUPDATE

      # shellcheck disable=SC2086,SC2046
      DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $(grep -v '^#' "${PACKAGES_FILE}") $GRMLPACKAGES
    fi
  fi
}
# }}}

# install extra packages {{{
extrapackages() {
    if [ "$EXTRAPACKAGES" = 'yes' ] ; then
        PACKAGELIST=$(find /etc/debootstrap/extrapackages -type f -name '*.deb')
        if [ -n "$PACKAGELIST" ]; then
            # shellcheck disable=SC2086
            dpkg -i $PACKAGELIST
            # run apt again to resolve any deps
            DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL
        fi
    fi
}
# }}}

# check if the specified Debian package exists
package_exists() {
  output=$(apt-cache show "$1" 2>/dev/null)
  [ -n "$output" ]
  return $?
}


# determine the kernel version postfix
get_kernel_version() {
  # do not override $KERNEL if set via config file
  if [ -n "$KERNEL" ] ; then
    echo "$KERNEL"
    return 0
  fi

  local kpackage
  local ksuffix
  ksuffix="${KPREFIX}$(dpkg --print-architecture)"
  kpackage=linux-image-"${ksuffix}"
  if package_exists "${kpackage}"; then
    echo "${ksuffix}"
    return 0
  fi

  echo "Automatically determined kernel package named ${kpackage} not found" >&2
  return 1
}

# install kernel packages {{{
kernel() {
  if [ -n "$NOKERNEL" ] ; then
    echo "Skipping installation of kernel packages as requested via --nokernel"
    return 0
  fi

  $APTUPDATE
  KVER=$(get_kernel_version)
  if [ -n "$KVER" ] ; then
     KERNELPACKAGES="linux-image-$KVER linux-headers-$KVER firmware-linux-free $INITRD_GENERATOR"
     # only add firmware-linux if we have non-free as a component
     if expr "$COMPONENTS" : '.*non-free' >/dev/null ; then
       KERNELPACKAGES="$KERNELPACKAGES firmware-linux"
     fi
     # shellcheck disable=SC2086
     DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL $KERNELPACKAGES
  else
     echo "Warning: Could not find a kernel for your system. Your system won't be able to boot itself!"
  fi
}
# }}}

# reconfigure packages {{{
reconfigure() {
  if [ -n "$RECONFIGURE" ] ; then
     for package in $RECONFIGURE ; do
         if dpkg --list "$package" >/dev/null 2>&1 | grep -q '^ii' ; then
           DEBIAN_FRONTEND=$DEBIAN_FRONTEND dpkg-reconfigure "$package" || \
           echo "Warning: $package does not exist, can not reconfigure it."
         fi
     done
  fi
}
# }}}

# set password of user root {{{
passwords()
{
  if [ -n "$NOPASSWORD" ] ; then
    echo "Skip setting root password as requested."
    return 0
  fi

  CHPASSWD_OPTION=
  if chpasswd --help 2>&1 | grep -q -- '-m,' ; then
     CHPASSWD_OPTION='-m'
  fi

  if [ -n "$ROOTPASSWORD" ] ; then
     # shellcheck disable=SC2086
     echo root:"$ROOTPASSWORD" | chpasswd $CHPASSWD_OPTION
     export ROOTPASSWORD=''
  else
    a='1'
    b='2'
     echo "Setting password for user root:"
     while [ "$a" != "$b" ] ; do
       printf "Enter new UNIX password for user root: "
       askpass
       a="$resp"
       unset resp
       echo
       printf "Retype new UNIX password for user root: "
       askpass
       b="$resp"
       unset resp
       echo
       if [ "$a" != "$b" ] ; then
         echo "Sorry, passwords do not match. Retry."
         a='1'
         b='2'
       else
         # shellcheck disable=SC2086
         echo root:"$a" | chpasswd $CHPASSWD_OPTION
         unset a
         unset b
       fi
     done
  fi
}
# }}}

# set up /etc/hosts {{{
hosts() {
  if ! [ -f /etc/hosts ] ; then
     cat > /etc/hosts << EOF
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
EOF
  fi
}
# }}}

# set default locales {{{
default_locales() {
  if [ -n "$DEFAULT_LOCALES" ] ; then
    if ! [ -x /usr/sbin/update-locale ] ; then
      echo "Warning: update-locale executable not available (no locales package installed?)"
      echo "Ignoring request to run update-locale for $DEFAULT_LOCALES therefore"
      return 0
    fi

    /usr/sbin/update-locale LANGUAGE="$DEFAULT_LANGUAGE" LANG="$DEFAULT_LOCALES"
  fi
}
# }}}

# adjust timezone {{{
timezone() {
  if [ -n "$TIMEZONE" ] ; then
    echo "Adjusting /etc/localtime"
    ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime

    if [ -e /etc/timezone ] ; then
      # not necessary for trixie or newer, see tzdata 2024b-6 changelog.
      # https://salsa.debian.org/glibc-team/tzdata/-/commit/c071fbc167ad306394b576879d515e6ecbe5a734
      echo "Setting /etc/timezone to $TIMEZONE"
      printf '%s\n' "$TIMEZONE"  > /etc/timezone
    fi
  fi
}
# }}}

# helper function for fstab() {{{
createfstab(){
  echo "Setting up /etc/fstab"
  cat > /etc/fstab <<EOF
# /etc/fstab - created by grml-debootstrap on $(date)
# Accessible filesystems, by reference, are maintained under '/dev/disk/'.
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
#
# After editing this file, run 'systemctl daemon-reload' to update systemd
# units generated from this file.
#
EOF

  if [ -n "$TARGET_UUID" ] ; then
    local rootfs_mount_options=""

    if [ -z "${FILESYSTEM}" ] ; then
      FILESYSTEM="$(blkid -o value -s TYPE /dev/disk/by-uuid/"${TARGET_UUID}")" || true
    fi

    case "${FILESYSTEM}" in
      # errors=remount-ro is supported only by a few file systems
      ext*|exfat|fat|jfs|nilfs2|vfat)
        rootfs_mount_options=",errors=remount-ro"
        ;;
    esac

    echo "/dev/disk/by-uuid/${TARGET_UUID} /  auto    defaults${rootfs_mount_options} 0   1" >> /etc/fstab
  else
    echo "Warning: couldn't identify target UUID for rootfs, your /etc/fstab might be incomplete."
  fi

if [ -n "$EFI" ] ; then
  UUID_EFI="$(blkid -o value -s UUID "$EFI")"
  echo "UUID=$UUID_EFI  /boot/efi       vfat    umask=0077      0       1" >> /etc/fstab
fi

cat >> /etc/fstab << EOF
proc           /proc        proc    defaults                      0   0
/dev/cdrom     /mnt/cdrom0  iso9660 ro,user,noauto                0   0
# some other examples:
# /dev/sda2       none         swap    sw,pri=0             0   0
# /dev/hda1       /Grml        ext3    dev,suid,user,noauto 0  2
# //1.2.3.4/pub   /smb/pub     cifs    user,noauto,uid=grml,gid=grml 0 0
# linux:/pub      /beer        nfs     defaults             0  0
# tmpfs           /tmp         tmpfs   size=300M            0  0
# /dev/sda5       none         swap    sw                   0  0
EOF
}
# }}}

# generate /etc/fstab {{{
fstab() {
  # set up /etc/fstab if file is UNCONFIGURED (debootstrap, mmdebstrap)
  if grep -q UNCONFIGURED /etc/fstab ; then
     createfstab
  fi
}
# }}}

# ensure we have according filesystem tools available {{{
install_fs_tools() {
  local pkg=""

  # note: this is supposed to be coming either via command lines'
  # $_opt_filesystem or via createfstab()
  case "${FILESYSTEM}" in
    jfs)
      pkg="jfsutils"
      ;;
    xfs)
      pkg="xfsprogs"
      ;;
  esac

  if [ -n "${pkg:-}" ] && ! dpkg --list "${pkg}" 2>/dev/null | grep -q '^ii' ; then
    echo "Filesystem package ${pkg} not present, installing now"
    DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL "${pkg}"
  fi
}
# }}}

# set up hostname {{{
hostname() {
  if [ -n "$HOSTNAME" ] ; then
     echo "Setting hostname to ${HOSTNAME}."
     echo "$HOSTNAME" > /etc/hostname

     # adjust postfix configuration
     if [ -r /etc/postfix/main.cf ] ; then
        # adjust hostname related options:
        sed -i "s/grml/$HOSTNAME/g" /etc/postfix/main.cf

        # listen on loopback interface only:
        sed -i "s/^inet_interfaces = .*/inet_interfaces = loopback-only/" /etc/postfix/main.cf
        grep -q inet_interfaces /etc/postfix/main.cf || echo 'inet_interfaces = loopback-only' >> /etc/postfix/main.cf
     fi
     if [ -r /etc/mailname ] ; then
        # adjust /etc/mailname
        local etc_mail_domain
        etc_mail_domain=$(/bin/dnsdomainname 2>/dev/null || echo localdomain)
        case "$HOSTNAME" in
          *.*)
            local mailname="$HOSTNAME"
            ;;
          *)
            local mailname="${HOSTNAME}.${etc_mail_domain}"
            ;;
        esac
        echo "Setting mailname to ${mailname}"
        echo "$mailname" > /etc/mailname
     fi
  fi
}
# }}}

# generate initrd/initramfs {{{
initrd() {
  # assume the first available kernel as our main kernel
  # shellcheck disable=SC2012
  KERNELIMG=$(ls -1 /boot/vmlinuz-* 2>/dev/null | head -1)
  if [ -z "$KERNELIMG" ] ; then
     echo 'No kernel image found, skipping initrd stuff.'>&2
     return
  fi

  KERNELVER=${KERNELIMG#/boot/vmlinuz-}

  # generate initrd
  if [ "$INITRD" = "yes" ] ; then
     echo "Generating initrd."
     if [ "$INITRD_GENERATOR" = 'dracut' ] ; then
         # shellcheck disable=SC2086
         dracut --no-hostonly --kver "$KERNELVER" --fstab --add-fstab /etc/fstab --force --reproducible $INITRD_GENERATOR_OPTS
     else
         # shellcheck disable=SC2086
         update-initramfs -c -t -k "$KERNELVER" $INITRD_GENERATOR_OPTS
     fi
  fi
}
# }}}

efi_setup() {
  if [ -z "$EFI" ] ; then
    return 0
  fi

  if ! dpkg --list efibootmgr 2>/dev/null | grep -q '^ii' ; then
    echo "Notice: efi option set but no efibootmgr package, installing it therefore."
    DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL efibootmgr
  fi

  mkdir -p /boot/efi
  echo "Mounting $EFI on /boot/efi"
  mount "$EFI" /boot/efi

  # if efivarfs kernel module is loaded, but efivars isn't,
  # then we need to mount efivarfs for efibootmgr usage
  if ! ls /sys/firmware/efi/efivars/* &>/dev/null ; then
    echo "Mounting efivarfs on /sys/firmware/efi/efivars"
    mount -t efivarfs efivarfs /sys/firmware/efi/efivars || true
  fi

  echo "Invoking efibootmgr"
  efibootmgr || true
}

# grub configuration/installation {{{

# helper function to get relevant /dev/disk/by-id/* entries,
# based on GRUB's postinst script
available_ids() {
  local path ids

  [ -d /dev/disk/by-id ] || return
  ids="$(
    for path in /dev/disk/by-id/*; do
      [ -e "${path}" ] || continue
      printf '%s %s\n' "${path}" "$(readlink -f "${path}")"
    done | sort -k2 -s -u | cut -d' ' -f1
  )"
  echo "${ids}"
}

# helper function to report corresponding /dev/disk/by-id/ for a given device name,
# based on GRUB's postinst script
device_to_id() {
  local id

  for id in $(available_ids); do
    if [ "$(readlink -f "${id}")" = "$(readlink -f "$1")" ]; then
      echo "${id}"
      return 0
    fi
  done

  # Fall back to the plain device name if there's no by-id link for it.
  if [ -e "$1" ]; then
    echo "$1"
    return 0
  fi

  echo "ERROR: Device '$1' does not exist!"
  return 1
}

is_grub_bios_compatible() {
  # Check if the disk uses an MSDOS partition table, these are always compatible
  if [[ "$(blkid "$GRUB")" =~ 'PTTYPE="dos"' ]]; then
    return 0
  # Look for a BIOS boot partition otherwise
  else
    SEARCH_STR="$GRUB"
    if [[ "$SEARCH_STR" =~ ^/dev/loop ]]; then
      SEARCH_STR="${SEARCH_STR//\/dev\//}" # loopX
      SEARCH_STR="/dev/mapper/${SEARCH_STR}" # /dev/mapper/loopX
      # Note that /dev/mapper/loopX won't actually exist, but
      # /dev/mapper/loopXpY will, so this works for the regex check in the
      # while loop below.
    fi
    while read -r line; do
      if [[ "$line" =~ ^${SEARCH_STR}.*21686148-6449-6e6f-744e-656564454649$ ]]; then
        return 0
      fi
    done < <(lsblk -pnlo NAME,PARTTYPE)
  fi
  return 1
}

run_grub_install() {
  grub_install_cmd=( 'grub-install' "$@" )
  if ! "${grub_install_cmd[@]}" ; then
    echo "Error: failed to execute '${grub_install_cmd[*]}'." >&2
    exit 1
  fi
}

grub_install() {
  if [ -z "$GRUB" ] ; then
    echo "Notice: \$GRUB not defined, will not install grub inside chroot at this stage."
    return 0
  fi
  MAIN_GRUB_PACKAGE=""
  GRUB_SECBOOT_PACKAGES=()

  case "$ARCH" in
    amd64)
      if is_grub_bios_compatible && [ -n "$EFI" ]; then
        MAIN_GRUB_PACKAGE="grub-cloud-amd64"
        GRUB_SECBOOT_PACKAGES=( "grub-efi-amd64-signed" "shim-signed" )
      elif [ -n "$EFI" ]; then
        MAIN_GRUB_PACKAGE="grub-efi-amd64"
        GRUB_SECBOOT_PACKAGES=( "grub-efi-amd64-signed" "shim-signed" )
      else
        MAIN_GRUB_PACKAGE="grub-pc"
      fi
      ;;
    arm64)
      if [ -n "$EFI" ]; then
        MAIN_GRUB_PACKAGE="grub-efi-arm64"
        GRUB_SECBOOT_PACKAGES=( "grub-efi-arm64-signed" "shim-signed" )
      fi
      ;;
  esac

  if [ -z "$MAIN_GRUB_PACKAGE" ]; then
    echo "Notice: No applicable bootloaders found, will not install grub inside chroot at this stage."
    return 0
  fi

  efi_setup

  # make sure this is pre-defined so we have sane settings for automated
  # upgrades, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=711019
  local grub_device
  grub_device=$(device_to_id "${GRUB}")
  if [ -z "${grub_device:-}" ] ; then
     echo "Warning: Could not identify /dev/disk/by-id/... for '${GRUB}', falling back to '${GRUB}'"
     grub_device="${GRUB}"
  fi

  echo "Setting grub debconf configuration for install device to $GRUB"
  if [ -n "$MAIN_GRUB_PACKAGE" ]; then
    echo "${MAIN_GRUB_PACKAGE} ${MAIN_GRUB_PACKAGE}/install_devices multiselect ${grub_device}" | debconf-set-selections
  fi

  echo "Installing automatically-determined grub packages ${MAIN_GRUB_PACKAGE}" "${GRUB_SECBOOT_PACKAGES[@]}"
  DEBIAN_FRONTEND=$DEBIAN_FRONTEND $APTINSTALL "${MAIN_GRUB_PACKAGE}" "${GRUB_SECBOOT_PACKAGES[@]}"

  if ! [ -x "$(command -v grub-install)" ] ; then
     echo "Error: grub-install not available. (Error while installing grub package?)" >&2
     return 1
  fi
  if ! [ -x "$(command -v update-grub)" ] ; then
     echo "Error: update-grub not available. (Error while installing grub package?)" >&2
     return 1
  fi

  local grub_targets=""
  if [ -n "$SELECTED_PARTITIONS" ]; then
    # sw-raid
    local device
    for device in $SELECTED_PARTITIONS ; do
      local grub_target="${device%%[0-9]}"
      grub_targets="${grub_targets} ${grub_target}"
    done
  else
    grub_targets="${GRUB}"
  fi

  local device
  for device in $grub_targets ; do
     echo "Installing grub on ${device}:"
     if [ -n "$EFI" ]; then
       case "${ARCH}" in
         amd64) run_grub_install --no-floppy --target=x86_64-efi --force-extra-removable "${device}";;
         arm64) run_grub_install --no-floppy --target=arm64-efi --force-extra-removable "${device}";;
       esac
     fi
     if [ "$MAIN_GRUB_PACKAGE" = 'grub-cloud-amd64' ] || [ -z "$EFI" ]; then
       run_grub_install --no-floppy --target=i386-pc "${device}"
     fi
  done
  rm -f /boot/grub/device.map  # avoid confusion with sw-raid

  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}\"#" /etc/default/grub
  fi

  # create (/update) grub configuration
  if ! update-grub ; then
    echo "Error: update-grub failed." >&2
    return 1
  fi

  if mountpoint -q /boot/efi ; then
    umount /boot/efi
  fi

  return 0
}
# }}}

# execute all scripts present in /etc/debootstrap/chroot-scripts/ {{{
custom_scripts() {
  [ -d /etc/debootstrap/chroot-scripts/ ] || return 0

  for script in /etc/debootstrap/chroot-scripts/* ; do
      echo "Executing script $script"
      $script && echo "done" || echo "failed"
  done
}
# }}}

# make sure we don't have any running processes left {{{
services() {
  for service in ssh mdadm mdadm-raid ; do
    if [ -x /etc/init.d/"$service" ] ; then
       /etc/init.d/"$service" stop || true
    fi
  done
}
# }}}

# unmount /proc and make sure nothing is left {{{
finalize() {
  # make sure we don't leave any sensible data
  rm -f /etc/debootstrap/variables

  [ -n "$POLICYRCD" ] && rm -f /usr/sbin/policy-rc.d

  umount /sys/firmware/efi/efivars &>/dev/null || true

  umount /sys >/dev/null 2>/dev/null || true
  umount /proc >/dev/null 2>/dev/null || true
}
# }}}

# signal handler {{{
signal_handler() {
  finalize
  [ -n "$1" ] && EXIT="$1" || EXIT="1"
  exit "$EXIT"
}
# }}}

# set signal handler {{{
trap signal_handler HUP INT QUIT TERM
# }}}

# execute the functions {{{

 # always execute install_policy_rcd
 install_policy_rcd

 for i in markauto chrootmirror grmlrepos backportrepos kernelimg_conf \
     kernel packages extrapackages reconfigure hosts \
     default_locales timezone fstab install_fs_tools hostname \
     initrd grub_install passwords \
     custom_scripts upgrade_system remove_apt_cache services \
     remove_chrootmirror; do
     if stage "$i" ; then
       "$i"
       stage "$i" 'done'
     fi
  done
  # always execute the finalize stage:
  finalize
# }}}

# finally exit the chroot {{{
  echo "Finished chroot installation, exiting."
  exit 0
# }}}

## END OF FILE #################################################################
# vim: ai tw=80 expandtab foldmethod=marker
