#!/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 $*
#####################################################################
"

## kloak changed from being 'WantedBy=multi-user.target' to being
## 'WantedBy=graphical.target' in Whonix 18. However, systemd doesn't notice
## this unless 'kloak.service' is disabled and re-enabled. Failing to disable
## and re-enable kloak can cause an ordering cycle, resulting in kloak failing
## to start. See:
##
## https://forums.whonix.org/t/kloak-broken-after-release-upgrade/22863
disable_and_reenable_kloak() {
  if [ -f "/var/lib/legacy-dist/do_once/${FUNCNAME[0]}_version_1" ]; then
    return 0
  fi
  mkdir --parents "/var/lib/legacy-dist/do_once"

  if ischroot --default-false; then
    true "INFO: Running in chroot, not disabling and re-enabling kloak."
    touch "/var/lib/legacy-dist/do_once/${FUNCNAME[0]}_version_1"
    return 0
  fi

  if [ ! -x "$(command -v systemctl)" ]; then
    true "INFO: systemctl command unavailable, not disabling and re-enabling kloak."
    touch "/var/lib/legacy-dist/do_once/${FUNCNAME[0]}_version_1"
    return 0
  fi

  if [ "$(systemctl is-enabled kloak.service)" != 'enabled' ]; then
    true "INFO: kloak is not enabled, not disabling and re-enabling kloak."
    touch "/var/lib/legacy-dist/do_once/${FUNCNAME[0]}_version_1"
    return 0
  fi

  true "INFO: Disabling and re-enabling kloak to prevent startup issues."
  systemctl disable kloak.service
  systemctl enable kloak.service

  touch "/var/lib/legacy-dist/do_once/${FUNCNAME[0]}_version_1"
}

/usr/libexec/legacy-dist/deprecation-popup cli || true
disable_and_reenable_kloak

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
