#!/bin/bash
# Tor Hidden Service Setup Script for Bloodweb Onion Chat
# Run this script to install and configure Tor

set -e

echo "╔═══════════════════════════════════════════════════╗"
echo "║  Bloodweb Onion Chat - Tor Setup                  ║"
echo "╚═══════════════════════════════════════════════════╝"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root: sudo ./setup-tor.sh"
    exit 1
fi

# Detect OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
    VERSION=$VERSION_ID
else
    echo "❌ Cannot detect OS"
    exit 1
fi

echo "📍 Detected OS: $OS $VERSION"
echo ""

# Install Tor based on OS
echo "📦 Installing Tor..."
case $OS in
    debian|raspbian)
        apt update
        apt install -y tor
        ;;
    ubuntu)
        apt update
        apt install -y tor
        ;;
    centos|rhel|fedora)
        dnf install -y tor || yum install -y tor
        ;;
    *)
        echo "❌ Unsupported OS: $OS"
        echo "Please install Tor manually: https://www.torproject.org/download/"
        exit 1
        ;;
esac

echo "✅ Tor installed successfully"
echo ""

# Create Tor configuration directory if it doesn't exist
mkdir -p /etc/tor
chmod 755 /etc/tor

# Backup existing torrc if it exists
if [ -f /etc/tor/torrc ]; then
    echo "📋 Backing up existing torrc..."
    cp /etc/tor/torrc /etc/tor/torrc.backup.$(date +%Y%m%d_%H%M%S)
fi

# Copy our configuration
echo "⚙️  Configuring Tor hidden service..."
cp /var/www/html/onion/config/torrc.example /etc/tor/torrc
chmod 644 /etc/tor/torrc

# Create hidden service directory
mkdir -p /var/lib/tor/bloodweb-onion-chat
chown -R debian-tor:debian-tor /var/lib/tor/bloodweb-onion-chat 2>/dev/null || \
    chown -R tor:tor /var/lib/tor/bloodweb-onion-chat
chmod 700 /var/lib/tor/bloodweb-onion-chat

# Enable and start Tor
echo "🚀 Starting Tor service..."
systemctl enable tor
systemctl restart tor

# Wait for hidden service to generate
echo "⏳ Waiting for hidden service to generate (this may take 10-30 seconds)..."
sleep 15

# Check if hostname file was created
if [ -f /var/lib/tor/bloodweb-onion-chat/hostname ]; then
    ONION_ADDRESS=$(cat /var/lib/tor/bloodweb-onion-chat/hostname)
    echo ""
    echo "╔═══════════════════════════════════════════════════╗"
    echo "║  ✅ Tor Hidden Service Successfully Created       ║"
    echo "╚═══════════════════════════════════════════════════╝"
    echo ""
    echo "🧅 Your .onion address:"
    echo "   http://$ONION_ADDRESS"
    echo ""
    echo "📝 Next steps:"
    echo "   1. Update public/tor-required.html with your .onion address"
    echo "   2. Test access via Tor Browser"
    echo "   3. Ensure Node.js server is running: npm start"
    echo ""
    echo "🔍 Verify Tor is running:"
    echo "   sudo systemctl status tor"
    echo ""
    echo "📂 Hidden service files location:"
    echo "   /var/lib/tor/bloodweb-onion-chat/"
    echo ""
    echo "⚠️  IMPORTANT: Backup these files (they contain your .onion identity):"
    echo "   - /var/lib/tor/bloodweb-onion-chat/hostname"
    echo "   - /var/lib/tor/bloodweb-onion-chat/hs_ed25519_secret_key"
    echo "   - /var/lib/tor/bloodweb-onion-chat/hs_ed25519_public_key"
    echo ""
else
    echo ""
    echo "⚠️  Hidden service hostname not found yet."
    echo "   Wait a bit longer and check: sudo cat /var/lib/tor/bloodweb-onion-chat/hostname"
    echo "   Check Tor logs: sudo journalctl -u tor -f"
fi

echo "✅ Setup complete!"
