#!/usr/bin/env python3

import argparse
import json
import sys

def parse_config(path):
    eeproms = {}

    with open(path, 'r') as f:
        config = json.load(f)

        for eeprom in config:
            eeproms[eeprom['path']] = eeprom['properties']
    return eeproms

'''
    [
        {
            "bus": 1,
            "address": 84,
            "path": "/com/luxshare/eeprom/1",
            "interface": "com.luxshare.eeprom",
            "properties": [
                {
                    "name": "ETH0MAC",
                    "offset": 0,
                    "size": 6
                },
                {
                    "name": "ETH1MAC",
                    "offset": 8,
                    "size": 6
                }
            ]
        }
    ]
'''
def check_overlap(properties):
    # sort by offset
    properties.sort(key=lambda x: x['offset'])

    for i in range(len(properties) - 1):
        if properties[i]['offset'] + properties[i]['size'] > properties[i + 1]['offset']:
            print('overlap found: {} {} {} {} {} {}'.format(
                properties[i]['name'],
                properties[i]['offset'],
                properties[i]['size'],
                properties[i + 1]['name'],
                properties[i + 1]['offset'],
                properties[i + 1]['size'],
            ))
            sys.exit(1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Check if eeprom properties overlap')
    parser.add_argument('path', help='path to json config')

    args = parser.parse_args()
    path = args.path

    eeproms = parse_config(path)

    for path, properties in eeproms.items():
        print(properties)
        check_overlap(properties)
