#!/bin/bash

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

## AI-Assisted

## style-ok: no-tmp-hardcode -- '/tmp/' in a regex that detects hardcoded /tmp.

## Canonicalize a debconf config.dat so the file is byte-identical regardless of
## the build environment. Two build-environment-noise sources are normalized:
## question 'Owners:' package lists (below) and transient mktemp paths recorded
## as substitution variables (see NEW = /tmp/... normalization further down).

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
export LC_ALL=C

# shellcheck source=../../../helper-scripts/usr/libexec/helper-scripts/log_run_die.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/log_run_die.sh

if [ "$#" -ne 1 ]; then
   die 2 "usage: ${0##*/} <config.dat>"
fi

config_dat="$1"
if [ ! -f "${config_dat}" ]; then
   die 2 "not a file: ${config_dat}"
fi

## Write the transformed content to a temp file in the same directory, then
## rename it over the original.
tmp_out="$( mktemp -- "${config_dat}.normalize.XXXXXX" )"
# shellcheck disable=SC2317  # reached only via the EXIT trap
cleanup() {
   ## Only lingers if the rename below did not happen (error path).
   safe-rm --force -- "${tmp_out}" 2>/dev/null
}
trap cleanup EXIT

## ucf records the temp copy it diffed a conffile against under "NEW"
## substitution variables in config.dat, each one on its own continuation line,
## e.g. " NEW = /tmp/grub.JI3HRI56IT".
new_key_regex='^([[:space:]]+NEW = /tmp/[^[:space:]]+)\.[A-Za-z0-9]{6,}([[:space:]]*)$'

while IFS= read -r line || [ -n "${line}" ]; do
   case "${line}" in
      "Owners: "*)
         ## Strip the ':arch' qualifier from every owner and de-duplicate,
         ## preserving first-seen order. Owners are ", "-separated package names,
         ## so a space-delimited seen-set membership test is unambiguous.
         owners_rest="${line#Owners: }"
         normalized_owners=""
         owner_seen=" "
         while [ -n "${owners_rest}" ]; do
            case "${owners_rest}" in
               *", "*)
                  owner="${owners_rest%%, *}"
                  owners_rest="${owners_rest#*, }"
                  ;;
               *)
                  owner="${owners_rest}"
                  owners_rest=""
                  ;;
            esac
            owner="${owner%%:*}"
            [ -n "${owner}" ] || continue
            case "${owner_seen}" in
               *" ${owner} "*)
                  continue
                  ;;
            esac
            owner_seen="${owner_seen}${owner} "
            if [ -z "${normalized_owners}" ]; then
               normalized_owners="${owner}"
            else
               normalized_owners="${normalized_owners}, ${owner}"
            fi
         done
         printf '%s\n' "Owners: ${normalized_owners}"
         ;;
      *)
         if [[ "${line}" =~ ${new_key_regex} ]]; then
            printf '%s\n' "${BASH_REMATCH[1]}.XXXXXX${BASH_REMATCH[2]}"
         else
            printf '%s\n' "${line}"
         fi
         ;;
   esac
done < "${config_dat}" > "${tmp_out}"

chmod --reference="${config_dat}" -- "${tmp_out}"
chown --reference="${config_dat}" -- "${tmp_out}"
mv -- "${tmp_out}" "${config_dat}"
exit 0
