#!/usr/bin/env bash

# This script sets up the Tor Project repository using the modern deb822 format.
# Optimized for Debian Bookworm and modern security standards.

set -e

# --- Variables (Defined as Lists/Arrays) ---
APP="torproject"
AVAILABLE="/etc/apt/sources.list-available"
ACTIVE="/etc/apt/sources.list.d"
KEY_HOME="/usr/share/keyrings"
KEYRING="${KEY_HOME}/tor-archive-keyring.gpg"
GPG_KEY_URL="https://deb.torproject.org/torproject.org/A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89.asc"

# Repository Specifics
ENABLED="yes"
TYPES="deb deb-src"
URIS="https://deb.torproject.org/torproject.org"
SUITES="bookworm"
COMPONENTS="main"
ARCHITECTURES=$(dpkg --print-architecture)

# --- Prep Work ---
echo "Installing prerequisites..."
sudo apt update && sudo apt install -y apt-transport-https wget gpg

# --- Key Management ---
echo "Importing Tor Project GPG key to ${KEYRING}..."
# Using gpg --dearmor ensures we have a binary keyring for the Signed-By field
wget -qO- "$GPG_KEY_URL" | gpg --dearmor | sudo tee "$KEYRING" >/dev/null

# --- Deb822 Configuration ---
# All fields are now strictly pulled from variables
conf_print_tor_sources() {
  cat <<EOF
Enabled: ${ENABLED}
Types: ${TYPES}
URIs: ${URIS}
Suites: ${SUITES}
Architectures: ${ARCHITECTURES}
Components: ${COMPONENTS}
Signed-By: ${KEYRING}
EOF
}

echo "Generating deb822 source file..."
sudo mkdir -p "$AVAILABLE"
conf_print_tor_sources | sudo tee "${AVAILABLE}/${APP}.sources" >/dev/null

# Create symbolic link to activate the repo
sudo ln -sf "${AVAILABLE}/${APP}.sources" "${ACTIVE}/${APP}.sources"

# --- Proxy Bypass ---
URL="deb.torproject.org"
PROXY_FILE="/etc/apt/apt.conf.d/02proxy"
ENTRY="Acquire::https::Proxy { \"${URL}\" DIRECT; };"

if [ -f "$PROXY_FILE" ] && grep -qF "${URL}" "$PROXY_FILE"; then
  echo "Proxy bypass for ${URL} already exists."
else
  sudo touch "$PROXY_FILE"
  echo "$ENTRY" | sudo tee -a "$PROXY_FILE" >/dev/null
  echo "Added proxy bypass for ${URL}."
fi

# --- Installation ---
echo "Updating package lists and installing Tor..."
sudo apt update
sudo apt install -y tor deb.torproject.org-keyring

echo "Tor Project repository setup complete."
