#!/bin/bash

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

## Static-analysis waiver: intentional word-splitting of $apt_unattended_opts
## (quoting would pass a single argument and break the apt call).
# shellcheck disable=SC2086

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

## colors is not available in the pbuilder chroot where this
## script runs, so plain (uncolored) log messages.
true "INFO: Currently running cowbuilder main chroot script."

## /usr/share/doc/pbuilder/examples/D10tmp
## https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=725434;msg=45
if [ -n "${TMP:-}" ]; then
   [ -d "$TMP" ] || mkdir -p -- "$TMP" || true
   chmod 1777 -- "$TMP" || true
fi
if [ -n "${TMPDIR:-}" ]; then
   [ -d "$TMPDIR" ] || mkdir -p -- "$TMPDIR" || true
   chmod 1777 -- "$TMPDIR" || true
fi

## Debugging.
cat -- "/home/$user_name/pbuilder_config_file"

source "/home/$user_name/pbuilder_config_file"

## help-steps/pre is not available in the pbuilder chroot, so define a minimal
## error handler and source just the standalone retry_run helper (copied in by
## *_cowbuilder-setup).
error() {
   printf '%s\n' "ERROR: $*" >&2
   exit 1
}
# shellcheck source=./retry-run
source "/home/$user_name/retry-run"

## Debugging.
true "apt_unattended_opts: $apt_unattended_opts"

mapfile -t DIST_APTGETOPT <<< "$DIST_APTGETOPT_SERIALIZED"
printf "%s\n" "DIST_APTGETOPT: ${DIST_APTGETOPT[*]}"

if [ "${dist_build_unsafe_io:-}" = "true" ]; then
  #if ! test -h /usr/lib/libeatmydata.so ; then
    #ln -s /usr/lib/x86_64-linux-gnu/libeatmydata.so /usr/lib/libeatmydata.so || true
  #fi
  ## Debugging.
  #ls -la /usr/lib/libeatmydata.so || true

  printf "%s\n" "force-unsafe-io" | tee -- "/etc/dpkg/dpkg.cfg.d/02apt-speedup" >/dev/null
  cat -- /etc/dpkg/dpkg.cfg.d/02apt-speedup
fi

## Debugging.
cat -- /etc/apt/sources.list.d/debian.sources || true

if test -f /var/lib/dpkg/available ; then
  true "INFO: /var/lib/dpkg/available exists."
else
  true "INFO: /var/lib/dpkg/available does not yet exist."
fi

## /var/lib/dpkg/available is missing after running mmdebstrap.
## aptitude does not like that.
## Leading to cowbuilder issue during make deb-pkg.
## Excerpt:
##
## Setting up pbuilder-satisfydepends-dummy (0.invalid.0) ...
## ++ chroot /var/cache/pbuilder/build/cow.6916 cow-shell env XDG_CACHE_HOME=/root aptitude -y --without-recommends -o APT::Install-Recommends=false -o Aptitude::ProblemResolver::StepScore=100 -o 'Aptitude::ProblemResolver::Hints::KeepDummy=reject pbuilder-satisfydepends-dummy :UNINST' -o Aptitude::ProblemResolver::Keep-All-Level=55000 -o Aptitude::ProblemResolver::Remove-Essential-Level=maximum install pbuilder-satisfydepends-dummy
## [ ERR] Writing extended state information
## [ ERR] Building tag database
## E: Failed to execute process to save dpkg selections, dpkg or trying to execute it exited with status/errno: 2
## E: failed to save selections to dpkg database
## E: pbuilder-satisfydepends failed
##
## The workaround is to run 'dpkg --clear-avail' followed by "apt-get update",
## which regenerates /var/lib/dpkg/available.
##
## No longer required in Debian bullseye.
#dpkg --clear-avail

## generate /var/lib/dpkg/available
## Inspired by Chris Gibson who pointed at /usr/lib/dpkg/methods/apt/update
## https://unix.stackexchange.com/users/162231/chris-gibson
## https://unix.stackexchange.com/a/271387/49297
#/usr/lib/dpkg/methods/apt/update /var/lib/dpkg apt apt

## Can be out-commented in Debian trixie.
## Required for usrmerge systemd unit files folder /usr/lib/system/system.
#debhelper_version="$(dpkg-query --show --showformat='${Version}' "debhelper")"
#if ! dpkg --compare-versions "$debhelper_version" ge "13.11.8~bpo12+1"; then
#  apt-get "${DIST_APTGETOPT[@]}" $apt_unattended_opts --yes --target-release=bookworm-backports install debhelper
#fi

retry_run --tries 4 --delay 15 -- apt-get "${DIST_APTGETOPT[@]}" $apt_unattended_opts --yes dist-upgrade

adduser --quiet --group --system --home "/home/$user_name" "$user_name"

true "INFO: End of script cowbuilder main chroot script."
