#!/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/bin/updatecheck-daemon

#set -x

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

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

source /usr/libexec/helper-scripts/light_sleep.bsh

## sets: systemd_notify
source /usr/libexec/helper-scripts/systemd-notify.bsh

## provides: is_whole_number
source /usr/libexec/helper-scripts/strings.bsh

## 6 hours
[[ -v sleep_seconds ]] || sleep_seconds="21600"
if ! [[ -v initial_wait_minutes ]] || ! is_whole_number "$initial_wait_minutes"; then
  initial_wait_minutes="2"
fi
export sleep_seconds initial_wait_minutes

initial_wait_seconds=$(( initial_wait_minutes * 60 ))

"${systemd_notify[@]}" --pid="$$" --ready

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

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

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

   updatecheck_pid="$!"

   "${systemd_notify[@]}" --pid="$$" WATCHDOG=1

   true "$0: INFO: sleep $sleep_seconds... (1/2)"
   light_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..."
   light_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
