#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

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

   ## Skip this test, if not running on Whonix-Gateway.
   if [ ! -e "/usr/share/anon-gw-base-files/gateway" ]; then
      TOR_ENABLED="1"
      return 0
   fi

   ## Skip this test, if running in Qubes TemplateVM.
   if command -v qubesdb-read >/dev/null 2>&1 ; then
      local qubes_vm_type
      qubes_vm_type="$(qubesdb-read /qubes-vm-type)" || true
      if [ "$qubes_vm_type" = "TemplateVM" ]; then
         TOR_ENABLED="1"
         return 0
      fi
   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
}
