# Generated by Django 2.2.15 on 2020-09-17 16:55

import contextlib

from django.db import migrations

def rename_default_repo(apps, schema_editor):
    AnsibleRepository = apps.get_model('ansible', 'AnsibleRepository')
    AnsibleDistribution = apps.get_model('ansible', 'AnsibleDistribution')
    db_alias = schema_editor.connection.alias

    old_name = 'automation-hub'
    new_name = 'published'

    if (
        AnsibleRepository.objects.using(db_alias).filter(name=new_name) or
        AnsibleDistribution.objects.using(db_alias).filter(name=new_name) or
        AnsibleDistribution.objects.using(db_alias).filter(base_path=new_name)
    ):
        return

    with contextlib.suppress(AnsibleRepository.DoesNotExist, AnsibleDistribution.DoesNotExist):
        repo = AnsibleRepository.objects.using(db_alias).get(name=old_name)
        distro = AnsibleDistribution.objects.using(db_alias).get(base_path=old_name)

        repo.name = new_name
        distro.name = new_name
        distro.base_path = new_name

        repo.save()
        distro.save()


class Migration(migrations.Migration):

    dependencies = [
        ('galaxy', '0007_merge_synclist'),
    ]

    operations = [
        migrations.RunPython(rename_default_repo, elidable=True),
    ]
