#!/usr/bin/env bash

set -euo pipefail

die() {
  echo "Error: $*" >&2
  exit 1
}

config_path="${PROXYCHAINS_CONFIG:-/etc/proxychains4.conf}"
check_only=false
if [[ "${1:-}" == "--check" ]]; then
  check_only=true
  shift
fi

command -v proxychains4 >/dev/null 2>&1 || die "proxychains4 is not installed."
command -v systemctl >/dev/null 2>&1 || die "systemctl is required to manage Tor."
if ((EUID == 0)); then
  sudo_cmd=()
elif command -v sudo >/dev/null 2>&1; then
  sudo_cmd=(sudo)
else
  die "run as root or install sudo."
fi
[[ -r "$config_path" ]] || die "ProxyChains configuration is not readable: $config_path"

if ! grep -Eq '^[[:space:]]*proxy_dns([[:space:]]|$)' "$config_path"; then
  die "enable 'proxy_dns' in $config_path to prevent DNS leaks."
fi
if ! grep -Eq '^[[:space:]]*strict_chain([[:space:]]|$)' "$config_path"; then
  die "enable 'strict_chain' in $config_path."
fi
if grep -Eq '^[[:space:]]*(dynamic_chain|random_chain|round_robin_chain)([[:space:]]|$)' \
  "$config_path"; then
  die "disable other chain modes in $config_path so only 'strict_chain' is active."
fi
tor_proxy_pattern='^[[:space:]]*socks5[[:space:]]+127\.0\.0\.1'
tor_proxy_pattern+='[[:space:]]+9050([[:space:]]|$)'
if ! grep -Eq "$tor_proxy_pattern" "$config_path"; then
  die "add 'socks5 127.0.0.1 9050' to the ProxyList in $config_path."
fi

if [[ "$check_only" != true ]]; then
  command -v firefox >/dev/null 2>&1 || die "Firefox is not installed."
  command -v pgrep >/dev/null 2>&1 || die "pgrep is required to check for running Firefox instances."
  for process_name in firefox firefox-esr; do
    if pgrep -x "$process_name" >/dev/null 2>&1; then
      die "close all Firefox instances before launching through ProxyChains."
    else
      pgrep_status=$?
      if ((pgrep_status != 1)); then
        die "unable to determine whether Firefox is already running."
      fi
    fi
  done
fi

echo "Starting Tor..."
"${sudo_cmd[@]}" systemctl start tor
"${sudo_cmd[@]}" systemctl is-active --quiet tor || die "the Tor service did not start."

if [[ "$check_only" == true ]]; then
  echo "ProxyChains configuration and the Tor service are ready."
  exit 0
fi

echo "Launching Firefox through ProxyChains and Tor..."
exec proxychains4 -f "$config_path" firefox --no-remote "$@"
