#!/bin/bash

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

# shellcheck source=./check_runtime.bsh
source /usr/libexec/helper-scripts/check_runtime.bsh

check_tor_enabled_do() {
   ## Fallback.
   TOR_ENABLED="1"

   ## Skip this test, if running in Qubes TemplateVM.
   if test -f /run/qubes/this-is-templatevm ; then
      TOR_ENABLED="1"
      return 0
   fi

   local line file_name file_name_list i

   shopt -s globstar
   shopt -s nullglob

   if [ -f /usr/share/tor/tor-service-defaults-torrc ]; then
      file_name_list+="/usr/share/tor/tor-service-defaults-torrc"
      file_name_list+=" "
   fi
   if [ -f /etc/tor/torrc ]; then
      file_name_list+="/etc/tor/torrc"
      file_name_list+=" "
   fi

   for i in /etc/torrc.d/* ; do
      file_name_list+="$i"
      file_name_list+=" "
   done

   for i in /usr/local/etc/torrc.d/* ; do
      file_name_list+="$i"
      file_name_list+=" "
   done

   for file_name in $file_name_list ; do
      if ! test -f "$file_name" ; then
         continue
      fi
      true "file_name: '$file_name'"
      while read -r line || [ -n "$line" ]; do
         if [ "$line" = "DisableNetwork 0" ]; then
            TOR_ENABLED="1"
         fi
         if [ "$line" = "DisableNetwork 1" ]; then
            TOR_ENABLED="0"
         fi
      done < "$file_name"
      unset line
   done
}

if was_executed "${BASH_SOURCE[0]}"; then
   check_tor_enabled_do
   if [ "$TOR_ENABLED" = "1" ]; then
      printf '%s' "true"
   else
      printf '%s' "false"
   fi
fi
