#!/usr/bin/env python3

import os
import sys
import subprocess
from kubernetes import client, config
from kubernetes.client.rest import ApiException
import random, string

def main():
    data = get_mac_pci_mapping()
    if not data:
        print("ERROR: Invalid data")
        sys.exit(1)
    create_cr(data)


def get_mac_pci_mapping():
    data = []
    networks = os.environ['NETWORK_NAME_LIST']
    network_list = networks.split(',')
    pci_all = []
    for net in network_list:
        pci_env = "PCIDEVICE_" + net.replace('/', '_').replace('.', '_').upper()
        pcis = os.environ[pci_env]
        print("pcis = %s" % pcis)
        pci_list = pcis.split(',')
        pci_all.extend(pci_list)

    data = get_mac_of_pci(pci_all)
    print("pci_all(%s) data(%s)" % (pci_all, data))

    nw_data = []
    for net in network_list:
        pci_env = "PCIDEVICE_" + net.replace('/', '_').replace('.', '_').upper()
        pcis = os.environ[pci_env]
        nw_item = {'name': net, 'devices': []}
        for item in data:
            if item['pci'] in pcis:
                nw_item['devices'].append(item)
        nw_data.append(nw_item)
    print("nw_data: %s" % nw_data)
    return nw_data


def get_mac_of_pci(pcis):
    mac_file = '/tmp/macaddr.txt'
    if not os.path.exists(mac_file):
        print("ERROR: mac address file /tmp/macaddr.txt should be present")
        sys.exit(1)
    content = ''
    info = {}
    with open(mac_file) as f:
        content = f.read()
    lines = content.split('\n')
    data = []
    for line in lines:
        info = line.split(',')
        if len(line.split(',')) != 2:
            continue
        info = {}
        info['pci'] = line.split(',')[0]
        info['mac'] = line.split(',')[1]
        print(info)
        data.append(info)
    return data


def create_cr(data):
    group = "examplecnf.openshift.io"
    version = "v1"
    namespace = "example-cnf"
    # TODO: Use that of LB's CR
    plural = "testpmdmacs"

    config.load_incluster_config()
    custom_api = client.CustomObjectsApi()

    hostname = os.environ['HOSTNAME']
    nodename = os.environ['NODE_NAME']

    cr = { 'apiVersion': group + '/' + version,
           'metadata': {
               'name': 'INVALID',
               'namespace': namespace,
               'ownerReferences': []
            },
           'kind': 'TestPMDMac',
           'spec': {}}

    body = cr
    body['spec']['resources'] = data
    body['spec']['hostname'] = hostname
    body['spec']['nodename'] = nodename
    #name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
    name = hostname
    body['metadata']['name'] = name

    try:
        api_instance = client.CoreV1Api()
        api_response = api_instance.read_namespaced_pod(name=hostname, namespace=namespace)
        uid = api_response.metadata.uid
    except ApiException as e:
        print('Found exception in reading the logs')

    body['metadata']['ownerReferences'].append({
        'apiVersion': 'v1',
        'kind': 'Pod',
        'name': hostname,
        'uid': uid,
        'controller': True
    })

    exists = False
    try:
        custom_api.get_namespaced_custom_object(group, version, namespace, plural, name)
        exists = True
        print("TestPMDMac CR exists with name %s" % name)
    except ApiException as e:
        if e.status != 404:
            print("Exception when calling CustomObjectsApi->get_namespaced_custom_object: %s\n" % e)
            sys.exit(1)

    if exists:
        try:
            custom_api.delete_namespaced_custom_object(group, version, namespace, plural, name)
            print("Deleted TestPMDMac CR with name %s" % name)
        except ApiException as e:
            print("Exception on Deleting CR: %s\n" % e)
            sys.exit(1)

    try:
        resp = custom_api.create_namespaced_custom_object(group, version, namespace, plural, body)
        print("TestPMDMac CR created with name %s" % name)
    except ApiException as e:
        print("Exception on Creating CR: %s\n" % e)
        sys.exit(1)


if __name__ == '__main__':
    main()
