#!/bin/bash

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

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

folder_init() {
   ## Honor XDG_RUNTIME_DIR (the systemd / XDG base-dir spec env
   ## var for the user's runtime directory). On a logind session
   ## this is /run/user/$(id -u); in containers / chroots / CI
   ## runners that lack a logind setup, the consumer (e.g. the
   ## integration-test harness) can export an alternate path so
   ## every msgcollector subprocess uses the same dir.
   msgcollector_run_id_folder="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
   if test -d "${msgcollector_run_id_folder}" ; then
      true "folder_init: INFO: msgcollector_run_id_folder exists."
      msgcollector_run_dir="${msgcollector_run_id_folder}/msgcollector"
      if ! test -d "${msgcollector_run_dir}" ; then
         mkdir --parents -- "${msgcollector_run_dir}"
      fi
   else
      true "folder_init: INFO: msgcollector_run_id_folder does not exist. Falling back to mktemp."
      msgcollector_run_dir="$(mktemp --directory)"
   fi
}

loop_protection() {
   if ! is_whole_number "$loop_counter_protection"; then
      loop_counter_protection="0"
      ## Do not wait on first run of this function.
      return 0
   fi
   loop_counter_protection="$(( $loop_counter_protection + 1 ))"
   if [ "$loop_counter_protection" -gt "60" ]; then
      ## Timeout reached.
      exit 2
   fi
   light_sleep 1
}
