#!/usr/bin/env python
import json
import colorama
import sys
from termcolor import colored
from tabulate import tabulate

'''
Quick script to format the result of a YARN Audit JSON report:
    yarn audit --json > yarn-audit.json
    python generate-report-yarn.py yarn-audit.json

Dependencies:
    pip install tabulate colorama termcolor
'''


def get_color(severity):
    if severity in ["HIGH", "CRITICAL"]:
        severity_color = "red"
    elif severity in ["MEDIUM", "MODERATE"]:
        severity_color = "yellow"
    elif severity == "LOW":
        severity_color = "cyan"
    else:
        severity_color = "white"
    return severity_color


report = sys.argv[1]
colorama.init()
table_rows = []
with open(report) as f:
    content = f.read()
for entry in content.splitlines():
    v = json.loads(entry)
    if v["type"] == "auditAdvisory":
        mod_name = v["data"]["advisory"]["module_name"]
        severity = v["data"]["advisory"]["severity"].upper()
        if len(v["data"]["advisory"]["cves"]) > 0:
            cves = ",".join(v["data"]["advisory"]["cves"])
        else:
            cves = "NONE"
        severity_color = get_color(severity)
        severity = colored(f"{severity}", severity_color, attrs=["bold"])
        table_rows.append([severity, mod_name, cves])
tempo = []
table_rows_depuplicated = []
for row in table_rows:
    k = ""
    for val in row:
        k += val.upper().strip()
    if k not in tempo:
        tempo.append(k)
        table_rows_depuplicated.append(row)
table_rows_depuplicated.sort()
print(colored("[+] Vulnerabilities:", "yellow"))
table_headers = ["Severity", "Module name", "CVE"]
print(tabulate(table_rows_depuplicated, headers=table_headers))
