#!/bin/bash

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

#### meta start
#### project Whonix and Kicksecure
#### category time and Tor
#### description
## start `anondate-set` when `sdwdate` creates file
## `/run/sdwdate/request_anondate-set`.
##
## This script allows `sdwdate` to request restart of Tor through creation of
## file `/run/sdwdate/request_anondate-set`.
##
## This is an alternative to avoid having to weaken `sdwdate` hardening (`systemd`,
## `apparmor`) while permitting `sdwdate` to restart of Tor.
##
## The script `sdwdate` executes the -> `/usr/libexec/helper-scripts/onion-time-pre-script` script,
## which creates file `/run/sdwdate/request_anondate-set` -> which results in this script running
## `anondate-set`.
##
## This script gets started systemd under user/group sdwdate.
#### meta end

#set -x
set -e

true "START: $0"

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

} > "$inotifywait_subshell_fifo" &

inotifywait_subshell_pid="$!"

if [ -f "/run/sdwdate/request_anondate-set" ]; then
   anondate-set || true
   rm -f "/run/sdwdate/request_anondate-set"
fi

while read file_name; do
   if [ "$file_name" = "/run/sdwdate/request_anondate-set" ] ; then
      anondate-set || true
      rm -f "/run/sdwdate/request_anondate-set"
   fi
done < "$inotifywait_subshell_fifo"

wait "$inotifywait_subshell_pid"
