#!/usr/bin/env python3
"""Takes JSON output and creates a vulnerability roundup issue.

Feed the output of `vulnix --json` into this script to create the issue
description.
"""

import urllib.parse
import argparse
import json
import sys


def parse(json_file):
    if json_file:
        return json.load(json_file)
    return json.load(sys.stdin)


def fmt(pkgs):
    for pkg in sorted(pkgs, key=lambda p: p['name']):
        name = pkg['name']
        quotedname = urllib.parse.quote_plus(pkg['pname'])
        search = 'https://search.nix.gsc.io/?q={}&i=fosho&repos=nixos-nixpkgs'.\
            format(quotedname)
        files = 'https://github.com/NixOS/nixpkgs/search?utf8=%E2%9C%93&q={}+in%3Apath&type=Code'.\
            format(quotedname)
        print("### {name} ([search]({search}), [files]({files}))".\
              format(name=name, search=search, files=files))
        cves = ("[{}]({})".format(
            cve, "https://web.nvd.nist.gov/view/vuln/detail?vulnId="+cve)
            for cve in sorted(pkg['affected_by']))
        for cve in cves:
            print(' - [ ] {}'.format(cve))
        print()

def main():
    a = argparse.ArgumentParser(description=__doc__)
    a.add_argument('VULNIX_JSON', nargs='?', type=argparse.FileType('r'),
                   help='vulnix json output (file or "-")')
    args = a.parse_args()
    fmt(parse(args.VULNIX_JSON))


if __name__ == '__main__':
    main()
