#!/usr/bin/env bash
# Oracle solution for sec-006-dependency-vulnerability-check
set -euo pipefail

WORKSPACE="${1:-workspace}"

python3 -c "
import json
from packaging.version import Version

with open('$WORKSPACE/requirements.txt') as f:
    deps = {}
    for line in f:
        line = line.strip()
        if '==' in line:
            pkg, ver = line.split('==')
            deps[pkg.strip()] = ver.strip()

with open('$WORKSPACE/vuln_database.json') as f:
    vulns = json.load(f)

audit = []
for v in vulns:
    pkg = v['package']
    if pkg in deps:
        installed = Version(deps[pkg])
        affected_from = Version(v['affected_from'])
        fixed = Version(v['fixed_version'])
        if affected_from <= installed < fixed:
            audit.append({
                'package': pkg,
                'installed_version': deps[pkg],
                'cve_id': v['cve_id'],
                'severity': v['severity'],
                'fixed_version': v['fixed_version'],
                'description': v['description']
            })

with open('$WORKSPACE/dependency_audit.json', 'w') as f:
    json.dump(audit, f, indent=2)
"

echo "Solution written to $WORKSPACE/dependency_audit.json"
