import re

def CVSS2deb(cvss):
    cvss = float(cvss)
    if cvss < 3.4:
        return "low"
    elif 3.4 < cvss < 6.7:
        return "medium"
    else:
        return "high"


def suite2tag(suite):
    return {
        "potato": "1",
        "woody": "2",
        "sarge": "3",
        "etch": "4",
        "lenny": "5",
        "squeeze": "6",
        "wheezy": "7",
        "jessie": "8",
        "stretch": "9",
        "buster": "10",
        "bullseye": "11",
        "bookworm": "12"
        # TO COMPLETE
    }[suite]
    
# Function to translate debian package to cpe
def dpkg2cpe(pkg_name, pkg_vers):
    editor = None
    cpe_name = pkg_name
    cpe_vers = re.search(r'[\d\.]+', pkg_vers).group(0)
    if pkg_name == "linux":
        cpe_name = "linux_kernel"
    elif pkg_name == "apache2":
        editor = "apache"
        cpe_name = "http_server"
    elif pkg_name == "glibc":
        editor = "gnu"
        cpe_name = "glibc"
    elif pkg_name == "file":
        editor = "file_project"
        cpe_name = "file"
    elif pkg_name == "isc-dhcp":
        editor = "isc"
        cpe_name = "dhcp"
    elif pkg_name == "mysql-community":
        cpe_name = "mysql"
    ## NON EXHAUSTIVE
        
    # To remove last digit bind9 ==> bind
    elif re.match(r'[a-z\-\_]+\d$', pkg_name):
        cpe_name = re.sub(r'[\d]$', r'[\d]?', pkg_name)
    # To remove package version python3.4 ==> python
    # gcc- ==> gcc
    elif re.match(r'[a-z\-\_]+([\-\d\.]+)$', pkg_name):
        cpe_name = re.sub(r'[\-\d\.]+$', r'([\-\d\.]+)?', pkg_name)
    # To change - in _ bsd-mailx ==> bsd_mailx
    elif re.match(r'[\w]+\-[\w]+', pkg_name): 
        cpe_name = pkg_name.replace('-', r'[-_]')

    return editor, cpe_name, cpe_vers
    
def hostnames2stats(hostnames, rules):
        
    for hostname in hostnames:
        for rule in rules:
            regex = re.compile(rule['regex'])
            if regex.match(hostname):
                rule['nb'] += 1
                
    return rules
