# Generated by Django 3.2.13 on 2022-07-01 10:19

import gnupg
import tempfile

from django.db import migrations, models


def migrate_keyring_to_gpgkey_on_repository_up(apps, schema_editor):
    AnsibleRepository = apps.get_model('ansible', 'AnsibleRepository')
    changed_repos = []
    with tempfile.TemporaryDirectory() as gnupghome:
        for repository in AnsibleRepository.objects.filter(keyring__isnull=False):
            try:
                gpg = gnupg.GPG(gnupghome=gnupghome, keyring=repository.keyring)
                repository.gpgkey = gpg.export_keys("*")
                changed_repos.append(repository)
            except Exception as e:
                # Make the migration resilient
                print(f"Repository {repository.pk} failed to migrate it's keyring. {e}")
                pass

            if len(changed_repos) >= 1024:
                AnsibleRepository.objects.bulk_update(changed_repos, ['gpgkey'])
                changed_repos.clear()
    # Flush the rest
    AnsibleRepository.objects.bulk_update(changed_repos, ['gpgkey'])


class Migration(migrations.Migration):

    dependencies = [
        ('ansible', '0041_alter_collectionversion_collection'),
    ]

    operations = [
        migrations.AddField(
            model_name='ansiblerepository',
            name='gpgkey',
            field=models.TextField(null=True),
        ),
        migrations.RunPython(
            code=migrate_keyring_to_gpgkey_on_repository_up,
            reverse_code=migrations.RunPython.noop,
            elidable=True,
        ),
        migrations.RemoveField(
            model_name='ansiblerepository',
            name='keyring',
        ),
    ]
