#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" APIs of searching cves """

import os
import json
from const import *
from kv import *


def cvesearch():
    '''search KACVs using search-fulltext of cve-search'''
    cve_set = set()

    old_dir = os.getcwd()
    os.chdir(old_dir + "/cve-search")

    for word in get_word_lst():
        cmd = "./bin/search_fulltext.py -q \"linux kernel\"  -q \"" + \
        word + \
        "\" > tmpcves.txt"
        
        os.system(cmd)


        with open("tmpcves.txt", "r") as f:
            for line in f:
                cve_set.add(line)

        os.remove("tmpcves.txt")
    
    os.chdir(old_dir)
    return sorted(list(cve_set))


def cvesearch_linux():
    '''search CVEs in Linux kernel using search-fulltext of cve-search'''
    
    cve_set = set()

    old_dir = os.getcwd()
    os.chdir(old_dir + "/cve-search")
    
    cmd = "./bin/search_fulltext.py -q \"linux kernel\" > tmpcves.txt"
    
    os.system(cmd)


    with open("tmpcves.txt", "r") as f:
        for line in f:
            cve_set.add(line)

    os.remove("tmpcves.txt")
    
    os.chdir(old_dir)
    return sorted(list(cve_set))


def getcveinfos(cve_id_lst):
    '''collect cve info (in json format)'''
    cveinfo_lst = []
    
    old_dir = os.getcwd()
    os.chdir(old_dir + "/cve-search")
    
    para_lst = ["-c " + cve_id.strip() for cve_id in cve_id_lst]
    paras_str = " ".join(para_lst)
    cmd = "./bin/search.py " + paras_str + " -o json > cve.json"
    os.system(cmd)

    with open("cve.json", "r") as f:
        for line in f:
            cveinfo = json.loads(line)
            cveinfo_lst.append(cveinfo)
    os.remove("cve.json")

    os.chdir(old_dir)
    return cveinfo_lst