#!/bin/bash

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

set -x

true "$0: START."

shopt -s nullglob
for i in \
   /etc/sdwdate-gui.d/*.conf \
   /usr/local/etc/sdwdate-gui.d/*.conf \
   ; do
      bash -n "$i"
      source "$i"
done

if ! test -f /usr/share/qubes/marker-vm ; then
   true "$0: INFO: Not implemented for Non-Qubes. Exiting. Ok."
   exit 0
fi

## https://forums.whonix.org/t/qubes-os-4-1-denied-whonix-newstatus-dom0-permission/12954
if test -e /usr/share/anon-gw-base-files/gateway ; then
   true "$0: INFO: Gateway detected. No need to notify self. Exiting. Ok."
   exit 0
fi

if [ "$disable" = "true" ]; then
   true "$0: INFO: setting disable=true. Exiting. Ok."
   exit 0
fi

if ! systemctl is-active --quiet sdwdate.service ; then
   true "$0: INFO: sdwdate not running. No need notify shutdown. Exiting. Ok."
   exit 0
fi

if [ "$gateway" = "" ]; then
   ## Fallback.
   ## If gateway is not configured in config file, use default.
   ## Non-ideal.
   ## qrexec feature request: send this over qrexec to the NetVM I am connected to / sys-whonix hardcoded / sys-whonix unexpected autostart #5253
   ## https://github.com/QubesOS/qubes-issues/issues/5253
   ## Networks VMs are restarting themselves without valid reason #5930
   ## https://github.com/QubesOS/qubes-issues/issues/5930
   ## HARDCODED!
   gateway=sys-whonix
fi

/usr/bin/qrexec-client-vm "$gateway" "whonix.NewStatus+shutdown"

true "$0: END."
