#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright 2016 by Avencall
# SPDX-License-Identifier: GPL-3.0+

# This script clean a .json consul backup
# It cleans from this backup :
# - the personal contacts duplicated
# - and the tokens


import json
import sys


def main():
    if len(sys.argv) != 2:
        print('Usage: %s /path/to/consul/backup.json' % sys.argv[0])
        sys.exit(1)

    filename = sys.argv[1]
    with open(filename, 'r') as f:
        index, entries = json.load(f)

    new_entries = []
    user_personal_contacts = {}
    count, skip, dup, perso = 0, 0, 0, 0
    for entry in entries:
        count += 1
        key = entry.get('Key')

        if 'tokens' in key:
            skip += 1
            continue  # Do not keep tokens key
        elif 'personal' not in key:
            new_entries.append(entry)
            continue
        try:
            _, __, user, ___, ____, contact_uuid, field = key.split('/')
        except ValueError:
            print('Error', key)
            continue

        if user not in user_personal_contacts:
            user_personal_contacts[user] = {}
        if contact_uuid not in user_personal_contacts[user]:
            user_personal_contacts[user][contact_uuid] = {}
        if field not in user_personal_contacts[user][contact_uuid]:
            user_personal_contacts[user][contact_uuid][field] = (entry.get('Value'), entry)

    for user, contacts in user_personal_contacts.items():
        unique_contacts = set()
        for uuid, fields in contacts.items():
            perso += 1
            this_contact = []
            for fieldname, values in fields.items():
                if fieldname != 'id':
                    this_contact.append((fieldname, values[0]))
            sorted_contact = tuple(sorted(this_contact))
            if sorted_contact in unique_contacts:
                dup += 1
                skip += len(fields)
                continue
            unique_contacts.add(sorted_contact)
            for values in fields.values():
                new_entries.append(values[1])

    new_filename = '{}-new'.format(filename)
    with open(new_filename, 'w') as f:
        json.dump([index, new_entries], f)

    print('Backup cleanup complete: {}/{} KV have been removed'.format(skip, count))
    print('Duplicate personal contacts {}/{}'.format(dup, perso))


if __name__ == '__main__':
    main()
