#!/usr/bin/env python3
"""
Web Application Enumeration Example

Demonstrates:
- Directory enumeration with gobuster
- Parallel scanning (directories + nikto)
- Background execution
- Session monitoring

Usage:
    python web_enum.py <url>
    
Example:
    python web_enum.py http://192.168.1.100
"""

import asyncio
import sys
from pentest_mcp_server import PentestMCPServer


async def main():
    if len(sys.argv) < 2:
        print("Usage: python web_enum.py <url>")
        print("Example: python web_enum.py http://192.168.1.100")
        sys.exit(1)
    
    target_url = sys.argv[1]
    server = PentestMCPServer()
    
    try:
        print(f"[*] Starting web application enumeration of {target_url}")
        print("[*] This will run multiple tools in parallel\n")
        
        # Create sessions for different tools
        sessions = {
            "gobuster": "Directory enumeration",
            "nikto": "Vulnerability scanning"
        }
        
        print("[+] Creating sessions...")
        for session_id, description in sessions.items():
            result = await server._handle_create_session({
                "session_id": session_id
            })
            if result["status"] == "created":
                print(f"  ✓ {session_id}: {description}")
            else:
                print(f"  ✗ Failed to create {session_id}")
                return
        
        print()
        
        # Start gobuster in foreground (with trigger)
        print("[*] Starting directory enumeration with gobuster...")
        gobuster_result = await server._handle_execute({
            "session_id": "gobuster",
            "command": f"gobuster dir -u {target_url} -w /usr/share/wordlists/dirb/common.txt -q",
            "triggers": [
                {"type": "regex", "pattern": "Finished", "name": "gobuster_done"},
                {"type": "timeout", "timeout_seconds": 300}
            ],
            "max_timeout": 300
        })
        
        if gobuster_result["status"] == "trigger_matched":
            print(f"[+] Gobuster completed in {gobuster_result['execution_time']:.2f} seconds\n")
            
            # Parse gobuster output
            print("[*] Found directories and files:")
            print("-" * 60)
            
            output_lines = gobuster_result["output"].split('\n')
            findings = []
            
            for line in output_lines:
                if line.strip().startswith('/'):
                    findings.append(line.strip())
            
            if findings:
                for finding in findings[:20]:  # Show first 20
                    print(f"  {finding}")
                
                if len(findings) > 20:
                    print(f"  ... and {len(findings) - 20} more findings")
            else:
                print("  No directories or files found")
            
            print("-" * 60 + "\n")
        else:
            print(f"[-] Gobuster failed or timed out\n")
        
        # Start nikto in background
        print("[*] Starting nikto vulnerability scan (background)...")
        nikto_result = await server._handle_execute({
            "session_id": "nikto",
            "command": f"nikto -h {target_url} -output /tmp/nikto_results.txt",
            "background": True
        })
        
        if nikto_result["status"] == "background":
            print("[+] Nikto scan started in background")
            print("[*] You can check progress with read_output tool")
        
        print()
        
        # List all active sessions
        print("[*] Active sessions:")
        list_result = await server._handle_list_sessions({})
        
        if list_result["status"] == "success":
            for session in list_result["sessions"]:
                print(f"  - {session['session_id']}: {session['status']}")
        
        print()
        
        # Wait a bit and check nikto progress
        print("[*] Waiting 5 seconds to check nikto progress...")
        await asyncio.sleep(5)
        
        nikto_output = await server._handle_read_output({
            "session_id": "nikto",
            "lines": 30
        })
        
        if nikto_output["status"] == "success":
            print("[*] Nikto progress (last 30 lines):")
            print("-" * 60)
            output_lines = nikto_output["output"].split('\n')
            for line in output_lines[-30:]:
                if line.strip():
                    print(f"  {line}")
            print("-" * 60)
        
        print("\n[!] Note: Nikto is still running in the background")
        print("[!] Use read_output or wait for completion to get full results")
        
    except Exception as e:
        print(f"[-] Error: {e}")
    
    finally:
        # Cleanup
        print("\n[*] Cleaning up sessions...")
        for session_id in sessions.keys():
            cleanup_result = await server._handle_kill_session({
                "session_id": session_id
            })
            if cleanup_result["status"] == "killed":
                print(f"  ✓ {session_id} terminated")
        
        await server.shutdown()
        print("[+] Done!")


if __name__ == "__main__":
    asyncio.run(main())
