#!/bin/bash
set -euo pipefail

# Integration test for pip-witness
# Tests the full pipeline: build image -> install test package -> verify attestation

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ATTESTATION_DIR="${SCRIPT_DIR}/attestations"
PASS=0
FAIL=0

pass() { echo "  PASS: $1"; ((PASS++)); }
fail() { echo "  FAIL: $1"; ((FAIL++)); }

echo "=========================================="
echo "  pip-witness integration tests"
echo "=========================================="

# Clean previous attestations
rm -rf "${ATTESTATION_DIR}"
mkdir -p "${ATTESTATION_DIR}"

# --- Test 1: Build the image ---
echo ""
echo "[Test 1] Building pip-witness image..."
"${SCRIPT_DIR}/pip-witness" --build
if [ $? -eq 0 ]; then
    pass "Image built successfully"
else
    fail "Image build failed"
    exit 1
fi

# --- Test 2: Static analysis of test package ---
echo ""
echo "[Test 2] Static analysis of evil-package..."
docker run --rm \
    -v "${SCRIPT_DIR}/test-packages/evil-package:/pkg" \
    -v "${ATTESTATION_DIR}:/attestations" \
    --entrypoint python3 \
    pip-witness:latest \
    /pip-witness/analyze.py /pkg evil-test-package > "${ATTESTATION_DIR}/static-analysis.json" 2>&1

if [ -f "${ATTESTATION_DIR}/static-analysis.json" ]; then
    # Check that static analysis found suspicious patterns
    if python3 -c "
import json, sys
with open('${ATTESTATION_DIR}/static-analysis.json') as f:
    data = json.load(f)
score = data.get('risk_score', 0)
level = data.get('risk_level', 'UNKNOWN')
findings = sum(len(a.get('findings', [])) for a in data.get('archives', []))
print(f'  Risk score: {score}, Level: {level}, Findings: {findings}')
sys.exit(0 if score > 0 else 1)
" 2>/dev/null; then
        pass "Static analysis detected suspicious patterns"
    else
        fail "Static analysis did not detect suspicious patterns"
    fi
else
    fail "Static analysis output missing"
fi

# --- Test 3: Traced install of evil-package ---
echo ""
echo "[Test 3] Traced install of evil-package (this exercises the full pipeline)..."
docker run --rm \
    --cap-add=SYS_PTRACE \
    --security-opt seccomp=unconfined \
    -v "${SCRIPT_DIR}/test-packages/evil-package:/workspace/evil-package" \
    -v "${ATTESTATION_DIR}:/attestations" \
    -e "STEP_NAME=test-evil-pkg" \
    pip-witness:latest \
    "/workspace/evil-package"

# Check that attestation was produced
ATTESTATION_FILES=(${ATTESTATION_DIR}/test-evil-pkg-*.json)
if [ -f "${ATTESTATION_FILES[0]}" ]; then
    pass "Attestation envelope produced"
else
    fail "No attestation envelope found"
fi

# --- Test 4: Verify attestation content ---
echo ""
echo "[Test 4] Verifying attestation content..."
if [ -f "${ATTESTATION_FILES[0]}" ]; then
    python3 -c "
import json, base64, sys

with open('${ATTESTATION_FILES[0]}') as f:
    envelope = json.load(f)

# Check DSSE envelope structure
assert 'payload' in envelope, 'Missing DSSE payload'
assert 'signatures' in envelope, 'Missing DSSE signatures'
print('  DSSE envelope: valid')

# Decode payload
payload = json.loads(base64.b64decode(envelope['payload']))
predicate = payload.get('predicate', {})

# Check for command-run attestation with process traces
found_commandrun = False
for key, val in predicate.items():
    if 'command-run' in key.lower():
        found_commandrun = True
        processes = val.get('processes', [])
        print(f'  Command-run: {len(processes)} traced processes')

        # Check for network activity in any process
        has_network = any(p.get('network') for p in processes)
        if has_network:
            print('  Network activity: DETECTED')
        else:
            print('  Network activity: not captured (may need kernel support)')

        # Check for file opens
        total_files = sum(len(p.get('openedfiles', {})) for p in processes)
        print(f'  Files opened: {total_files}')

        # Check for subprocess spawning
        if len(processes) > 1:
            print(f'  Subprocesses spawned: {len(processes) - 1}')

if found_commandrun:
    print('  VERDICT: Attestation contains process trace data')
else:
    print('  WARNING: No command-run attestation found')

# Check for pip-install attestation
found_pip = False
for key in predicate:
    if 'pip-install' in key.lower():
        found_pip = True
        pip_data = predicate[key]
        print(f'  Pip version: {pip_data.get(\"pipVersion\", \"unknown\")}')
        print(f'  Packages installed: {pip_data.get(\"totalInstalled\", 0)}')
        setup_analyses = pip_data.get('setupPyAnalysis', [])
        if setup_analyses:
            print(f'  Setup.py analyses: {len(setup_analyses)}')

if found_pip:
    print('  Pip-install attestor: active')
else:
    print('  Pip-install attestor: not present (check attestation flags)')
" 2>&1 && pass "Attestation content valid" || fail "Attestation content invalid"
else
    fail "No attestation to verify"
fi

# --- Test 5: Install a real package from PyPI ---
echo ""
echo "[Test 5] Traced install of a real PyPI package (httpie - has dependencies)..."
"${SCRIPT_DIR}/pip-witness" httpie 2>&1 | tail -20

REAL_ATTESTATIONS=(${ATTESTATION_DIR}/pip-install-httpie-*.json)
if [ -f "${REAL_ATTESTATIONS[0]}" ]; then
    pass "Real package attestation produced"
else
    fail "Real package attestation missing"
fi

# Summary
echo ""
echo "=========================================="
echo "  Results: ${PASS} passed, ${FAIL} failed"
echo "=========================================="
echo "  Attestation files:"
ls -la "${ATTESTATION_DIR}/"

exit ${FAIL}
