# Generated by Django 3.0.6 on 2020-05-23 16:40
from os import environ

from django.apps.registry import Apps
from django.conf import settings
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor


def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    from django.contrib.auth.hashers import make_password

    User = apps.get_model("authentik_core", "User")
    db_alias = schema_editor.connection.alias

    akadmin, _ = User.objects.using(db_alias).get_or_create(
        username="akadmin", email="root@localhost", name="authentik Default Admin"
    )
    password = None
    if "TF_BUILD" in environ or settings.TEST:
        password = "akadmin"  # noqa # nosec
    if "AK_ADMIN_PASS" in environ:
        password = environ["AK_ADMIN_PASS"]
    if "AUTHENTIK_BOOTSTRAP_PASSWORD" in environ:
        password = environ["AUTHENTIK_BOOTSTRAP_PASSWORD"]
    if password:
        akadmin.password = make_password(password)
    else:
        akadmin.password = make_password(None)
    akadmin.save()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_core", "0002_auto_20200523_1133"),
    ]

    operations = [
        migrations.RemoveField(
            model_name="user",
            name="is_superuser",
        ),
        migrations.RemoveField(
            model_name="user",
            name="is_staff",
        ),
        migrations.RunPython(create_default_user),
        migrations.AddField(
            model_name="user",
            name="is_superuser",
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name="user", name="is_staff", field=models.BooleanField(default=False)
        ),
    ]
