#!/bin/bash

# DonkTool Penetration Testing Tools Installation Script (Fixed Version)
# This script handles modern macOS environment constraints

echo "🔧 Installing DonkTool Penetration Testing Tools (Fixed Version)..."
echo "=================================================================="

# Check if Homebrew is installed
if ! command -v brew &> /dev/null; then
    echo "❌ Homebrew not found. Installing Homebrew first..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

# Update Homebrew
echo "📦 Updating Homebrew..."
brew update

# Install core Homebrew tools
echo "📦 Installing core penetration testing tools..."
brew install nmap nikto sqlmap gobuster

# Install DoS/Stress testing tools (AUTHORIZED USE ONLY)
echo "⚠️  Installing DoS/Stress testing tools (AUTHORIZED USE ONLY)..."
echo "These tools are for defensive testing of systems you own or have permission to test."
brew install wrk hping

# Try to install dirb from alternative sources
echo "📦 Installing dirb (directory brute-forcer)..."
if ! command -v dirb &> /dev/null; then
    # Try installing from source since it's not in Homebrew
    cd /tmp
    if command -v git &> /dev/null && command -v make &> /dev/null; then
        echo "Installing dirb from source..."
        git clone https://github.com/v0re/dirb.git
        cd dirb
        chmod +x configure
        ./configure && make
        echo "⚠️  Run 'sudo make install' to complete dirb installation"
        cd ..
        rm -rf dirb
    else
        echo "⚠️  Cannot compile dirb - missing git or make"
    fi
else
    echo "✅ dirb already installed"
fi

# Check Go version and install if needed
echo "📦 Checking Go installation..."
if ! command -v go &> /dev/null; then
    echo "Installing Go..."
    brew install go
else
    GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    echo "Current Go version: $GO_VERSION"
    
    # Check if Go version is compatible (needs 1.21+)
    if [[ "$GO_VERSION" < "1.21" ]]; then
        echo "⚠️  Go version too old. Updating Go..."
        brew upgrade go
    fi
fi

# Set Go environment
export PATH=$PATH:$(go env GOPATH)/bin
echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.zshrc

# Install Go-based tools with fallback to older versions
echo "🚀 Installing Go-based security tools..."

# Install FFuF (this one worked in your output)
echo "Installing FFuF (web fuzzer)..."
go install github.com/ffuf/ffuf@latest

# Install Nuclei with version fallback
echo "Installing Nuclei (vulnerability scanner)..."
if ! go install github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest 2>/dev/null; then
    echo "Trying older Nuclei version..."
    go install github.com/projectdiscovery/nuclei/v2/cmd/nuclei@latest
fi

# Install HTTPx with version fallback
echo "Installing HTTPx (HTTP probe)..."
if ! go install github.com/projectdiscovery/httpx/cmd/httpx@latest 2>/dev/null; then
    echo "Trying to install HTTPx from specific version..."
    go install github.com/projectdiscovery/httpx/cmd/httpx@v1.6.8
fi

# Install Subfinder with version fallback
echo "Installing Subfinder (subdomain enumeration)..."
if ! go install github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest 2>/dev/null; then
    echo "Trying older Subfinder version..."
    go install github.com/projectdiscovery/subfinder/v2/cmd/subfinder@v2.6.6
fi

# Install Katana with version fallback
echo "Installing Katana (web crawler)..."
if ! go install github.com/projectdiscovery/katana/cmd/katana@latest 2>/dev/null; then
    echo "Trying older Katana version..."
    go install github.com/projectdiscovery/katana/cmd/katana@v1.0.5
fi

# Install Python tools using pipx (recommended for modern macOS)
echo "🐍 Installing Python-based security tools..."

# Install pipx if not present
if ! command -v pipx &> /dev/null; then
    echo "Installing pipx for Python package management..."
    brew install pipx
    pipx ensurepath
fi

# Install Python tools with pipx
echo "Installing SSLyze (SSL/TLS analyzer)..."
pipx install sslyze

echo "Installing Dirsearch (web path scanner)..."
pipx install dirsearch

echo "Installing Wfuzz (web fuzzer)..."
pipx install wfuzz

# Install slowhttptest for DoS testing (manual compilation)
echo "🔧 Installing slowhttptest (Slowloris testing)..."
if ! command -v slowhttptest &> /dev/null; then
    cd /tmp
    if command -v git &> /dev/null; then
        git clone https://github.com/shekyan/slowhttptest.git
        cd slowhttptest
        if command -v make &> /dev/null; then
            chmod +x configure
            ./configure && make
            echo "⚠️  Run 'sudo make install' to complete slowhttptest installation"
            echo "Or manually copy 'slowhttptest' binary to /usr/local/bin/"
        else
            echo "⚠️  make not found - install Xcode Command Line Tools: xcode-select --install"
        fi
        cd ..
        rm -rf slowhttptest
    else
        echo "⚠️  git not found - cannot install slowhttptest"
    fi
else
    echo "✅ slowhttptest already installed"
fi

# Install advanced DoS testing tools
echo "🚨 Installing advanced DoS testing tools (AUTHORIZED USE ONLY)..."
echo "These tools require explicit authorization and should only be used on systems you own."

# Install HULK (Python-based)
echo "Installing HULK HTTP flood tool..."
if ! command -v hulk &> /dev/null; then
    cd /tmp
    git clone https://github.com/grafov/hulk.git 2>/dev/null || echo "Note: HULK may need manual installation"
fi

# Install GoldenEye (Python-based)
echo "Installing GoldenEye Layer 7 attack tool..."
if ! command -v goldeneye &> /dev/null; then
    cd /tmp
    git clone https://github.com/jseidl/GoldenEye.git 2>/dev/null || echo "Note: GoldenEye may need manual installation"
fi

# Install additional stress testing tools via homebrew alternatives
echo "Installing additional stress testing tools..."
brew install siege 2>/dev/null || echo "⚠️  Siege not available via homebrew"
brew install vegeta 2>/dev/null || echo "⚠️  Vegeta not available via homebrew"

# Install Artillery.io for load testing
echo "Installing Artillery.io load testing framework..."
if command -v npm &> /dev/null; then
    npm install -g artillery@latest 2>/dev/null || echo "⚠️  Artillery install failed - may need manual installation"
else
    echo "⚠️  npm not found - cannot install Artillery.io"
fi

# Install iPerf3 for network testing
echo "Installing iPerf3 network testing tool..."
brew install iperf3 2>/dev/null || echo "⚠️  iPerf3 not available via homebrew"

# Install Rust tools (optional)
echo "🦀 Installing Rust-based tools (optional)..."
if command -v cargo &> /dev/null; then
    echo "Installing Feroxbuster (recursive content discovery)..."
    cargo install feroxbuster
else
    echo "⚠️  Rust not found. Install with: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
    echo "Then run: cargo install feroxbuster"
fi

# Update tool templates and paths
echo "📋 Updating tool templates and configurations..."

# Reload shell environment
source ~/.zshrc 2>/dev/null || true

# Update Nuclei templates if nuclei is available
if command -v nuclei &> /dev/null; then
    echo "Updating Nuclei templates..."
    nuclei -update-templates -silent
else
    echo "⚠️  Nuclei not found in PATH. You may need to restart your terminal or run:"
    echo "export PATH=\$PATH:\$(go env GOPATH)/bin"
fi

# Create tool verification script
echo "📝 Creating tool verification script..."
cat > ~/verify-pentest-tools.sh << 'EOF'
#!/bin/bash
echo "DonkTool Penetration Testing Tools Verification"
echo "============================================"

# Core tools
echo "Core Tools:"
command -v nmap >/dev/null && echo "✅ nmap" || echo "❌ nmap"
command -v nikto >/dev/null && echo "✅ nikto" || echo "❌ nikto"
command -v sqlmap >/dev/null && echo "✅ sqlmap" || echo "❌ sqlmap"
command -v gobuster >/dev/null && echo "✅ gobuster" || echo "❌ gobuster"
command -v dirb >/dev/null && echo "✅ dirb" || echo "❌ dirb"

# Go tools
echo "\nGo-based Tools:"
command -v nuclei >/dev/null && echo "✅ nuclei" || echo "❌ nuclei"
command -v httpx >/dev/null && echo "✅ httpx" || echo "❌ httpx"
command -v subfinder >/dev/null && echo "✅ subfinder" || echo "❌ subfinder"
command -v ffuf >/dev/null && echo "✅ ffuf" || echo "❌ ffuf"

# Python tools
echo "\nPython Tools:"
command -v sslyze >/dev/null && echo "✅ sslyze" || echo "❌ sslyze"
command -v dirsearch >/dev/null && echo "✅ dirsearch" || echo "❌ dirsearch"
command -v wfuzz >/dev/null && echo "✅ wfuzz" || echo "❌ wfuzz"

# DoS/Stress testing tools
echo "\nDoS/Stress Testing Tools:"
command -v wrk >/dev/null && echo "✅ wrk" || echo "❌ wrk"
command -v hping3 >/dev/null && echo "✅ hping3" || echo "❌ hping3"
command -v slowhttptest >/dev/null && echo "✅ slowhttptest" || echo "❌ slowhttptest"
command -v siege >/dev/null && echo "✅ siege" || echo "❌ siege"
command -v iperf3 >/dev/null && echo "✅ iperf3" || echo "❌ iperf3"
command -v artillery >/dev/null && echo "✅ artillery" || echo "❌ artillery"

echo "\n📊 Verification complete!"
EOF

chmod +x ~/verify-pentest-tools.sh
echo "Created verification script at ~/verify-pentest-tools.sh"

# Verify installations
echo ""
echo "✅ Installation Summary:"
echo "======================="

check_tool() {
    if command -v $1 &> /dev/null; then
        VERSION=$($1 --version 2>/dev/null | head -1 || echo "unknown")
        echo "✅ $1 - Installed ($VERSION)"
    else
        echo "❌ $1 - Not found in PATH"
    fi
}

echo ""
echo "Core Tools:"
check_tool "nmap"
check_tool "nikto"
check_tool "sqlmap"
check_tool "gobuster"
check_tool "dirb"

echo ""
echo "Modern Go Tools:"
check_tool "nuclei"
check_tool "httpx"
check_tool "subfinder"
check_tool "ffuf"
check_tool "katana"

echo ""
echo "Python Tools:"
check_tool "sslyze"
check_tool "dirsearch"
check_tool "wfuzz"

echo ""
echo "DoS/Stress Testing Tools:"
check_tool "wrk"
check_tool "hping3"
check_tool "slowhttptest"

echo ""
echo "Optional Tools:"
check_tool "feroxbuster"

echo ""
echo "🎉 Installation complete!"
echo ""
echo "⚠️  IMPORTANT ETHICAL NOTICE:"
echo "===================="
echo "DoS/Stress testing tools (wrk, hping3, slowhttptest) are included for:"
echo "• Testing systems you own"
echo "• Authorized penetration testing with written permission"
echo "• Defensive security assessment of your infrastructure"
echo ""
echo "❌ DO NOT use these tools for:"
echo "• Attacking systems you don't own"
echo "• Unauthorized testing"
echo "• Malicious activities"
echo ""
echo "Unauthorized DoS attacks are illegal and can result in criminal charges."
echo "Always ensure you have explicit permission before testing any system."
echo ""
echo "🔧 Troubleshooting:"
echo "=================="
echo "If tools are not found in PATH after installation:"
echo "1. Restart your terminal"
echo "2. Run: source ~/.zshrc"
echo "3. Add to PATH manually: export PATH=\$PATH:\$(go env GOPATH)/bin"
echo ""
echo "For Python tools, ensure pipx is in PATH:"
echo "pipx ensurepath"
echo ""
echo "📚 Tool Documentation:"
echo "• Nuclei: https://github.com/projectdiscovery/nuclei"
echo "• HTTPx: https://github.com/projectdiscovery/httpx"
echo "• Subfinder: https://github.com/projectdiscovery/subfinder"
echo "• FFuF: https://github.com/ffuf/ffuf"
echo "• SSLyze: https://github.com/nabla-c0d3/sslyze"
echo "• Wrk: https://github.com/wg/wrk"
echo "• slowhttptest: https://github.com/shekyan/slowhttptest"
echo ""
echo "🔐 DonkTool now has access to professional-grade penetration testing tools!"
echo "\n🎯 Available Testing Modules:"
echo "• Web Application Security Testing"
echo "• DoS/Stress Testing (AUTHORIZED USE ONLY)"
echo "• Network Vulnerability Scanning"
echo "• CVE Database Integration"
echo "\n🚀 Getting Started:"
echo "1. Start DonkTool in Xcode"
echo "2. Navigate to the desired testing module"
echo "3. Ensure you have written authorization for target systems"
echo "4. Run verification script: ~/verify-pentest-tools.sh"
echo "\n⚠️  FINAL REMINDER:"
echo "DoS testing tools are for defensive security assessment only."
echo "Unauthorized testing is illegal and can result in criminal charges."
echo "Always ensure proper authorization before testing any system."