#!/bin/bash
# Native Tor Browser Container Manager
# Uses the official Tor Browser Bundle from the Tor Project
# Usage: tor-browser-native.sh [create|start|stop|launch|status|destroy|shell|update]

set -e

CONTAINER="tor-browser-native"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SPEC_FILE="$SCRIPT_DIR/../specs/tor-browser-native.yaml"
DOWNLOADS_DIR="$HOME/Downloads/tor-browser-native"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo -e "${GREEN}[tor-native]${NC} $1"; }
warn() { echo -e "${YELLOW}[tor-native]${NC} $1"; }
error() { echo -e "${RED}[tor-native]${NC} $1"; }

container_exists() {
    sudo machinectl list-images 2>/dev/null | grep -q "^$CONTAINER "
}

container_running() {
    sudo machinectl list 2>/dev/null | grep -q "^$CONTAINER "
}

wait_for_boot() {
    log "Waiting for container to boot..."
    for i in {1..30}; do
        if sudo machinectl shell "$CONTAINER" /bin/true 2>/dev/null; then
            return 0
        fi
        sleep 1
    done
    error "Container failed to boot"
    return 1
}

setup_network() {
    log "Configuring network..."
    sudo machinectl shell "$CONTAINER" /bin/bash -c '
        # Install network tools if needed
        if ! command -v ip &>/dev/null; then
            apt-get update
            apt-get install -y iproute2
        fi

        # Create network config if not exists
        if [ ! -f /etc/systemd/network/80-container-host0.network ]; then
            cat > /etc/systemd/network/80-container-host0.network << EOF
[Match]
Name=host0

[Network]
DHCP=yes
EOF
        fi
        systemctl enable --now systemd-networkd 2>/dev/null || true
    ' 2>/dev/null

    # Wait for IP
    for i in {1..30}; do
        IP=$(sudo machinectl show "$CONTAINER" -p Addresses --value 2>/dev/null | grep -oE '192\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        if [ -n "$IP" ]; then
            log "Container IP: $IP"
            return 0
        fi
        sleep 1
    done
    warn "Could not get container IP"
}

install_tor_browser() {
    log "Installing Tor Browser Bundle..."
    sudo machinectl shell "$CONTAINER" /bin/bash -c '
        # Install dependencies
        apt-get update
        apt-get install -y wget gpg file libgtk-3-0 libdbus-glib-1-2 libasound2t64 \
            libx11-xcb1 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libxtst6 \
            libpango-1.0-0 libcairo2 libatk1.0-0 libgdk-pixbuf-2.0-0 fonts-dejavu

        # Create browser user with UID 1000
        if ! id -u browser 2>/dev/null; then
            useradd -u 1000 -m -s /bin/bash browser
        fi

        # Download Tor Browser as browser user
        TOR_VERSION="15.0.4"
        TOR_URL="https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux-x86_64-${TOR_VERSION}.tar.xz"
        TOR_SIG_URL="${TOR_URL}.asc"

        cd /home/browser

        if [ ! -d "tor-browser" ]; then
            echo "Downloading Tor Browser ${TOR_VERSION}..."
            wget -q --show-progress "$TOR_URL" -O tor-browser.tar.xz
            wget -q "$TOR_SIG_URL" -O tor-browser.tar.xz.asc

            # Import Tor Browser developers key
            gpg --auto-key-locate nodefault,wkd --locate-keys torbrowser@torproject.org 2>/dev/null || true

            # Extract
            echo "Extracting..."
            tar -xJf tor-browser.tar.xz
            rm tor-browser.tar.xz tor-browser.tar.xz.asc

            chown -R browser:browser /home/browser/tor-browser
            echo "Tor Browser installed"
        else
            echo "Tor Browser already installed"
        fi
    ' 2>/dev/null
}

create_nspawn_config() {
    log "Creating nspawn configuration..."
    sudo tee /etc/systemd/nspawn/$CONTAINER.nspawn > /dev/null << EOF
[Exec]
Boot=yes
PrivateUsers=no
Environment=DISPLAY=:0
Environment=WAYLAND_DISPLAY=wayland-0
Environment=XDG_RUNTIME_DIR=/tmp
Environment=MOZ_ENABLE_WAYLAND=1

[Network]
VirtualEthernet=yes
Bridge=br0

[Files]
Bind=/tmp/.X11-unix:/tmp/.X11-unix
Bind=/run/user/1000/wayland-0:/tmp/wayland-0
Bind=$DOWNLOADS_DIR:/home/browser/Downloads
EOF
}

cmd_create() {
    if container_exists; then
        error "Container already exists. Use 'destroy' first or 'start' to run it."
        exit 1
    fi

    # Create downloads directory
    mkdir -p "$DOWNLOADS_DIR"

    log "Creating container from spec..."

    # Find gaol binary
    GAOL_BIN=$(which gaol)
    if [ -z "$GAOL_BIN" ]; then
        error "gaol not found in PATH"
        exit 1
    fi

    sudo "$GAOL_BIN" apply "$SPEC_FILE"

    # Update nspawn config with correct settings
    create_nspawn_config

    log "Starting container..."
    sudo machinectl start "$CONTAINER"
    wait_for_boot

    setup_network
    install_tor_browser

    log "Container created and configured!"
    log "Run '$0 launch' to start Tor Browser"
}

cmd_start() {
    if ! container_exists; then
        error "Container does not exist. Run 'create' first."
        exit 1
    fi

    if container_running; then
        warn "Container already running"
        return 0
    fi

    log "Starting container..."
    sudo machinectl start "$CONTAINER"
    wait_for_boot
    setup_network
    log "Container started!"
}

cmd_stop() {
    if ! container_running; then
        warn "Container not running"
        return 0
    fi

    log "Stopping container..."
    sudo machinectl stop "$CONTAINER"
    log "Container stopped"
}

cmd_launch() {
    if ! container_running; then
        log "Container not running, starting..."
        cmd_start
    fi

    log "Launching Tor Browser..."

    # Create systemd service if it doesn't exist
    sudo machinectl shell "$CONTAINER" /bin/bash -c '
        if [ ! -f /etc/systemd/system/tor-browser.service ]; then
            cat > /etc/systemd/system/tor-browser.service << EOF
[Unit]
Description=Tor Browser
After=network.target

[Service]
Type=simple
User=browser
Environment=WAYLAND_DISPLAY=wayland-0
Environment=XDG_RUNTIME_DIR=/tmp
Environment=MOZ_ENABLE_WAYLAND=1
Environment=NO_AT_BRIDGE=1
Environment=LIBGL_ALWAYS_SOFTWARE=1
Environment=HOME=/home/browser
WorkingDirectory=/home/browser/tor-browser
ExecStart=/home/browser/tor-browser/Browser/start-tor-browser
Restart=no

[Install]
WantedBy=multi-user.target
EOF
            systemctl daemon-reload
        fi

        # Fix dconf permissions
        mkdir -p /tmp/dconf
        chmod 777 /tmp/dconf

        # Stop existing if running
        systemctl stop tor-browser 2>/dev/null || true
        pkill -f "firefox.real" 2>/dev/null || true
        sleep 1

        # Start the service
        systemctl start tor-browser
        sleep 2
        systemctl is-active tor-browser && echo "Tor Browser launched via systemd"
    ' 2>/dev/null

    log "Tor Browser launched - check your desktop"
}

cmd_update() {
    if ! container_running; then
        log "Container not running, starting..."
        cmd_start
    fi

    log "Checking for Tor Browser updates..."
    sudo machinectl shell "$CONTAINER" /bin/bash -c '
        # Remove old installation
        rm -rf /home/browser/tor-browser

        # Re-download latest
        TOR_VERSION="15.0.4"
        TOR_URL="https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux-x86_64-${TOR_VERSION}.tar.xz"

        cd /home/browser
        echo "Downloading Tor Browser ${TOR_VERSION}..."
        wget -q --show-progress "$TOR_URL" -O tor-browser.tar.xz

        echo "Extracting..."
        tar -xJf tor-browser.tar.xz
        rm tor-browser.tar.xz

        chown -R browser:browser /home/browser/tor-browser
        echo "Tor Browser updated to ${TOR_VERSION}"
    ' 2>/dev/null

    log "Update complete"
}

cmd_status() {
    echo "=== Container Status ==="
    if container_exists; then
        echo "Image: EXISTS"
    else
        echo "Image: NOT FOUND"
        return
    fi

    if container_running; then
        echo "State: RUNNING"
        IP=$(sudo machinectl show "$CONTAINER" -p Addresses --value 2>/dev/null | head -1)
        echo "IP: $IP"

        # Check Tor Browser
        if sudo machinectl shell "$CONTAINER" /bin/bash -c 'pgrep -f "firefox.real"' 2>/dev/null | grep -q .; then
            echo "Tor Browser: RUNNING"
        else
            echo "Tor Browser: NOT RUNNING"
        fi

        # Check Tor connection
        if sudo machinectl shell "$CONTAINER" /bin/bash -c 'test -d /home/browser/tor-browser' 2>/dev/null; then
            echo "Tor Browser Bundle: INSTALLED"
        else
            echo "Tor Browser Bundle: NOT INSTALLED"
        fi
    else
        echo "State: STOPPED"
    fi
}

cmd_destroy() {
    if container_running; then
        log "Stopping container..."
        sudo machinectl stop "$CONTAINER" 2>/dev/null || true
        sleep 2
    fi

    if container_exists; then
        log "Removing container..."
        sudo machinectl remove "$CONTAINER" 2>/dev/null || true
        sudo rm -f /etc/systemd/nspawn/$CONTAINER.nspawn
        log "Container destroyed"
    else
        warn "Container does not exist"
    fi
}

cmd_shell() {
    if ! container_running; then
        error "Container not running. Run 'start' first."
        exit 1
    fi

    sudo machinectl shell "$CONTAINER"
}

cmd_help() {
    cat << EOF
Native Tor Browser Container Manager

Usage: $0 <command>

Commands:
  create   Create and configure the Tor Browser container
  start    Start the container (if stopped)
  stop     Stop the container
  launch   Launch Tor Browser (starts container if needed)
  update   Re-download and update Tor Browser
  status   Show container status
  destroy  Remove the container completely
  shell    Open a shell in the container
  help     Show this help message

This container uses the official Tor Browser Bundle from the Tor Project,
which includes its own Tor daemon and is specifically designed for
anonymous browsing with fingerprinting protection.

Downloads are saved to: $DOWNLOADS_DIR
EOF
}

# Main
case "${1:-help}" in
    create)  cmd_create ;;
    start)   cmd_start ;;
    stop)    cmd_stop ;;
    launch)  cmd_launch ;;
    update)  cmd_update ;;
    status)  cmd_status ;;
    destroy) cmd_destroy ;;
    shell)   cmd_shell ;;
    help|--help|-h) cmd_help ;;
    *)
        error "Unknown command: $1"
        cmd_help
        exit 1
        ;;
esac
