#!/usr/bin/env python

from io import BytesIO
import pycurl
import json
import os
import re
import string
import sys
import yaml

f_adopters = 'ADOPTERS.md'
url_adopters = 'https://raw.githubusercontent.com/kubevirt/kubevirt/main/ADOPTERS.md'

adopters = {
    "adopters": {
        "endusers": [],
        "integrations": [],
        "vendors": [],
    }
}

def logo(name):
    result = []
    path = '../assets/images/adopters/'
    name = re.sub('[^a-zA-Z0-9 \n]', '', name)
    for root, dirs, files in os.walk(path):
        result = [s for s in files if '.' + name.lower() + '.' in '.' + s.lower()]

    if len(result) > 1:
        print("Image search yielded more than 1 result")
        print(result)
        print("Please resolve this and settle on one img file")
        raise SystemExit
    if len(result) == 0:
        print("Image search could not find anything for " + name)
        print("Please add an image file for " + name)
        raise SystemExit
    return result[0]


try:
    with open(f_adopters, 'r') as f:
        print('Using local ADOPTERS file: ./' + f_adopters + "\n")
        print('This is for development purposes!')
        print('The production file is kubevirt/kubvirt/' + f_adopters)
        print('If production updates are expected please be sure to create a pull req in kubevirt/kubevirt\n')
        lines = f.read().split('\n')

except OSError:
    print('Curling ADOPTERS file: ' + url_adopters + "\n")

    b_obj = BytesIO()
    c = pycurl.Curl()
    c.setopt(c.URL, url_adopters)
    c.setopt(c.WRITEDATA, b_obj)
    c.perform()
    if '200' in str(c.getinfo(pycurl.RESPONSE_CODE)):
        c.close()
        lines = b_obj.getvalue().decode('utf8').split('\n')
    else:
        print("Curl failed. Exitting...")
        sys.exit(2)

for line in lines:
    if '| ' in line:
        line = line.replace('| ', '', 1)
        regexp = re.compile(r'([Ee]nd-[Uu]ser|[Ii]ntegration|[Vv]endor)')
        if regexp.search(line):
            line = line.split('| ')
            line[0] = line[0].replace('-','').lower().rstrip() + 's'
            line[1] = line[1].rstrip()
            line[3] = line[3].replace('[link](','').replace(')','').rstrip()
            adopters['adopters'][line[0]].append(
                (
                    {
                    "link": line[3],
                    "logo": logo(line[1].replace(' ','')),
                    "name": line[1]
                    }
                )
            )

x = json.loads(json.dumps(adopters))
f = open('adopters.yml','w')
f.write('# DO NOT EDIT THIS FILE.  PLEASE RUN ./adopters.py INSTEAD!\n')
f.write(yaml.dump(x))
print('adopters.yml updated')
print('Please create pull request... https://github.com/<user>/kubevirt.github.io/pull/new/')
