#!/bin/bash
# shellcheck disable=SC2001,SC2016,SC2154

# This file is part of TorBox, an easy to use anonymizing router based on Raspberry Pi.
# Copyright (C) 2026 radio_24
# Contact: anonym@torbox.ch
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it is useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# DESCRIPTION
# This file deactivates already configured bridges in /etc/tor/torrc.
#
# SYNTAX
# ./bridges_deactivate_obfs4
#
#
###### SET VARIABLES ######
#
# SIZE OF THE MENU
#
# How many items do you have in the main menu?
NO_ITEMS=4
#
# How many lines are only for decoration and spaces?
NO_SPACER=2
#
#Set the the variables for the menu
MENU_WIDTH=80
MENU_WIDTH_REDUX=60
MENU_HEIGHT_10=10
# MENU_HEIGHT should not exceed 26
MENU_HEIGHT=$((8+NO_ITEMS+NO_SPACER))
MENU_LIST_HEIGHT=$((NO_ITEMS+NO_SPACER))

#Colors
RED='\033[1;31m'
YELLOW='\033[1;93m'
NOCOLOR='\033[0m'

#Other variables
BRIDGE_DB_URL="https://onionoo.torproject.org"
TORRC="/etc/tor/torrc"
BAK="/etc/tor/torrc.bak"
TORBOX_PATH="/home/torbox/torbox"
RUNFILE="$TORBOX_PATH/run/torbox.run"
EXITID=$(grep "^EXITID=" ${RUNFILE}) 2>/dev/null
bridge_address_list=""
i=0

###########################
######## FUNCTIONS ########

#include lib
.  /home/torbox/torbox/lib/torbox.lib

######## PREPARATIONS ########
#
# number_of_obfs4_bridges()
# How many OBFS4 bridges do we have? readarray reads into an array beginning with index 0
# Following variables can be used:
# $configured_bridges_deactivated -> An array with all deactivated OBFS4 bridges
# $configured_bridges_activated -> An array with all activated OBFS4 bridges
# $number_configured_bridges_deactivated -> Number of deactivated bridges
# $number_configured_bridges_activated -> Number of activated bridges
# $number_configured_bridges_total -> Total number of bridges
number_of_obfs4_bridges

###########################

if [ $EXITID = "EXITID=1" ]; then
  sudo sed -i "s/^EXITID=.*/EXITID=0/" ${RUNFILE}
  exit 0
fi

if [ $number_configured_bridges_activated = 0 ]; then
  clear
  echo -e "${YELLOW}[!] There are no activated OBFS4 bridges. ${NOCOLOR}"
  echo -e "${RED}[+] You may use the menu entry \"Activate configured OBFS4 bridges...\". ${NOCOLOR}"
  echo " "
  read -n 1 -s -r -p "Press any key to continue"
  clear
  exit 0
fi

clear
CHOICE=$(whiptail --cancel-button "Back" --title "TorBox v.0.5.5 - BRIDGE DEACTIVATION MENU" --menu "Choose an option (ESC -> go back)" $MENU_HEIGHT $MENU_WIDTH $MENU_LIST_HEIGHT \
"==" "===============================================================" \
" 1" "Deactivate ALL configured OBFS4 bridges and directly connect tor"  \
" 2" "Deactivate only OBFS4 bridges, which are not longer ONLINE"  \
" 3" "Deactivate only selected OBFS4 bridges"  \
" 4" "List all $number_configured_bridges_total OBFS4 bridges"  \
"==" "===============================================================" \
3>&1 1>&2 2>&3)

CHOICE=$(echo "$CHOICE" | tr -d ' ')
case "$CHOICE" in

  # Deactivate ALL configured bridges
  1)
		sudo sed -i "s/^EXITID=.*/EXITID=1/" ${RUNFILE}
    deactivate_obfs4_bridges bridges_deactivate_obfs4
		exit 0
  ;;

  # Deactivate only bridges, which are OFFLINE or do not exist anymore
  2)
    clear
    online_check $BRIDGE_DB_URL 0 1
    if [ $OCHECK == 1 ]; then
      echo -e "${YELLOW}[+] OK - we are connected with the bridge database${NOCOLOR}"
      echo " "
      echo -e "${RED}[+] Checking for bridges to deactivate - please wait...${NOCOLOR}"
			trap break SIGINT
      j=0
      i=0
      while [ $i -lt $number_configured_bridges_activated ]
      do
        bridge_address=$(cut -d ' ' -f2- <<< ${configured_bridges_activated[$i]})
        bridge_hash=$(cut -d ' ' -f3 <<< $bridge_address)
        if [ $CLEARNET_DECISION == 1 ]; then
          bridge_status=$($TORBOX_PATH/bin/bridges_check.py -f $bridge_hash)
        else
          bridge_status=$($TORBOX_PATH/bin/bridges_check.py --network=tor -f $bridge_hash)
        fi
        if [ $bridge_status == 0 ] || [ $bridge_status == 2 ]; then
          j=$((j+1))
          echo -e "${RED}[+] Deactivating bridge number $j${NOCOLOR}"
          #This is necessary to work with special characters in sed
          ORIGINAL_STR="Bridge $bridge_address"
          ORIGINAL_STR="$(<<< "$ORIGINAL_STR" sed -e 's`[][\\/.*^$]`\\&`g')"
          ORIGINAL_STR="^$ORIGINAL_STR"
          REPLACEMENT_STR="#Bridge $bridge_address"
          REPLACEMENT_STR="$(<<< "$REPLACEMENT_STR" sed -e 's`[][\\/.*^$]`\\&`g')"
          sudo sed -i "s/${ORIGINAL_STR}/${REPLACEMENT_STR}/g" ${TORRC}
        fi
        i=$((i+1))
      done
			trap "bash bridges_deactivate_obfs4; exit 0" SIGINT
      if [ $j = 0 ]; then
        echo " "
        echo -e "${YELLOW}[!] All checked OBFS4 do exist and are online -> nothing to deactivate!${NOCOLOR}"
        echo " "
        read -n 1 -s -r -p "Press any key to continue"
        clear
        exit 0
      else
        # We will not use "Press any key to continue" because the User shouldn't have the impression he can CTRL-C the process, which will break torrc
        sleep 5
        clear
        number_of_obfs4_bridges
        if [ $number_configured_bridges_activated = 0 ]; then
			    sudo sed -i "s/^EXITID=.*/EXITID=1/" ${RUNFILE}
					deactivate_obfs4_bridges bridges_deactivate_obfs4
					clear
					exit 0
        else
					sudo sed -i "s/^EXITID=.*/EXITID=1/" ${RUNFILE}
          activate_obfs4_bridges bridges_deactivate_obfs4
					clear
          exit 0
        fi
      fi
    else
      echo -e "${YELLOW}[+] OH NO! - no connection to the bridge database :( ${NOCOLOR}"
      echo -e "${YELLOW}[+] Can't fetch the status of the bridges - ABORTING :( ${NOCOLOR}"
      echo " "
      read -n 1 -s -r -p "Press any key to continue"
      clear
      exit 0
    fi
  ;;

  # Deactivate only selected bridges
  3)
		clear
		online_check $BRIDGE_DB_URL 0 1
		clear
		if [ $OCHECK == 1 ]; then
			if (whiptail --title "TorBox - BRIDGE DEACTIVATION" --yesno "Do you want to see the ONLINE/OFFLINE status of the bridges?" $MENU_HEIGHT_10 $MENU_WIDTH_REDUX); then
				echo -e "${YELLOW}[+] OK - we are connected with the bridge database${NOCOLOR}"
				echo " "
				sleep 2
				STATUS=1
			else
				STATUS=0
			fi
		else
			echo -e "${YELLOW}[!] SORRY! - no connection with the bridge database${NOCOLOR}"
      echo -e "${RED}[!] We'll go ahead anyway.${NOCOLOR}"
      echo " "
			sleep 3
		fi
		number_of_obfs4_bridges
		if [ "$number_configured_bridges_activated" == "0" ]; then
			echo ""
			echo -e "${YELLOW}[!] There is no activated bridge, which can be deactivated!${NOCOLOR}"
			echo " "
			read -n 1 -s -r -p "Press any key to continue"
			clear
			exit 0
		fi
		trap break SIGINT
		i=0
		while [ $i -lt $number_configured_bridges_activated ]
		do
			n=$((i+1))
			echo -e "${RED}[+] Checking bridge $n of $number_configured_bridges_activated bridges${NOCOLOR}"
			bridge_address=$(cut -d ' ' -f3,4 <<< ${configured_bridges_activated[$i]})
			bridge_ip=$(cut -d ' ' -f1 <<< $bridge_address)
			if [ $OCHECK == 1 ] && [ $STATUS == 1 ]; then
				bridge_hash=$(cut -d ' ' -f2 <<< $bridge_address)
				if [ $CLEARNET_DECISION == 1 ]; then
					bridge_status=$($TORBOX_PATH/bin/bridges_check.py -f $bridge_hash)
				else
					bridge_status=$($TORBOX_PATH/bin/bridges_check.py --network=tor -f $bridge_hash)
				fi
				if [ $bridge_status == 1 ]; then bridge_status="-ONLINE"
				elif [ $bridge_status == 0 ]; then bridge_status="-OFFLINE"
				elif [ $bridge_status == 2 ]; then bridge_status="-REMOVED"
				fi
			else bridge_status=""
			fi
			i=$((i+1))
			bridge_address="$bridge_address$bridge_status"
			bridge_address_display="$bridge_ip$bridge_status"
			bridge_address=$(sed "s/ /-/g" <<< "$bridge_address")
			bridge_address_display=$(sed "s/ /-/g" <<< "$bridge_address_display")
			if [ "$bridge_address_list" == "" ]; then
				bridge_address_list="$(printf "%s\n" "${bridge_address}")"
				bridge_address_display_list="$(printf "%s\n" "${bridge_address_display}")"
			else
				bridge_address_list="$(printf "%s\n%s\n" "${bridge_address_list}" "${bridge_address}")"
				bridge_address_display_list="$(printf "%s\n%s\n" "${bridge_address_display_list}" "${bridge_address_display}")"
			fi
		done
		trap "bash bridges_deactivate_obfs4; exit 0" SIGINT
		service_menu checklist "${bridge_address_display_list}" "\nThis is the list of bridges which can still get deactivated.\nImportant: If available, the bridge status is not always accurate!"
		if [ "$exitstatus" = "0" ]; then
			clear
			sudo cp ${TORRC} ${BAK}
			i=0
			for bridge_address in $bridge_address_list; do
				i=$((i+1))
				for SERVICE_NUMBER in $ENTRY_NUMBERS; do
					if [ "$i" == "$SERVICE_NUMBER" ]; then
						echo -e "${RED}[+] Deactivate bridge number $i${NOCOLOR}"
						bridge_address=$(sed "s/-ONLINE//g" <<< "$bridge_address")
						bridge_address=$(sed "s/-OFFLINE//g" <<< "$bridge_address")
						bridge_address=$(sed "s/-REMOVED//g" <<< "$bridge_address")
						bridge_address=$(sed "s/-/ /g" <<< "$bridge_address")
        		ORIGINAL_STR="Bridge obfs4 $bridge_address"
						#This is necessary to work with special characters in sed
        		ORIGINAL_STR="$(<<< "$ORIGINAL_STR" sed -e 's`[][\\/.*^$]`\\&`g')"
        		ORIGINAL_STR="^$ORIGINAL_STR"
        		REPLACEMENT_STR="#Bridge obfs4 $bridge_address"
						#This is necessary to work with special characters in sed
        		REPLACEMENT_STR="$(<<< "$REPLACEMENT_STR" sed -e 's`[][\\/.*^$]`\\&`g')"
        		sudo sed -i "s/${ORIGINAL_STR}/${REPLACEMENT_STR}/g" ${TORRC}
					fi
				done
      done
			echo ""
			echo -e "${RED}[+] DONE!${NOCOLOR}"
			sleep 5
			clear
			number_of_obfs4_bridges
      if [ $number_configured_bridges_activated = 0 ]; then
		    sudo sed -i "s/^EXITID=.*/EXITID=1/" ${RUNFILE}
				deactivate_obfs4_bridges bridges_deactivate_obfs4
				clear
				exit 0
      else
        if [ $j -gt 0 ]; then
		    	sudo sed -i "s/^EXITID=.*/EXITID=1/" ${RUNFILE}
          activate_obfs4_bridges bridges_deactivate_obfs4
					clear
          exit 0
        fi
      fi
    fi
  ;;

  # List all bridges configured in torrc and if online display the status of the bridges
  4)
    list_all_obfs4_bridges
  ;;

  *)
    clear
    exit 0
esac
bash bridges_deactivate_obfs4
exit 0
