#!/bin/bash

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

loop_protection() {
   trap "error_handler" ERR

   prot="$(( $prot + 1 ))"
   if [ $prot -gt "60" ]; then
      exit 2
   fi
}

## {{ In case /etc/init.d/msgcollector has not started yet, i.e. has not
##    created "/run/msgcollector" yet, wait a bit.
maybe_wait() {
   trap "error_handler" ERR

   ## initialize prot variable
   if [ "$prot" = "" ]; then
      prot="0"
   fi

   loop_protection

   if [ ! -d "/run/msgcollector" ]; then
      true "Waiting for /run/msgcollector..."
      sleep 2 &
      wait "$!"
      maybe_wait
      return 0
   fi

   ## The following tests are only of interest when run in cli mode.
   if [ ! "$cli" = "1" ]; then
      return 0
   fi

   local command_v_tput_exit_code
   command_v_tput_exit_code="0"
   command -v tput >/dev/null || { command_v_tput_exit_code="$?" ; true; };

   if [ ! "$command_v_tput_exit_code" = "0" ]; then
      true "Waiting for tput..."
      sleep 2 &
      wait "$!"
      maybe_wait
      return 0
   fi
}
## }}
