#!/usr/bin/python

import urllib
import urllib2
from optparse import OptionParser
import json
import os.path
import time
import re
from datetime import datetime, timedelta

import sys

BASEurl = "https://api.xforce.ibmcloud.com/"

sys.path.append('./')
import iprep_conf as IC

yesterday = datetime.now() - timedelta(days=1)
YEST = yesterday.strftime('20%y-%m-%dT00:00:00Z')


headers = {"Authorization": "Basic %s " % IC.xfex_cred,
		   "Accept": "application/json",
		   'User-Agent': 'Mozilla 5.0'}

def getPAM(text):
	furl = BASEurl + "signatures/fulltext?q=%s" % text.strip()
	
	request = urllib2.Request(furl, None, headers)
	data = urllib2.urlopen(request)
	data2 = json.loads(data.read())
	return data2["rows"][0]["pamid"].strip()

def getXFD_fromCVE(cve):
	furl = BASEurl + "vulnerabilities/search/%s" % cve.strip()
	
	request = urllib2.Request(furl, None, headers)
	try:
		data = urllib2.urlopen(request)
		data2 = json.loads(data.read())
		return data2[0]["xfdbid"]
	except:
		return "Not found"

def getXFD(pamid):
	furl = BASEurl + "signatures/%s" % pamid
	
	request = urllib2.Request(furl, None, headers)
	data = urllib2.urlopen(request)
	data2 = json.loads(data.read())
	return data2["protects_against"]["xfdbid"]

def getFull(xfid):
	if xfid == "Not found":
		return xfid
	furl = BASEurl + "vulnerabilities/%s" % xfid
	
	request = urllib2.Request(furl, None, headers)
	data = urllib2.urlopen(request)
	data2 = json.loads(data.read())
	list = []
	return [data2[u"description"], data2[u"risk_level"], data2[u"platforms_affected"], data2[u"stdcode"]]