# This script reads a file with this format:
#
#  email_addr account_id
#
# It will then remove all external ids with that email addr
# in them from the account specified.
# Note the account_ids and emails both may be non unique depending
# on the gerrit account situation. We iterate over each line in this
# file one at a time to avoid problems with deduping in datastructures.
#
# Consider running this with python3 -u to get unbuffered stdout. This
# will help you better track progress.

import getpass
import json
import requests

def get_external_ids(account_id, auth):
    r = requests.get('https://review.opendev.org'
                     '/a/accounts/%s/external.ids' % account_id,
                     auth=auth)
    # Strip off the gerrit json prefix
    j = json.loads(r.text[5:])
    return j


def is_active(account_id, auth):
    r = requests.get('https://review.opendev.org'
                     '/a/accounts/%s/detail' % account_id,
                     auth=auth)
    # Strip off the gerrit json prefix
    j = json.loads(r.text[5:])
    if 'inactive' in j and j['inactive']:
        return False
    else:
        return True


if __name__ == '__main__':
    query_user = input('Username: ')
    query_pass = getpass.getpass('Password: ')
    if query_user and query_pass:
        auth = (query_user, query_pass)
    else:
        print("This script requires authentication")
        exit(1)

    with open('external_id_cleanups.txt') as f:
        for line in f:
            (email, account_id) = line.strip().split()
            print(email + ' ' + account_id)

            if is_active(account_id, auth):
                print('This account is active. Skipping.')
                continue

            j = get_external_ids(account_id, auth)
            print('external IDs: ' + str(j))

            eids_to_remove = []
            for eid in j:
                if 'email_address' in eid and eid['email_address'] == email:
                    eids_to_remove.append(eid['identity'])

            if eids_to_remove:
                print('Removing these external IDs: ' + str(eids_to_remove))
                url = 'https://review.opendev.org' \
                    '/a/accounts/%s/external.ids:delete' % account_id
                print(url)
                r = requests.post(url, json=eids_to_remove, auth=auth)
                print(r.status_code)
                print(r.text)
            else:
                print('No matching external ids')