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

sdwdate_gui_configuration_update() {
   if [ -f "/var/lib/whonix/do_once/${FUNCNAME}_version_1" ]; then
      return 0
   fi

   local dirs_list dir_item file_item

   dirs_list=(
      /usr/local/etc/sdwdate-gui.d
      /etc/sdwdate-gui.d
   )

   for dir_item in "${dirs_list[@]}"; do
      [[ -d "$dir_item" ]] || continue
      for file_item in "$dir_item"/*.conf; do
         [[ -f "$file_item" ]] || continue
         ## Add quotes around gateway value if not already quoted.
         sed -i 's/^gateway=\([^"].*\)$/gateway="\1"/' "$file_item" || true
      done
   done

   mkdir --parents "/var/lib/whonix/do_once"
   touch "/var/lib/whonix/do_once/${FUNCNAME}_version_1"
}

case "$1" in
    configure)
       mkdir -p /run/sdwdate-gui || true

       ## Enable Qubes-related services on Qubes OS only.
       ## TODO: Is marker-vm guaranteed to exist by the time this postinst
       ## script runs during the Qubes template build process?
       if [ -f /usr/share/qubes/marker-vm ]; then
         deb-systemd-helper enable sdwdate-gui-qubes@.socket
         deb-systemd-helper enable sdwdate-gui-qubes-proxy-helper.service
       fi

       sdwdate_gui_configuration_update
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "$DPKG_MAINTSCRIPT_NAME called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

## workaround for 'dh_installinit should run systemd-tmpfiles if a
## /usr/lib/tmpfiles.d/ snippet gets shipped for systemd-only packages
## also' - http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=795519
# In case this system is running systemd, we need to ensure that all
# necessary tmpfiles (if any) are created before starting.
if [ -d /run/systemd/system ] ; then
	systemd-tmpfiles --create /usr/lib/tmpfiles.d/sdwdate.conf >/dev/null || true
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
