#!/usr/bin/env python3

from configparser import ConfigParser
from sys import argv, exit

import psycopg2


def main():
    try:
        group_id = int(argv[1])
    except IndexError:
        print(f'Usage: {argv[0]} <group_id>')
        print()
        print('Sets pretalx administrator permissions based on that group id')
        exit(1)

    config = ConfigParser()
    config.read('/opt/pretalx/pretalx.cfg')

    try:
        db = psycopg2.connect(
            dbname=config['database']['name'],
            user=config['database']['user'],
            password=config['database']['password'],
        )
        with db.cursor() as sel:
            sel.execute(
                'SELECT id, user_id FROM event_team_members WHERE team_id=%s ORDER BY user_id ASC;',
                (group_id,),
            )
            admin_users = set()
            for perm_id, user_id in sel.fetchall():
                admin_users.add(user_id)

        if not admin_users:
            raise ValueError(f'There are no users in group {argv[1]}')

        update_queries = []
        with db.cursor() as sel:
            sel.execute('SELECT id, name, email, is_administrator, is_staff FROM person_user ORDER BY name ASC;')
            for uid, name, email, is_admin, is_staff in sel.fetchall():
                should_admin = (uid in admin_users)

                if not (
                    should_admin == is_admin and
                    should_admin == is_staff
                ):
                    print(f'Fixing user "{name}" ({email}) - is: {is_admin} {is_staff} - should: {should_admin}')
                    update_queries.append({
                        'admin': should_admin,
                        'uid': uid,
                    })

        with db.cursor() as upd:
            for query in update_queries:
                upd.execute(
                    'UPDATE person_user SET is_administrator=%(admin)s, is_staff=%(admin)s WHERE id=%(uid)s;',
                    query,
                )

        db.commit()
    finally:
        db.close()


if __name__ == '__main__':
    main()
