# Generated by Django 3.2.9 on 2022-08-13 05:34
import os
from django.db import migrations


# AWESOME tip on SO on how to create a super user ONCE on application deployment rather than in the docker
# start script which naturally needs to run EVERY TIME container starts: https://stackoverflow.com/a/53555252
class Migration(migrations.Migration):

    dependencies = [
        ('users', '0002_setup_permissions_group'),
    ]

    def generate_superuser(apps, schema_editor):
        # Use historical model from apps to avoid referencing fields
        # that might not yet exist in the database (e.g., newly added columns).
        User = apps.get_model('users', 'User')

        DJANGO_SU_NAME = os.environ.get('DJANGO_SUPERUSER_USERNAME', None)
        DJANGO_SU_EMAIL = os.environ.get('DJANGO_SUPERUSER_EMAIL', None)
        DJANGO_SU_PASSWORD = os.environ.get('DJANGO_SUPERUSER_PASSWORD', None)

        if DJANGO_SU_NAME is not None and DJANGO_SU_EMAIL is not None and DJANGO_SU_PASSWORD is not None:
            superuser = User.objects.create_superuser(
                username=DJANGO_SU_NAME,
                email=DJANGO_SU_EMAIL,
                password=DJANGO_SU_PASSWORD,
                is_usage_capped=False
            )
            superuser.save()
        else:
            print("OpenContracts Server - Initial superuser values were not found in environment... "
                  "you need to run createsuperuser manually to setup a superuser.")

    operations = [
        migrations.RunPython(generate_superuser),
    ]
