#!/usr/bin/python
import re
import subprocess
import json
uplinkmatch = re.compile('^\s*Uplinks:\s*(.*)')
nodename = None
for inf in open('/etc/confluent/confluent.info', 'r').read().split('\n'):
    if inf.startswith('NODENAME: '):
        nodename = inf.replace('NODENAME: ', '')
        break

deploycfg = open('/etc/confluent/confluent.deploycfg', 'r').read().split('\n')
cfg = {}
nslist = False
nameservers = []
for line in deploycfg:
    kv = line.split(': ')
    if not kv[0]:
        continue
    if len(kv) == 2:
        cfg[kv[0]] = kv[1]
    if kv[0] == 'nameservers:':
        nslist = True
        continue
    if nslist and kv[0].startswith('- '):
        nameservers.append(kv[0].split(' ', 1)[1])
    else:
        nslist=False
cfg['nameservers'] = ','.join(nameservers)
vswinfo = subprocess.check_output(['localcli', 'network', 'vswitch', 'standard', 'list']).decode('utf8')
vmnic = None
for info in vswinfo.split('\n'):
    upinfo = uplinkmatch.match(info)
    if upinfo:
        vmnic = upinfo.group(1)
        if vmnic and 'vusb0' not in vmnic:
            break
try:
    with open('/tmp/confluentident/cnflnt.jsn') as identin:
        identcfg = json.load(identin)
        ncfg = identcfg['net_cfgs'][0]
        cfg['ipv4_method'] = ncfg['ipv4_method']
        cfg['ipv4_address'] = ncfg['ipv4_address'].split('/')[0]
        cfg['ipv4_netmask'] = ncfg['ipv4_netmask']
        cfg['ipv4_gateway'] = ncfg['ipv4_gateway']
except Exception:
    pass
if cfg['ipv4_method'] == 'static':
    netline = 'network --hostname={0} --bootproto={1}'.format(nodename, cfg['ipv4_method'])
else:
    netline = 'network --bootproto=dhcp'
if vmnic:
    netline += ' --device={0}'.format(vmnic)
if cfg['ipv4_method'] == 'static':
    netline += ' --ip={0} --netmask={1}'.format(cfg['ipv4_address'], cfg['ipv4_netmask'])
    if cfg.get('ipv4_gateway', 'null') not in (None, '', 'null'):
        netline += ' --gateway={0}'.format(cfg['ipv4_gateway'])
    if cfg['nameservers']:
        netline += ' --nameserver={0}'.format(cfg['nameservers'])
vlanid = None
try:
    with open('/tmp/confluent.vlanid', 'r') as vlanin:
        vlanid = vlanin.read()
except Exception:
    pass
if vlanid:
    netline += ' --vlanid={0}'.format(vlanid)
print(netline)
