#!/bin/bash

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

if [ -f /usr/libexec/helper-scripts/pre.bsh ]; then
   source /usr/libexec/helper-scripts/pre.bsh
fi

set -e

true "
#####################################################################
## INFO: BEGIN: $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $@
#####################################################################
"

## https://phabricator.whonix.org/T377
## Debian has no update-grub trigger yet:
## https://bugs.debian.org/481542
if command -v update-grub >/dev/null 2>&1; then
   update-grub || \
      echo "$DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME ERROR: Running \
'update-grub' failed with exit code $?. $DPKG_MAINTSCRIPT_PACKAGE is most \
likely only the trigger, not the cause. Unless you know this is not an issue, \
you should fix running 'update-grub', otherwise your system might no longer \
boot." >&2
fi

case "$1" in
   configure)
      true "INFO: Configuring $DPKG_MAINTSCRIPT_PACKAGE..."

      if ischroot --default-false ; then
         ## Avoid running "hostname host" inside chroot to avoid breaking the build host.
         true 'INFO: chroot detected. Skip running "hostname host".'
      else
         true 'INFO: Working around: "sudo: unable to resolve host host"'
         if [ -f /etc/hostname ]; then
            my_host_name="$(cat "/etc/hostname")" || true
            if [ ! "$my_host_name" = "" ]; then
               hostname "$my_host_name" || true
            fi
         fi
      fi

      ## 70_dpkg_origins {{
      ## || true to support re-running the script
      ## Get rid of old symlink.
      #unlink /etc/dpkg/origins/default || true
      #ln -s /etc/dpkg/origins/whonix /etc/dpkg/origins/default || true
      ## 70_dpkg_origins }}

      true "INFO: End configuring $DPKG_MAINTSCRIPT_PACKAGE."

      ;;

   *)
      ;;
esac

true "CI: $CI"

if [ "$CI" = "true" ]; then
   ## config-package-dev displace of /etc/hosts broken on Travis CI.
   ## Therefore disabling errexit and ERR trap.
   ## https://api.travis-ci.org/v3/job/715156029/log.txt
   ## Adding 'diversion of /etc/hosts to /etc/hosts.whonix-orig by whonix-base-files'
   ## dpkg-divert: error: unable to remove copied source file '/etc/hosts': Device or resource busy
   set +e
   trap "" ERR
fi

true "INFO: debhelper beginning here."

#DEBHELPER#

true "INFO: Done with debhelper."

true "
#####################################################################
## INFO: END  : $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $@
#####################################################################
"

## Explicitly "exit 0", so eventually trapped errors can be ignored.
exit 0
