# Generated by Django 2.2.26 on 2022-10-26 10:01

import logging
import os

from django.db import migrations, transaction

logger = logging.getLogger('authentic2.auth_saml')


def metadata_file_to_db(apps, schema_editor):
    SAMLAuthenticator = apps.get_model('authentic2_auth_saml', 'SAMLAuthenticator')

    def move_data(authenticator):
        path = authenticator.metadata_path

        if not os.path.exists(path):
            return

        try:
            with open(path) as fd:
                metadata = fd.read()
        except OSError:
            logger.warning('auth_saml: open()/read() call failed for %s on %s', authenticator, path)
            return

        authenticator.metadata = metadata
        authenticator.save()

    for authenticator in SAMLAuthenticator.objects.exclude(metadata_path=''):
        try:
            with transaction.atomic():
                move_data(authenticator)
        except Exception:
            logger.exception('auth_saml: could not move metadata file to db for %s', authenticator)


class Migration(migrations.Migration):
    dependencies = [
        ('authentic2_auth_saml', '0012_move_add_role_action'),
    ]

    operations = [
        migrations.RunPython(metadata_file_to_db, reverse_code=migrations.RunPython.noop),
    ]
