#!/usr/bin/env python

import __main__
# This is going to require sqlalchemy 0.8 sooner than later.
__main__.__requires__ = __requires__ = ["tahrir-api", "sqlalchemy>=0.7"]
import pkg_resources
pkg_resources.require(__requires__)

import requests
import time

from tahrir_api.dbapi import TahrirDatabase
import transaction

import logging
log = logging.getLogger()
logging.basicConfig()

import fedmsg
import fedmsg.config

fm_config = fedmsg.config.load_config()
fm_config['cert_prefix'] = 'fedbadges'
fm_config['name'] = 'relay_inbound'
fm_config['active'] = True
fedmsg.init(**fm_config)

import fedbadges.utils


def main():
    url = 'https://admin.fedoraproject.org/mirrormanager/api/mirroradmins'
    response = requests.get(url)

    if response.status_code != 200:
        raise IOError("Couldn't read the mirrormanager/mirroradmins list.")

    usernames = response.json()['admins']

    badge = tahrir.get_badge(badge_id='mirror,-mirror-on-the-wall')
    if not badge:
        raise ValueError("badge does not exist")

    for username in usernames:
        email = username + "@fedoraproject.org"

        person = tahrir.get_person(person_email=email)
        if not person:
            print email, "does not exist.  Creating."
            try:
                transaction.begin()
                tahrir.add_person(email, nickname=username)
                transaction.commit()
            except Exception as e:
                transaction.abort()
                print "Failure:", e
                continue

        if tahrir.assertion_exists(badge.id, email):
            print email, "already has", badge.id, "skipping."
            continue

        time.sleep(1)
        print "awarding", badge.id, "to", email
        try:
            transaction.begin()
            tahrir.add_assertion(badge.id, email, None)
            transaction.commit()
        except Exception as e:
            transaction.abort()
            print "Failure:", e


if __name__ == '__main__':
    uri = fm_config['badges_global']['database_uri']
    tahrir = TahrirDatabase(
        uri,
        notification_callback=fedbadges.utils.notification_callback,
    )
    main()
