#!/bin/bash

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

#### meta start
#### project Whonix
#### category time and firewall
#### description
## restart firewall when sdwdate succeeded
#### meta end

## NOTE: No cleanup exit trap needed.
##       - No need to clean up inotifywait_subshell_fifo thanks to systemd 'PrivateTmp=true'.
##         No need to kill subshell thanks to systemd 'KillMode=control-group'.

#set -x
set -e

true "START: $0"

## inotifywait requires the folder to already exist.
mkdir --parents /run/updatesproxycheck
mkdir --parents /run/sdwdate
chown --recursive sdwdate:sdwdate /run/sdwdate

inotifywait_subshell_fifo="$(mktemp)"
rm --force "$inotifywait_subshell_fifo"
mkfifo "$inotifywait_subshell_fifo"

{
  inotifywait --quiet --recursive --monitor --event create --format "%w%f" "/run/sdwdate/" "/run/updatesproxycheck/" &
  wait "$!"

} > "$inotifywait_subshell_fifo" &

inotifywait_subshell_pid="$!"

if [ -f "/run/sdwdate/first_success" ] || [ -f "/run/updatesproxycheck/whonix-secure-proxy" ]; then
  if systemctl --no-pager --no-block status whonix-firewall; then
    systemctl --no-pager --no-block restart whonix-firewall || true
  fi
fi

while read -r file_name; do
  if [ "$file_name" = "/run/sdwdate/first_success" ] || [ "$file_name" = "/run/updatesproxycheck/whonix-secure-proxy" ]; then
    if systemctl --no-pager --no-block status whonix-firewall; then
      systemctl --no-pager --no-block restart whonix-firewall || true
    fi
  fi
done < "$inotifywait_subshell_fifo"

wait "$inotifywait_subshell_pid"
