#!/bin/bash

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

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
}

: "${BASH_SOURCE:=""}"

if [ "${BASH_SOURCE}" = "${0}" ]; then
  ## Script was executed.
  tor_enabled_check_was_sourced="false"
elif [ "${BASH_SOURCE}" = "$(command -v "${0}")" ]; then
  ## Script was executed probably with 'bash -x'.
  tor_enabled_check_was_sourced="false"
else
  ## Script was sourced.
  ## This is useful for other programs / scripts to be able to `source` the
  ## functions of this script for code re-use. dist-installer-gui will do this.
  tor_enabled_check_was_sourced="true"
fi

if [ "$tor_enabled_check_was_sourced" = "false" ]; then
   check_tor_enabled_do
   if [ "$TOR_ENABLED" = "1" ]; then
      printf '%s' "true"
   else
      printf '%s' "false"
   fi
fi
