try:
    import configparser
except ImportError:
    import ConfigParser as configparser
    import cStringIO
import importlib.util
import importlib.machinery
import sys
modloader = importlib.machinery.SourceFileLoader('apiclient', '/opt/confluent/bin/apiclient')
modspec = importlib.util.spec_from_file_location('apiclient', '/opt/confluent/bin/apiclient', loader=modloader)
apiclient = importlib.util.module_from_spec(modspec)
modspec.loader.exec_module(apiclient)
repo = None
server = None
v4cfg = None
server4 = None
server6 = None
profile = None
with open('/etc/confluent/confluent.deploycfg') as dplcfgfile:
    lines = dplcfgfile.read().split('\n')
    for line in lines:
        if line.startswith('deploy_server:'):
           _, server4 = line.split(' ', 1)
        if line.startswith('deploy_server_v6:'):
           _, server6 = line.split(' ', 1)
        if line.startswith('profile: '):
           _, profile = line.split(' ', 1)
        if line.startswith('ipv4_method: '):
           _, v4cfg = line.split(' ', 1)
if v4cfg == 'static' or v4cfg =='dhcp':
    server = server4
if not server:
    server = '[{}]'.format(server6)

path = '/confluent-public/os/{0}/distribution/'.format(profile)
clnt = apiclient.HTTPSClient()
cfgdata = clnt.grab_url(path + '.treeinfo').decode()
c = configparser.ConfigParser()
try:
    c.read_string(cfgdata)
except AttributeError:
    f = cStringIO.StringIO(cfgdata)
    c.readfp(f)
for sec in c.sections():
    if sec.startswith('variant-'):
        try:
            repopath = c.get(sec, 'repository')
        except Exception:
            continue
        _, varname = sec.split('-', 1)
        reponame = '/etc/yum.repos.d/local-{0}.repo'.format(varname.lower())
        with open(reponame, 'w') as repout:
            repout.write('[local-{0}]\n'.format(varname.lower()))
            repout.write('name=Local install repository for {0}\n'.format(varname))
            if repopath[0] == '.':
                repopath = repopath[1:]
            repout.write('baseurl=https://{}/confluent-public/os/{}/distribution/{}\n'.format(server, profile, repopath))
            repout.write('enabled=1\n')
