# Generated by Django 3.1.6 on 2021-02-02 20:51

from django.apps.registry import Apps
from django.db import migrations


def set_managed_flag(apps: Apps, schema_editor):
    LDAPPropertyMapping = apps.get_model(
        "authentik_sources_ldap", "LDAPPropertyMapping"
    )
    db_alias = schema_editor.connection.alias
    field_to_uid = {
        "name": "goauthentik.io/sources/ldap/default-name",
        "email": "goauthentik.io/sources/ldap/default-mail",
        "username": "goauthentik.io/sources/ldap/ms-samaccountname",
        "attributes.upn": "goauthentik.io/sources/ldap/ms-userprincipalname",
        "first_name": "goauthentik.io/sources/ldap/ms-givenName",
        "last_name": "goauthentik.io/sources/ldap/ms-sn",
    }
    for mapping in LDAPPropertyMapping.objects.using(db_alias).filter(
        name__startswith="Autogenerated "
    ):
        mapping.managed = field_to_uid.get(mapping.object_field)
        mapping.save()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_core", "0017_managed"),
        ("authentik_sources_ldap", "0007_ldapsource_sync_users_password"),
    ]

    operations = [migrations.RunPython(set_managed_flag)]
