#!/bin/bash

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

## Developer test command:
#sudo genmkfile install && initial_wait_minutes=0 sleep_seconds=10 bash -x /usr/libexec/systemcheck/updatecheck-daemon

#set -x

printf "%s\n" "$0: INFO: start."

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

## 6 hours
[[ -v sleep_seconds ]] || sleep_seconds="21600"
[[ -v initial_wait_minutes ]] || initial_wait_minutes="2"
export sleep_seconds initial_wait_minutes

[[ -v NOTIFY_SOCKET ]] || NOTIFY_SOCKET=""

if [ "$NOTIFY_SOCKET" = "" ]; then
   ## Support manual run from command line.
   ## I.e. when run not through systemd unit.
   systemd_notify="true 'INFO: skip because NOTIFY_SOCKET unset. Probably run manually. SKIP: systemd-notify"
else
   systemd_notify=systemd-notify
fi

$systemd_notify --pid="$$" --ready

printf "%s\n" "$0: INFO: First start. Therefore waiting for ${initial_wait_minutes} minutes for first updatecheck."
sleep -- "${initial_wait_minutes}m"

while true; do
   printf "%s\n" "$0: INFO: loop start."
   $systemd_notify --pid="$$" WATCHDOG=1

   if [ -o xtrace ]; then
      bash -x /usr/libexec/systemcheck/updatecheck &
   else
      /usr/libexec/systemcheck/updatecheck &
   fi

   updatecheck_pid="$!"

   $systemd_notify --pid="$$" WATCHDOG=1

   true "$0: INFO: sleep $sleep_seconds... (1/2)"
   sleep -- "$sleep_seconds"
   true "$0: INFO: Completed sleep $sleep_seconds. (1/2)"

   true "$0: INFO: Check if updatecheck is still running. (1/2)"
   if kill -0 -- "$updatecheck_pid" 2>/dev/null; then
      true "$0: INFO: updatecheck is still running. Sending signal sigterm... (1/2)"
      kill -s sigterm -- "$updatecheck_pid" 2>/dev/null || true
   fi

   true "$0: INFO: sleep 10..."
   sleep -- 10
   true "$0: INFO: Completed sleep 10."

   true "$0: INFO: Check if updatecheck is still running. (2/2)"
   if kill -0 -- "$updatecheck_pid" 2>/dev/null; then
      true "$0: INFO: updatecheck is still running. Sending signal sigkill... (2/2)"
      kill -s sigkill -- "$updatecheck_pid" 2>/dev/null || true
   fi

   printf "%s\n" "$0: INFO: loop end."

   ## Debugging.
   #exit 0
done
