#!/bin/bash

## Copyright (C) 2017 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## This script fixes the interaction between multiple tools.
##
## - `cowbuilder` hardcodes setting '--buildplace'.
##
## - `pbuilder` sets by default '--force-check-gpg'.
##   (This could also be sorted in `dist_build_pbuilder_config_file`.)
## - `pbuilder` `/usr/lib/pbuilder/pbuilder-createbuildenv` hardcodes calling `${DEBOOTSTRAP}`.
##
## - `mmdebstrap` does not support '--force-check-gpg'.
## - `mmdebstrap` requires the parameters in a certain order.
##
## - grml-debootstrap deprecated variables:
##   - '$DEBOOTSTRAP' (use of wrapper)
#    - '$DEBOOTSTRAP_OPTS' (adding additional options)
##   https://github.com/grml/grml-debootstrap/pull/309

set -x
set -e

true "${bold}INFO: Currently running: $0 (derivative-maker help-steps/mmdebstrap wrapper)${reset}"

args_original="$@"

path_variable_remove_help_steps() {
   local path_part path_array

   true "${bold}INFO: Old PATH: $PATH${reset}"
   ## Example PATH:
   ## /home/user/derivative-maker/help-steps:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

   IFS=':' read -ra path_array <<< "$PATH"

   new_path=""
   for path_part in "${path_array[@]}"; do
      if [[ "$path_part" != *"help-steps"* ]]; then
         new_path+="$path_part:"
      fi
   done

   ## Remove trailing colon.
   new_path="${new_path%:}"

   true "${bold}INFO: New PATH: $PATH${reset}"
   ## Example PATH:
   ## /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
}

path_variable_remove_help_steps
export PATH="$new_path"

## Example $@ when called by cowbuilder:
## --arch=amd64 --include=apt --variant=buildd --force-check-gpg trixie /var/cache/pbuilder/base.cow_amd64 http://HTTPS///deb.debian.org/debian

### }}}

## Sanity test.
[ -n "$APTGETOPT_SERIALIZED" ] || error "APTGETOPT_SERIALIZED is unset!"

## Debugging.
mapfile -t APTGETOPT <<< "$APTGETOPT_SERIALIZED"
printf "%s\n" "APTGETOPT: ${APTGETOPT[@]}"

## Debugging.
true "BUILDPLACE: $BUILDPLACE"
true "dist_grml_mount_point: $dist_grml_mount_point"
true "http_proxy: $http_proxy"
true "https_proxy: $https_proxy"
true "ALL_PROXY: $ALL_PROXY"
true "REPO_PROXY: ${REPO_PROXY}"
true "APPROX_PROXY_ENABLE: ${APPROX_PROXY_ENABLE}"
true "dist_build_target_arch: $dist_build_target_arch"
true "dist_build_multiarch_package_item: $dist_build_multiarch_package_item"
true "dist_build_apt_stable_release: $dist_build_apt_stable_release"
true "dist_build_apt_sources_mirror: $dist_build_apt_sources_mirror"
true "dist_aptgetopt_file: $dist_aptgetopt_file"
cat "$dist_aptgetopt_file"
true "dist_build_sources_list_primary: $dist_build_sources_list_primary"
cat -- "$dist_build_sources_list_primary"

## args_filtered is currently not required. Just keeping it for debugging
## purposes in applications such as grml-debootstrap, cowbuilder or pbuilder in
## the future set additional arguments.

args_filtered="$args_original"

true "INFO: filter out default mirror by cowbuilder or pbuilder (if we were not using --mirror)."
args_filtered="${args_filtered//"http://ftp.us.debian.org/debian"}"
args_filtered="${args_filtered//"https://ftp.us.debian.org/debian"}"

true "INFO: filter out default mirror by grml-debootstrap"
args_filtered="${args_filtered//"http://httpredir.debian.org/debian"}"
args_filtered="${args_filtered//"https://httpredir.debian.org/debian"}"
args_filtered="${args_filtered//"http://deb.debian.org/debian"}"
args_filtered="${args_filtered//"https://deb.debian.org/debian"}"

true "INFO: filter out --mirror"
args_filtered="${args_filtered//"$dist_build_apt_sources_mirror"}"

true "INFO: filter out variable BUILDPLACE (set by pbuilder) because we need to adjust the order of arguments."
args_filtered="${args_filtered//"$BUILDPLACE"}"

true "INFO: filter out --force-check-gpg (set by cowbuilder or pbuilder) since mmdebstrap does this by default and therefore does not support that command."
args_filtered="${args_filtered//"--force-check-gpg"}"

true "INFO: filter out --verbose (set by grml-debootstrap) since we add it by ourselves."
args_filtered="${args_filtered//"--verbose"}"

true "INFO: filter out --include=apt (set by cowbuilder or pbuilder) since we will use our own --include switch."
args_filtered="${args_filtered//"--include=apt"}"

true "INFO: Default to default --variant. Decide which packages are to be installed using --include."
args_filtered="${args_filtered//"--variant=buildd"}"

true "INFO: filter out '--arch amd64' since we will use our own."
args_filtered="${args_filtered//"--arch $dist_build_target_arch"}"
true "INFO: filter out '--arch=amd64' since we will use our own."
args_filtered="${args_filtered//"--arch=$dist_build_target_arch"}"

true "INFO: filter out suite since we will use our own."
args_filtered="${args_filtered//"$dist_build_apt_stable_release"}"

true "INFO: filter out --include (that grml-debootstrap sets) since we will use our own."
args_filtered="${args_filtered//"--include"}"

true "INFO: filter out sources list file (that grml-debootstrap sets) since we will use our own."
args_filtered="${args_filtered//"$dist_build_sources_list_primary"}"

true "INFO: filter out dist_build_apt_sources_mirror (that pbuilder sets) since we will use our own."
args_filtered="${args_filtered//"$dist_build_apt_sources_mirror"}"

true "INFO: filter out --skip=cleanup/apt (that grml-debootstrap sets) since deletion of APT package lists and cache is useful because later build steps set up different build sources."
args_filtered="${args_filtered//"--skip=cleanup/apt"}"

true "INFO: filter out --skip=check/empty (that grml-debootstrap sets) since we are not operating on empty folders."
args_filtered="${args_filtered//"--skip=check/empty"}"

## TODO: broken
#true "INFO: filter out extraneous white spaces."
#args_filtered="${args_filtered//" "}"

true "FINAL args_filtered: $args_filtered"
## example args_filtered:
## /mnt/debootstrap.15557

## mmdebstrap needs 3 positional arguments.
## suite buildplace path-to-sources-list
## For example when using grml-debootstrap:
## trixie /mnt/debootstrap.15557 /home/user/derivative-maker/build_sources/debian_stable_current_clearnet.sources
## For example when using cowbuilder:
## trixie /var/cache/pbuilder/base.cow_amd64 /home/user/derivative-maker/build_sources/debian_stable_current_clearnet.sources

## - locales:
##   XXX: Workaround for:
##   https://github.com/grml/grml-debootstrap/issues/48

if [ "$BUILDPLACE" = "" ]; then
   ## For grml-debootstrap.

   true "$0: Variable BUILDPLACE is unset."
   true "$0: This means this script was probably called by grml-debootstrap."
   true "$0: Setting BUILDPLACE to: $dist_grml_mount_point"
   BUILDPLACE="$dist_grml_mount_point"

   ## - zstd: for faster speed
   ##   grml-debootstrap default '/etc/debootstrap/packages' file contains 'zstd' but we are not using the 'packages' file.
   ##   https://github.com/grml/grml-debootstrap/issues/211
   ##
   ## - libpam-systemd
   ##   dracut requires libpam-systemd
   ##   https://github.com/grml/grml-debootstrap/issues/233
   ##
   ## - dracut-live
   ##   'dracut --add dmsquash-live' requires dracut-live
   include_opt="--include=eatmydata,apt-transport-tor,gpg,gpg-agent,fasttrack-archive-keyring,zstd,libpam-systemd,dracut-live"

   ## example:
   ## /home/user/derivative_dot/derivative-maker/help-steps/mmdebstrap --verbose --debug --format directory --variant=required --architectures=amd64 --aptopt=/home/user/derivative-binary/30_derivative-maker.conf --include=eatmydata,apt-transport-tor,gpg,gpg-agent,fasttrack-archive-keyring trixie /mnt/debootstrap.33132 /home/user/derivative-maker/build_sources/debian_stable_current_clearnet.sources
else
   ## For cowbuilder.

   true "$0: Variable BUILDPLACE is set."
   true "$0: This means this script was probably called by called by pbuilder which was called by cowbuilder."

   ## build dependencies
   include_opt="--include=apt,sudo,devscripts,debhelper,strip-nondeterminism,fakeroot,apt-transport-tor,eatmydata,aptitude,cowdancer,fasttrack-archive-keyring"

   ## example:
   ## /home/user/derivative-maker/help-steps/mmdebstrap --verbose --debug --format directory --variant=required --architectures=amd64 --aptopt=/home/user/derivative-binary/30_derivative-maker.conf --include=apt,sudo,devscripts,debhelper,strip-nondeterminism,fakeroot,apt-transport-tor,eatmydata,aptitude,cowdancer,fasttrack-archive-keyring trixie /var/cache/pbuilder/base.cow_amd64 /home/user/derivative-maker/build_sources/debian_stable_current_clearnet.sources
fi

## Sanity tests.
[ -n "$dist_build_apt_stable_release" ] || error "dist_build_apt_stable_release is unset!"
[ -n "$BUILDPLACE" ] || error "BUILDPLACE is unset!"
[ -n "$dist_build_sources_list_primary" ] || error "dist_build_sources_list_primary is unset!"
[ -n "$APTGETOPT" ] || error "APTGETOPT is unset!"

## '--variant=required' is only supported by 'mmdebstrap'. It might not be supported by 'debootstrap'.

#"$dist_source_help_steps_folder/mmdebstrap"

## Deletion of /etc/apt/apt.conf.d/99mmdebstrap is required for compatibility with live-boot (non-customized).
## This is because otherwise 99mmdebstrap results in not installing 'Recommends:' packages, which
## are actually a dependency for a fully functional ISO with functional login.

mmdebstrap \
   --verbose \
   --debug \
   --format directory \
   --variant=required \
   --architectures="$dist_build_multiarch_package_item" \
   --aptopt="$dist_aptgetopt_file" \
   --customize-hook='echo "mmdebstrap hooks START"' \
   --customize-hook='echo "----------"' \
   --customize-hook='ls -la "$1" || true' \
   --customize-hook='realpath "$1" || true' \
   --customize-hook='echo "----------"' \
   --customize-hook='cat "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources" || true' \
   --customize-hook='cat "$1/etc/apt/apt.conf.d/99mmdebstrap" || true' \
   --customize-hook='echo "----------"' \
   --customize-hook='rm --force --verbose "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources"' \
   --customize-hook='rm --force --verbose "$1/etc/apt/apt.conf.d/99mmdebstrap"' \
   --customize-hook='echo "----------"' \
   --customize-hook='echo "mmdebstrap hooks END"' \
   $include_opt \
   "$dist_build_apt_stable_release" \
   "$BUILDPLACE" \
   "$dist_build_sources_list_primary"

true "${bold}INFO: End of script: $0 (derivative-maker help-steps/mmdebstrap wrapper)${reset}"

## Example execution when cross-buidling ARM64 on AMD64:

## pbuilder:
## + mmdebstrap --verbose --debug --format directory --variant=required --architectures=amd64 --aptopt=/home/ansible/derivative-binary/30_derivative-maker.conf '--customize-hook=echo "mmdebstrap hooks START"' '--customize-hook=echo "----------"' '--customize-hook=ls -la "$1" || true' '--customize-hook=realpath "$1" || true' '--customize-hook=echo "----------"' '--customize-hook=cat "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources" || true' '--customize-hook=cat "$1/etc/apt/apt.conf.d/99mmdebstrap" || true' '--customize-hook=echo "----------"' '--customize-hook=rm --force --verbose "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources"' '--customize-hook=rm --force --verbose "$1/etc/apt/apt.conf.d/99mmdebstrap"' '--customize-hook=echo "----------"' '--customize-hook=echo "mmdebstrap hooks END"' --include=apt,sudo,devscripts,debhelper,strip-nondeterminism,fakeroot,apt-transport-tor,eatmydata,aptitude,cowdancer,fasttrack-archive-keyring trixie /var/cache/pbuilder/base.cow_amd64 /home/ansible/derivative-maker/build_sources/debian_stable_current_clearnet.sources

## grml-debootstrap v0.111:
## + mmdebstrap --verbose --debug --format directory --variant=required --architectures=arm64 --aptopt=/home/ansible/derivative-binary/30_derivative-maker.conf '--customize-hook=echo "mmdebstrap hooks START"' '--customize-hook=echo "----------"' '--customize-hook=ls -la "$1" || true' '--customize-hook=realpath "$1" || true' '--customize-hook=echo "----------"' '--customize-hook=cat "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources" || true' '--customize-hook=cat "$1/etc/apt/apt.conf.d/99mmdebstrap" || true' '--customize-hook=echo "----------"' '--customize-hook=rm --force --verbose "$1/etc/apt/sources.list.d/0000debian_stable_current_clearnet.sources"' '--customize-hook=rm --force --verbose "$1/etc/apt/apt.conf.d/99mmdebstrap"' '--customize-hook=echo "----------"' '--customize-hook=echo "mmdebstrap hooks END"' --include=eatmydata,apt-transport-tor,gpg,gpg-agent,fasttrack-archive-keyring,zstd,libpam-systemd,dracut-live trixie /mnt/derivative-maker-grml-debootstrap.49847 /home/ansible/derivative-maker/build_sources/debian_stable_current_clearnet.sources
