#!/usr/bin/env bash
#
# i2p-release-tools.sh - All-In-One I2P Release Management Tool
#
# A unified launcher for I2P release deployment tasks including:
#   - Torrent creation
#   - Torrent distribution to seed servers
#   - YAML generation for website
#   - Download verification across all mirrors
#   - Full release workflow automation
#
# Usage:
#   ./i2p-release-tools.sh [options]
#   ./i2p-release-tools.sh --menu              # Interactive menu (default)
#   ./i2p-release-tools.sh --create <dir>      # Create torrents
#   ./i2p-release-tools.sh --push <dir>        # Push torrents
#   ./i2p-release-tools.sh --yaml <dir>        # Generate YAML
#   ./i2p-release-tools.sh --verify <dir>      # Verify downloads
#   ./i2p-release-tools.sh --full <dir>        # Full workflow
#
set -euo pipefail

# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERSION="1.0.0"

# Mirror URLs for verification
declare -A MIRRORS=(
    ["clearnet_primary"]="https://files.i2p.net"
    ["clearnet_secondary"]="https://mirror.stormycloud.org"
    ["i2p"]="http://mirror.stormycloud.i2p"
    ["tor"]="http://hhn4r4qyrmplmfiermza6p3d67a5ra7ecwjeoo5a5ddiogwhyjg675id.onion"
)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# -----------------------------------------------------------------------------
# Logging helpers
# -----------------------------------------------------------------------------
log_info()    { echo -e "${BLUE}ℹ️  ${NC}$*"; }
log_success() { echo -e "${GREEN}✅ ${NC}$*"; }
log_warning() { echo -e "${YELLOW}⚠️  ${NC}$*"; }
log_error()   { echo -e "${RED}❌ ${NC}$*" >&2; }
log_header()  { echo -e "\n${BOLD}${CYAN}$*${NC}"; }

# -----------------------------------------------------------------------------
# Print banner
# -----------------------------------------------------------------------------
print_banner() {
    echo -e "${CYAN}"
    cat << 'EOF'
╔═══════════════════════════════════════════════════════════════════════════╗
║                                                                           ║
║     ██╗██████╗ ██████╗     ██████╗ ███████╗██╗     ███████╗ █████╗ ███████║
║     ██║╚════██╗██╔══██╗    ██╔══██╗██╔════╝██║     ██╔════╝██╔══██╗██╔════║
║     ██║ █████╔╝██████╔╝    ██████╔╝█████╗  ██║     █████╗  ███████║███████║
║     ██║██╔═══╝ ██╔═══╝     ██╔══██╗██╔══╝  ██║     ██╔══╝  ██╔══██║╚════██║
║     ██║███████╗██║         ██║  ██║███████╗███████╗███████╗██║  ██║███████║
║     ╚═╝╚══════╝╚═╝         ╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝╚═╝  ╚═╝╚══════║
║                                                                           ║
║                    🌀 I2P Release Management Tools 🌀                     ║
║                              Version 1.0.0                                ║
╚═══════════════════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

# -----------------------------------------------------------------------------
# Print main menu
# -----------------------------------------------------------------------------
print_menu() {
    echo -e "${BOLD}┌─────────────────────────────────────────────────────────────┐${NC}"
    echo -e "${BOLD}│                      MAIN MENU                              │${NC}"
    echo -e "${BOLD}├─────────────────────────────────────────────────────────────┤${NC}"
    echo -e "${BOLD}│${NC}  ${GREEN}1.${NC} Create Torrents              - Generate .torrent files   ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${GREEN}2.${NC} Push Torrents                - Distribute to seed hosts  ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${GREEN}3.${NC} Generate YAML                - Create download page YAML ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${GREEN}4.${NC} Verify Downloads             - Check all mirror links    ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${GREEN}5.${NC} Full Release Workflow        - Run complete deployment   ${BOLD}│${NC}"
    echo -e "${BOLD}├─────────────────────────────────────────────────────────────┤${NC}"
    echo -e "${BOLD}│${NC}  ${YELLOW}6.${NC} Push Custom Torrents         - Push existing .torrents   ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${YELLOW}7.${NC} Check Dependencies           - Verify required tools     ${BOLD}│${NC}"
    echo -e "${BOLD}│${NC}  ${YELLOW}8.${NC} View Configuration           - Show current settings     ${BOLD}│${NC}"
    echo -e "${BOLD}├─────────────────────────────────────────────────────────────┤${NC}"
    echo -e "${BOLD}│${NC}  ${RED}0.${NC} Exit                                                     ${BOLD}│${NC}"
    echo -e "${BOLD}└─────────────────────────────────────────────────────────────┘${NC}"
    echo ""
}

# -----------------------------------------------------------------------------
# Read directory input with validation
# -----------------------------------------------------------------------------
read_directory() {
    local prompt="$1"
    local dir=""

    while true; do
        echo -en "${CYAN}$prompt: ${NC}" >&2
        read -r dir

        # Allow empty to cancel
        if [[ -z "$dir" ]]; then
            echo "Cancelled." >&2
            return 1
        fi

        # Expand tilde
        dir="${dir/#\~/$HOME}"

        if [[ -d "$dir" ]]; then
            echo "$dir"
            return 0
        else
            log_error "Directory does not exist: $dir"
            echo "Please enter a valid directory path or press Enter to cancel." >&2
        fi
    done
}

# -----------------------------------------------------------------------------
# Read yes/no input
# -----------------------------------------------------------------------------
read_yes_no() {
    local prompt="$1"
    local default="${2:-n}"
    local response

    if [[ "$default" == "y" ]]; then
        prompt="$prompt [Y/n]: "
    else
        prompt="$prompt [y/N]: "
    fi

    echo -en "${CYAN}$prompt${NC}"
    read -r response

    response="${response:-$default}"
    [[ "${response,,}" == "y" || "${response,,}" == "yes" ]]
}

# -----------------------------------------------------------------------------
# Check dependencies
# -----------------------------------------------------------------------------
check_dependencies() {
    log_header "Checking Dependencies"
    echo ""

    local all_ok=true
    local deps=(
        "mktorrent:Torrent creation"
        "rsync:File distribution"
        "curl:Download verification"
        "sha256sum:Checksum calculation"
        "transmission-show:Magnet link extraction"
        "npx:R2 upload (wrangler)"
        "torsocks:Tor verification (optional)"
    )

    for dep_info in "${deps[@]}"; do
        local cmd="${dep_info%%:*}"
        local desc="${dep_info#*:}"

        if command -v "$cmd" &>/dev/null; then
            echo -e "  ${GREEN}✓${NC} $cmd - $desc"
        else
            if [[ "$cmd" == "torsocks" ]]; then
                echo -e "  ${YELLOW}○${NC} $cmd - $desc (optional)"
            else
                echo -e "  ${RED}✗${NC} $cmd - $desc"
                all_ok=false
            fi
        fi
    done

    echo ""
    if [[ "$all_ok" == true ]]; then
        log_success "All required dependencies are installed!"
    else
        log_warning "Some dependencies are missing. Install with:"
        echo "  apt install mktorrent rsync curl transmission-cli torsocks"
        echo "  npm install -g wrangler"
    fi

    return 0
}

# -----------------------------------------------------------------------------
# View configuration
# -----------------------------------------------------------------------------
view_configuration() {
    log_header "Current Configuration"
    echo ""

    echo -e "${BOLD}Script Locations:${NC}"
    echo "  Create Torrents:  $SCRIPT_DIR/create-torrents.sh"
    echo "  Generate YAML:    $SCRIPT_DIR/generate-release-yaml.sh"
    echo "  SSH Config:       $SCRIPT_DIR/ssh.conf"
    echo "  Hosts File:       $SCRIPT_DIR/hosts.txt"
    echo ""

    echo -e "${BOLD}Mirror URLs:${NC}"
    for mirror in "${!MIRRORS[@]}"; do
        echo "  $mirror: ${MIRRORS[$mirror]}"
    done
    echo ""

    # Show SSH config if exists
    if [[ -f "$SCRIPT_DIR/ssh.conf" ]]; then
        echo -e "${BOLD}SSH Configuration (from ssh.conf):${NC}"
        grep -v '^#' "$SCRIPT_DIR/ssh.conf" | grep -v '^$' | sed 's/^/  /'
        echo ""
    fi

    # Show hosts if exist
    if [[ -f "$SCRIPT_DIR/hosts.txt" ]]; then
        local hosts
        hosts=$(grep -v '^#' "$SCRIPT_DIR/hosts.txt" | grep -v '^$' || true)
        if [[ -n "$hosts" ]]; then
            echo -e "${BOLD}Configured Seed Hosts:${NC}"
            echo "$hosts" | sed 's/^/  /'
        else
            echo -e "${BOLD}Configured Seed Hosts:${NC} (none configured)"
        fi
        echo ""
    fi
}

# -----------------------------------------------------------------------------
# Option 1: Create Torrents
# -----------------------------------------------------------------------------
do_create_torrents() {
    log_header "Create Torrents"
    echo ""

    local release_dir
    release_dir=$(read_directory "Enter release directory (e.g., /srv/mirror/2.10.0)") || return 0

    local opts=""

    if read_yes_no "Force regenerate existing torrents?" "n"; then
        opts="$opts --force"
    fi

    if read_yes_no "Dry-run mode (show what would be done)?" "n"; then
        opts="$opts --dry-run"
    fi

    echo ""
    log_info "Running: create-torrents.sh $release_dir $opts"
    echo ""

    "$SCRIPT_DIR/create-torrents.sh" "$release_dir" $opts
}

# -----------------------------------------------------------------------------
# Option 2: Push Torrents (from release directory)
# -----------------------------------------------------------------------------
do_push_torrents() {
    log_header "Push Torrents to Seed Hosts"
    echo ""

    local release_dir
    release_dir=$(read_directory "Enter release directory containing .torrent files") || return 0

    local opts="--distribute"

    if read_yes_no "Dry-run mode (show what would be done)?" "n"; then
        opts="$opts --dry-run"
    fi

    echo ""
    log_info "Running: create-torrents.sh $release_dir $opts"
    echo ""

    "$SCRIPT_DIR/create-torrents.sh" "$release_dir" $opts
}

# -----------------------------------------------------------------------------
# Option 3: Generate YAML
# -----------------------------------------------------------------------------
do_generate_yaml() {
    log_header "Generate Download YAML"
    echo ""

    local release_dir
    release_dir=$(read_directory "Enter release directory (e.g., /srv/mirror/2.10.0)") || return 0

    echo ""
    log_info "Running: generate-release-yaml.sh $release_dir"
    echo ""

    "$SCRIPT_DIR/generate-release-yaml.sh" "$release_dir"
}

# -----------------------------------------------------------------------------
# Option 4: Verify Downloads
# -----------------------------------------------------------------------------
do_verify_downloads() {
    log_header "Download Verification"
    echo ""

    local release_dir
    release_dir=$(read_directory "Enter release directory to verify") || return 0

    local version
    version=$(basename "$release_dir")

    echo ""
    log_info "Verifying downloads for version: $version"
    echo ""

    # Find release files (skip signatures, checksums, torrents)
    local files=()
    shopt -s nullglob
    for f in "$release_dir"/*; do
        local basename_f
        basename_f=$(basename "$f")

        # Skip non-files
        [[ ! -f "$f" ]] && continue

        # Skip signatures, torrents, checksums
        case "$basename_f" in
            *.sig|*.asc|*.gpg|*.pgp|*.torrent|*.sha256|*.sha512|*.md5|SHA256SUMS*|MD5SUMS*)
                continue
                ;;
        esac

        files+=("$basename_f")
    done
    shopt -u nullglob

    if [[ ${#files[@]} -eq 0 ]]; then
        log_warning "No release files found in $release_dir"
        return 0
    fi

    log_info "Found ${#files[@]} files to verify"
    echo ""

    # Check options
    local check_clearnet=true
    local check_i2p=false
    local check_tor=false

    if read_yes_no "Check I2P mirror? (requires I2P running)" "n"; then
        check_i2p=true
    fi

    if read_yes_no "Check Tor mirror? (requires torsocks/Tor)" "n"; then
        check_tor=true
    fi

    echo ""
    echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BOLD}                         DOWNLOAD VERIFICATION RESULTS                      ${NC}"
    echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""

    local total_checks=0
    local passed_checks=0
    local failed_checks=0

    for filename in "${files[@]}"; do
        echo -e "${BOLD}📁 $filename${NC}"

        # Check clearnet primary
        local url="${MIRRORS[clearnet_primary]}/$version/$filename"
        ((total_checks++)) || true
        if verify_url "$url" "curl"; then
            echo -e "   ${GREEN}✓${NC} Clearnet Primary: $url"
            ((passed_checks++)) || true
        else
            echo -e "   ${RED}✗${NC} Clearnet Primary: $url"
            ((failed_checks++)) || true
        fi

        # Check clearnet secondary (skip for source)
        if [[ "$filename" != *"source"* ]]; then
            url="${MIRRORS[clearnet_secondary]}/$version/$filename"
            ((total_checks++)) || true
            if verify_url "$url" "curl"; then
                echo -e "   ${GREEN}✓${NC} Clearnet Secondary: $url"
                ((passed_checks++)) || true
            else
                echo -e "   ${RED}✗${NC} Clearnet Secondary: $url"
                ((failed_checks++)) || true
            fi
        fi

        # Check I2P if enabled (skip for source)
        if [[ "$check_i2p" == true ]] && [[ "$filename" != *"source"* ]]; then
            url="${MIRRORS[i2p]}/$version/$filename"
            ((total_checks++)) || true
            if verify_url "$url" "i2p"; then
                echo -e "   ${GREEN}✓${NC} I2P Mirror: $url"
                ((passed_checks++)) || true
            else
                echo -e "   ${RED}✗${NC} I2P Mirror: $url"
                ((failed_checks++)) || true
            fi
        fi

        # Check Tor if enabled (skip for source)
        if [[ "$check_tor" == true ]] && [[ "$filename" != *"source"* ]]; then
            url="${MIRRORS[tor]}/$version/$filename"
            ((total_checks++)) || true
            if verify_url "$url" "tor"; then
                echo -e "   ${GREEN}✓${NC} Tor Mirror: $url"
                ((passed_checks++)) || true
            else
                echo -e "   ${RED}✗${NC} Tor Mirror: $url"
                ((failed_checks++)) || true
            fi
        fi

        echo ""
    done

    echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BOLD}SUMMARY:${NC} $passed_checks/$total_checks checks passed"

    if [[ $failed_checks -gt 0 ]]; then
        echo -e "${RED}$failed_checks checks FAILED${NC}"
    else
        echo -e "${GREEN}All checks passed!${NC}"
    fi
    echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# -----------------------------------------------------------------------------
# Verify a URL returns 200 status
# -----------------------------------------------------------------------------
verify_url() {
    local url="$1"
    local method="${2:-curl}"
    local timeout=30

    case "$method" in
        curl)
            local status
            status=$(curl -s -o /dev/null -w "%{http_code}" --max-time "$timeout" --head "$url" 2>/dev/null || echo "000")
            [[ "$status" == "200" ]]
            ;;
        i2p)
            # Use I2P HTTP proxy (default port 4444)
            local status
            status=$(curl -s -o /dev/null -w "%{http_code}" --max-time "$timeout" --head \
                --proxy "http://127.0.0.1:4444" "$url" 2>/dev/null || echo "000")
            [[ "$status" == "200" ]]
            ;;
        tor)
            # Use torsocks or Tor SOCKS proxy
            if command -v torsocks &>/dev/null; then
                local status
                status=$(torsocks curl -s -o /dev/null -w "%{http_code}" --max-time "$timeout" --head "$url" 2>/dev/null || echo "000")
                [[ "$status" == "200" ]]
            else
                # Fallback to SOCKS5 proxy
                local status
                status=$(curl -s -o /dev/null -w "%{http_code}" --max-time "$timeout" --head \
                    --proxy "socks5h://127.0.0.1:9050" "$url" 2>/dev/null || echo "000")
                [[ "$status" == "200" ]]
            fi
            ;;
    esac
}

# -----------------------------------------------------------------------------
# Option 5: Full Release Workflow
# -----------------------------------------------------------------------------
do_full_workflow() {
    log_header "Full Release Workflow"
    echo ""
    echo "This will run the complete release deployment process:"
    echo "  1. Create torrents for all release files"
    echo "  2. Push torrents to configured seed hosts"
    echo "  3. Upload files to R2 and generate YAML"
    echo "  4. Verify all download links"
    echo ""

    local release_dir
    release_dir=$(read_directory "Enter release directory (e.g., /srv/mirror/2.10.0)") || return 0

    local dry_run=false
    if read_yes_no "Dry-run mode (show what would be done)?" "n"; then
        dry_run=true
    fi

    echo ""

    if ! read_yes_no "Proceed with full workflow?" "n"; then
        echo "Cancelled."
        return 0
    fi

    echo ""
    local dry_run_opt=""
    [[ "$dry_run" == true ]] && dry_run_opt="--dry-run"

    # Step 1: Create torrents
    log_header "Step 1/4: Creating Torrents"
    "$SCRIPT_DIR/create-torrents.sh" "$release_dir" $dry_run_opt

    # Step 2: Push torrents
    log_header "Step 2/4: Pushing Torrents to Seed Hosts"
    "$SCRIPT_DIR/create-torrents.sh" "$release_dir" --distribute $dry_run_opt

    # Step 3: Generate YAML (uploads to R2)
    if [[ "$dry_run" == true ]]; then
        log_header "Step 3/4: Generate YAML (skipped in dry-run mode)"
        echo "Would run: generate-release-yaml.sh $release_dir"
    else
        log_header "Step 3/4: Generating YAML and Uploading to R2"
        "$SCRIPT_DIR/generate-release-yaml.sh" "$release_dir"
    fi

    # Step 4: Verify downloads
    if [[ "$dry_run" == true ]]; then
        log_header "Step 4/4: Verify Downloads (skipped in dry-run mode)"
        echo "Would verify all download links"
    else
        log_header "Step 4/4: Verifying Downloads"
        echo ""

        # Auto-verify clearnet only in workflow
        local version
        version=$(basename "$release_dir")
        local files=()
        shopt -s nullglob
        for f in "$release_dir"/*; do
            local basename_f
            basename_f=$(basename "$f")
            [[ ! -f "$f" ]] && continue
            case "$basename_f" in
                *.sig|*.asc|*.gpg|*.pgp|*.torrent|*.sha256|*.sha512|*.md5|SHA256SUMS*|MD5SUMS*)
                    continue
                    ;;
            esac
            files+=("$basename_f")
        done
        shopt -u nullglob

        local passed=0
        local failed=0

        for filename in "${files[@]}"; do
            for mirror in "clearnet_primary" "clearnet_secondary"; do
                [[ "$filename" == *"source"* ]] && [[ "$mirror" == "clearnet_secondary" ]] && continue

                local url="${MIRRORS[$mirror]}/$version/$filename"
                if verify_url "$url" "curl"; then
                    echo -e "  ${GREEN}✓${NC} $mirror: $filename"
                    ((passed++)) || true
                else
                    echo -e "  ${RED}✗${NC} $mirror: $filename"
                    ((failed++)) || true
                fi
            done
        done

        echo ""
        if [[ $failed -eq 0 ]]; then
            log_success "All $passed clearnet checks passed!"
        else
            log_warning "$passed passed, $failed failed"
        fi
    fi

    echo ""
    log_header "Workflow Complete!"
    log_success "Release deployment finished for: $release_dir"
}

# -----------------------------------------------------------------------------
# Option 6: Push Custom Torrents
# -----------------------------------------------------------------------------
do_push_custom_torrents() {
    log_header "Push Custom Torrents"
    echo ""
    echo "Push existing .torrent files to configured seed hosts."
    echo "Use this for torrents not created with the create-torrents.sh script."
    echo ""

    local source_path
    echo -en "${CYAN}Enter path to torrent file(s) or directory: ${NC}"
    read -r source_path

    if [[ -z "$source_path" ]]; then
        echo "Cancelled."
        return 0
    fi

    # Expand tilde
    source_path="${source_path/#\~/$HOME}"

    # Collect torrent files
    local torrent_files=()

    if [[ -d "$source_path" ]]; then
        shopt -s nullglob
        for f in "$source_path"/*.torrent; do
            torrent_files+=("$f")
        done
        shopt -u nullglob
    elif [[ -f "$source_path" ]] && [[ "$source_path" == *.torrent ]]; then
        torrent_files+=("$source_path")
    else
        log_error "Not a valid torrent file or directory: $source_path"
        return 1
    fi

    if [[ ${#torrent_files[@]} -eq 0 ]]; then
        log_warning "No .torrent files found"
        return 0
    fi

    log_info "Found ${#torrent_files[@]} torrent file(s):"
    for f in "${torrent_files[@]}"; do
        echo "  - $(basename "$f")"
    done
    echo ""

    # Load SSH config
    local SSH_CONFIG_FILE="$SCRIPT_DIR/ssh.conf"
    local HOSTS_FILE="$SCRIPT_DIR/hosts.txt"

    if [[ ! -f "$HOSTS_FILE" ]]; then
        log_error "Hosts file not found: $HOSTS_FILE"
        return 1
    fi

    # Source SSH config
    local SSH_KEY="" SSH_PORT="22" SSH_USER="" REMOTE_STAGING_DIR="/tmp/i2p-torrents" REMOTE_FINAL_DIR=""
    if [[ -f "$SSH_CONFIG_FILE" ]]; then
        source "$SSH_CONFIG_FILE"
    fi

    local dry_run=false
    if read_yes_no "Dry-run mode?" "n"; then
        dry_run=true
    fi

    if ! read_yes_no "Push torrents to seed hosts?" "y"; then
        echo "Cancelled."
        return 0
    fi

    echo ""

    # Build SSH options
    local ssh_opts=""
    [[ -n "$SSH_KEY" ]] && ssh_opts="-i $SSH_KEY"
    [[ "$SSH_PORT" != "22" ]] && ssh_opts="$ssh_opts -p $SSH_PORT"
    ssh_opts="$ssh_opts -o StrictHostKeyChecking=accept-new -o BatchMode=yes"

    local rsync_ssh_cmd="ssh"
    [[ -n "$SSH_KEY" ]] && rsync_ssh_cmd="$rsync_ssh_cmd -i $SSH_KEY"
    [[ "$SSH_PORT" != "22" ]] && rsync_ssh_cmd="$rsync_ssh_cmd -p $SSH_PORT"
    rsync_ssh_cmd="$rsync_ssh_cmd -o StrictHostKeyChecking=accept-new -o BatchMode=yes"

    local success_count=0
    local fail_count=0

    while IFS= read -r line || [[ -n "$line" ]]; do
        [[ -z "$line" ]] && continue
        [[ "$line" == \#* ]] && continue

        local host
        host=$(echo "$line" | xargs)

        local target
        if [[ -n "$SSH_USER" ]]; then
            target="${SSH_USER}@${host}"
        else
            target="$host"
        fi

        log_info "Syncing to: $target"

        if [[ "$dry_run" == true ]]; then
            echo "  Would rsync ${#torrent_files[@]} files to ${target}:${REMOTE_STAGING_DIR}/"
            if [[ -n "$REMOTE_FINAL_DIR" ]]; then
                echo "  Would sudo mv files to $REMOTE_FINAL_DIR"
            fi
            ((success_count++)) || true
            continue
        fi

        # Create staging directory
        if ! ssh $ssh_opts "$target" "mkdir -p '$REMOTE_STAGING_DIR'" 2>&1; then
            log_error "Failed to create staging directory on $host"
            ((fail_count++)) || true
            continue
        fi

        # Rsync files
        if ! rsync -avz --progress -e "$rsync_ssh_cmd" "${torrent_files[@]}" "${target}:${REMOTE_STAGING_DIR}/" 2>&1; then
            log_error "Failed to rsync to: $host"
            ((fail_count++)) || true
            continue
        fi

        # Move to final directory if configured
        if [[ -n "$REMOTE_FINAL_DIR" ]]; then
            local remote_cmd="sudo mkdir -p '$REMOTE_FINAL_DIR' && sudo mv '$REMOTE_STAGING_DIR'/*.torrent '$REMOTE_FINAL_DIR/' && rmdir '$REMOTE_STAGING_DIR' 2>/dev/null || true"
            if ! ssh $ssh_opts "$target" "$remote_cmd" 2>&1; then
                log_error "Failed to move files to final directory on $host"
                ((fail_count++)) || true
                continue
            fi
        fi

        log_success "Synced to: $host"
        ((success_count++)) || true

    done < "$HOSTS_FILE"

    echo ""
    log_info "Distribution complete: $success_count succeeded, $fail_count failed"
}

# -----------------------------------------------------------------------------
# Usage
# -----------------------------------------------------------------------------
usage() {
    cat << EOF
Usage: $(basename "$0") [options]

I2P Release Management Tools - All-in-One Launcher

Options:
    --menu              Interactive menu mode (default)
    --create <dir>      Create torrents for release directory
    --push <dir>        Push torrents to seed hosts
    --yaml <dir>        Generate YAML for release directory
    --verify <dir>      Verify download links for release
    --full <dir>        Run full release workflow
    --deps              Check dependencies
    --config            View configuration
    -h, --help          Show this help message
    -v, --version       Show version

Examples:
    $(basename "$0")                        # Interactive menu
    $(basename "$0") --create /srv/mirror/2.10.0
    $(basename "$0") --full /srv/mirror/2.10.0
    $(basename "$0") --verify /srv/mirror/2.10.0

Configuration Files:
    $SCRIPT_DIR/hosts.txt   - List of seed hosts
    $SCRIPT_DIR/ssh.conf    - SSH connection settings
EOF
    exit 0
}

# -----------------------------------------------------------------------------
# Command-line mode handlers
# -----------------------------------------------------------------------------
cli_create() {
    local dir="$1"
    [[ ! -d "$dir" ]] && { log_error "Directory not found: $dir"; exit 1; }
    "$SCRIPT_DIR/create-torrents.sh" "$dir"
}

cli_push() {
    local dir="$1"
    [[ ! -d "$dir" ]] && { log_error "Directory not found: $dir"; exit 1; }
    "$SCRIPT_DIR/create-torrents.sh" "$dir" --distribute
}

cli_yaml() {
    local dir="$1"
    [[ ! -d "$dir" ]] && { log_error "Directory not found: $dir"; exit 1; }
    "$SCRIPT_DIR/generate-release-yaml.sh" "$dir"
}

cli_verify() {
    local dir="$1"
    [[ ! -d "$dir" ]] && { log_error "Directory not found: $dir"; exit 1; }

    # Simplified verification for CLI mode
    local version
    version=$(basename "$dir")

    log_info "Verifying downloads for version: $version"
    echo ""

    local files=()
    shopt -s nullglob
    for f in "$dir"/*; do
        local basename_f
        basename_f=$(basename "$f")
        [[ ! -f "$f" ]] && continue
        case "$basename_f" in
            *.sig|*.asc|*.gpg|*.pgp|*.torrent|*.sha256|*.sha512|*.md5|SHA256SUMS*|MD5SUMS*)
                continue
                ;;
        esac
        files+=("$basename_f")
    done
    shopt -u nullglob

    local passed=0
    local failed=0

    for filename in "${files[@]}"; do
        for mirror in "clearnet_primary" "clearnet_secondary"; do
            [[ "$filename" == *"source"* ]] && [[ "$mirror" == "clearnet_secondary" ]] && continue

            local url="${MIRRORS[$mirror]}/$version/$filename"
            if verify_url "$url" "curl"; then
                echo -e "${GREEN}✓${NC} $mirror: $filename"
                ((passed++)) || true
            else
                echo -e "${RED}✗${NC} $mirror: $filename"
                ((failed++)) || true
            fi
        done
    done

    echo ""
    if [[ $failed -eq 0 ]]; then
        log_success "All $passed checks passed!"
    else
        log_error "$passed passed, $failed failed"
        exit 1
    fi
}

cli_full() {
    local dir="$1"
    [[ ! -d "$dir" ]] && { log_error "Directory not found: $dir"; exit 1; }

    log_header "Full Release Workflow: $dir"

    log_header "Step 1/4: Creating Torrents"
    "$SCRIPT_DIR/create-torrents.sh" "$dir"

    log_header "Step 2/4: Pushing Torrents"
    "$SCRIPT_DIR/create-torrents.sh" "$dir" --distribute

    log_header "Step 3/4: Generating YAML"
    "$SCRIPT_DIR/generate-release-yaml.sh" "$dir"

    log_header "Step 4/4: Verifying Downloads"
    cli_verify "$dir"

    log_success "Full workflow complete!"
}

# -----------------------------------------------------------------------------
# Main menu loop
# -----------------------------------------------------------------------------
run_menu() {
    while true; do
        clear
        print_banner
        print_menu

        echo -en "${CYAN}Select option [0-8]: ${NC}"
        read -r choice

        case "$choice" in
            1) do_create_torrents ;;
            2) do_push_torrents ;;
            3) do_generate_yaml ;;
            4) do_verify_downloads ;;
            5) do_full_workflow ;;
            6) do_push_custom_torrents ;;
            7) check_dependencies ;;
            8) view_configuration ;;
            0|q|Q)
                echo ""
                log_info "Goodbye!"
                exit 0
                ;;
            *)
                log_warning "Invalid option: $choice"
                ;;
        esac

        echo ""
        echo -en "${CYAN}Press Enter to continue...${NC}"
        read -r
    done
}

# -----------------------------------------------------------------------------
# Main
# -----------------------------------------------------------------------------
main() {
    # Parse command-line arguments
    if [[ $# -eq 0 ]]; then
        run_menu
        exit 0
    fi

    case "$1" in
        --menu)
            run_menu
            ;;
        --create)
            [[ -z "${2:-}" ]] && { log_error "Missing directory argument"; exit 1; }
            cli_create "$2"
            ;;
        --push)
            [[ -z "${2:-}" ]] && { log_error "Missing directory argument"; exit 1; }
            cli_push "$2"
            ;;
        --yaml)
            [[ -z "${2:-}" ]] && { log_error "Missing directory argument"; exit 1; }
            cli_yaml "$2"
            ;;
        --verify)
            [[ -z "${2:-}" ]] && { log_error "Missing directory argument"; exit 1; }
            cli_verify "$2"
            ;;
        --full)
            [[ -z "${2:-}" ]] && { log_error "Missing directory argument"; exit 1; }
            cli_full "$2"
            ;;
        --deps)
            check_dependencies
            ;;
        --config)
            view_configuration
            ;;
        -h|--help)
            usage
            ;;
        -v|--version)
            echo "i2p-release-tools.sh version $VERSION"
            ;;
        *)
            log_error "Unknown option: $1"
            echo "Use --help for usage information."
            exit 1
            ;;
    esac
}

main "$@"
