#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

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

set -x
set -e

## inotifywait requires the folder to already exist.
mkdir --parents /run/qubes-service
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/qubes-service/" &
   wait "$!"

} > "$inotifywait_subshell_fifo" &

inotifywait_subshell_pid="$!"

if [ -f "/run/sdwdate/first_success" ] || [ -f "/run/qubes-service/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 file_name; do
   if [ "$file_name" = "/run/sdwdate/first_success" ] || [ "$file_name" = "/run/qubes-service/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"
