#!/bin/bash

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

check_control_port_filter_running() {
   ## Small check if Control Port Filter Proxy is functional.

   ## Only testing on Whonix-Gateway, because Control Port Filter Proxy only
   ## runs on Whonix-Gateway.
   if [ ! "$VM" = "Whonix-Gateway" ]; then
      return 0
   fi

   ## Skip in Qubes-Whonix-Gateway TemplateVM, because control port filter proxy is not running there.
   if test -f /run/qubes/this-is-templatevm ; then
      return 0
   fi

   local i
   i="0"
   while ! leaprun onion-grater-status >/dev/null 2>&1 ; do
      local MSG="<p>Control Port Filter Proxy test: The onion-grater service is not running. Waiting up to 30 seconds.</p>"
      if [ "$silent" -le "2" ]; then
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
      fi
      i="$(( $i + 1 ))"
      if [ "$i" -ge "30" ]; then
         local if_you_know_what_you_are_doing_msg
         if_you_know_what_you_are_doing_msg="$(if_you_know_what_you_are_doing_funct "$FUNCNAME")"
         local MSG="<p>Control Port Filter Proxy Test Result: onion-grater service not running.
<br></br>
<br></br>Did you disable Control Port Filter Proxy?
<br></br>
<br></br>Recommendation:
Try manually starting onion-grater.
<blockquote>
<code>sudo systemctl restart onion-grater</code>
</blockquote>

$if_you_know_what_you_are_doing_msg</p>"
         $output_x ${output_opts[@]} --messagex --typex "error" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "error" --message "$MSG"
         EXIT_CODE="1"
         return 0
      fi
      sleep "1" &
      lastpid="$!"
      wait "$lastpid" || true
   done
   local MSG="<p>Control Port Filter Proxy Test Result: OK</p>"
   if [ "$verbose" -ge "1" ]; then
      $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
      $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
   fi
}
