# build_obfuscated_package.py - Script pour créer un package Python obfusqué
"""
Création d'un package Python avec code obfusqué pour la distribution client.
Utilise PyArmor pour protéger le code source.
"""

import os
import subprocess
import sys
import shutil
from pathlib import Path

def install_pyarmor():
    """Installer PyArmor si nécessaire."""
    try:
        import pyarmor
        print("✅ PyArmor déjà installé")
        return True
    except ImportError:
        print("📦 Installation de PyArmor...")
        result = subprocess.run([sys.executable, "-m", "pip", "install", "pyarmor"], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ PyArmor installé avec succès")
            return True
        else:
            print("❌ Erreur lors de l'installation de PyArmor:")
            print(result.stderr)
            return False

def obfuscate_code():
    """Obfusquer le code Python avec PyArmor."""
    
    # Nettoyer les anciens builds
    if Path("dist_obf").exists():
        shutil.rmtree("dist_obf")
    
    # Configuration PyArmor
    armor_commands = [
        # Générer les fichiers obfusqués
        ["python", "-m", "pyarmor", "gen", "--output", "dist_obf", 
         "--recursive", "--exclude", "__pycache__", "--exclude", "*.pyc",
         "web_sentinel/"],
    ]
    
    for cmd in armor_commands:
        print(f"🔐 Exécution: {' '.join(cmd)}")
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            print("❌ Erreur PyArmor:")
            print(result.stderr)
            return False
    
    print("✅ Code obfusqué créé dans dist_obf/")
    return True

def build_wheel():
    """Construire le package wheel avec code obfusqué."""
    
    # Copier les fichiers nécessaires dans dist_obf
    files_to_copy = [
        "setup.py",
        "requirements.txt", 
        "README.md",
        "MANIFEST.in"
    ]
    
    for file in files_to_copy:
        if Path(file).exists():
            shutil.copy2(file, "dist_obf/")
    
    # Construire le package
    build_cmd = [sys.executable, "setup.py", "bdist_wheel"]
    
    os.chdir("dist_obf")
    result = subprocess.run(build_cmd, capture_output=True, text=True)
    os.chdir("..")
    
    if result.returncode == 0:
        print("✅ Package wheel créé avec succès")
        
        # Copier le wheel dans le dossier principal
        wheel_files = list(Path("dist_obf/dist").glob("*.whl"))
        if wheel_files:
            final_wheel = Path("dist") / wheel_files[0].name
            final_wheel.parent.mkdir(exist_ok=True)
            shutil.copy2(wheel_files[0], final_wheel)
            print(f"📦 Package final: {final_wheel}")
            
        return True
    else:
        print("❌ Erreur lors de la construction:")
        print(result.stderr)
        return False

def create_installation_guide():
    """Créer un guide d'installation pour les clients."""
    
    guide = """# Guide d'installation Web Sentinel Client

## Installation

```bash
# Installation depuis le package wheel
pip install dist/web_sentinel_client-1.0.0-py3-none-any.whl

# OU installation depuis PyPI (si publié)
pip install web-sentinel-client
```

## Usage CLI

```bash
# Scan basic
web-sentinel example.com

# Scan avec options avancées  
web-sentinel example.com --json --modules headers tls --json-report report.json

# Scan avec tests invasifs (licence requise)
web-sentinel example.com --allow-invasive --html-report report.html

# Analyse de code source (licence PRO+)
web-sentinel example.com --source-path ./src --source-languages php python
```

## Usage GUI

```bash
# Lancer l'interface graphique
web-sentinel-gui
```

## Configuration

Le client stocke sa configuration dans:
- Windows: `%USERPROFILE%\\.web-sentinel\\`
- Linux/Mac: `~/.web-sentinel/`

Fichiers:
- `history.json`: Historique des scans
- `web-sentinel.log`: Logs de l'application
- `config.json`: Configuration utilisateur

## Support

Pour toute question ou support technique, contactez:
- Email: support@web-sentinel.com  
- Documentation: https://docs.web-sentinel.com
"""
    
    with open("CLIENT_INSTALL_GUIDE.md", "w", encoding="utf-8") as f:
        f.write(guide)
    
    print("✅ Guide d'installation créé: CLIENT_INSTALL_GUIDE.md")

def main():
    """Point d'entrée principal."""
    print("🚀 Construction du package client obfusqué...")
    
    if not install_pyarmor():
        return False
    
    if not obfuscate_code():
        return False
    
    if not build_wheel():
        return False
    
    create_installation_guide()
    
    print("\n🎉 Package client prêt pour distribution!")
    print("📋 Fichiers générés:")
    print("   - dist/web_sentinel_client-*.whl (package Python)")
    print("   - CLIENT_INSTALL_GUIDE.md (guide d'installation)")
    print("\n💡 Les clients peuvent installer avec:")
    print("   pip install dist/web_sentinel_client-*.whl")
    
    return True

if __name__ == "__main__":
    main()