#!/usr/bin/python3

###############################################################################
##
## Functions for downloading and parsing Common Vulnerability DB data
##
###############################################################################

import logging, sys
import re
import urllib.request
import datetime

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

def correctCVE(cve_id):
    cve_id_new = cve_id
    if cve_id == 2116:
        cve_id_new = 1921
    
    return cve_id_new

## Get details of given CVE entry from NIST DB - we use cve-search and mongodb
def fetchCVE(cve_id, client):

    logging.info('Fetching CVE: ' + cve_id + '\n')

    #Make this subtitution for some reason
    cve_id = re.sub('^CAN','CVE',cve_id)
    cve_id = correctCVE(cve_id)
    ##
    ## get CVE Scores from db
    ##
    db = client.cvedb
    collection = db.cves
    cve = collection.find_one({"id": cve_id})

    if cve == '':
        logging.warning('CVE not found in mongodb')


#    print(cve)
    return cve


    # Check for error pages: referenced but unpublished CVEs :-/
###############################################################################

## Get CVE severity rating and report date, and return
## (date base-score impact-score exploit-score)
def parseCVE(cve_id, cve):
    #use worst case info as defaults
    cve_date = datetime.datetime.now()
    cve_base = 10
    cve_impact = 10
    cve_exploit = 10

    try:
        if cve == None:
            # No details means we assume worst-case (highest score, recent bug)
            print('CVE' + str(cve_id) + ' not yet reported, getting default values')
            return(cve_date, cve_base, cve_impact, cve_exploit)
        else:
            cve_date = cve['Published']
            cve_base = cve['cvss']
    except KeyError:
        print('CVE ' + cve_id + ' not parsed correctly')

    return(cve_date, cve_base, cve_impact, cve_exploit)
