# Generated by Django 3.1.7 on 2021-03-16 05:24

import os

from django.conf import settings
from django.db import migrations

from weblate.vcs.base import RepositoryException
from weblate.vcs.git import LocalRepository


def migrate_glossaries(apps, schema_editor):
    """
    Removes automatically created glossaries for source language.

    These were wrongly created by 0116_migrate_glossaries and it was fixed in
    0d8b564903518a313d4116ffe82d9c7bc31f7908.
    """
    Component = apps.get_model("trans", "Component")
    db_alias = schema_editor.connection.alias

    for component in (
        Component.objects.using(db_alias)
        .filter(is_glossary=True, repo="local:")
        .prefetch_related("project", "source_language")
    ):
        repo_path = os.path.join(
            settings.DATA_DIR, "vcs", component.project.slug, component.slug
        )
        file_path = os.path.join(
            repo_path, component.filemask.replace("*", component.source_language.code)
        )

        if not os.path.exists(file_path):
            continue

        print(f"Removing stale {file_path}")

        repo = LocalRepository(repo_path)
        with repo.lock:
            try:
                repo.remove([file_path], "Removing stale glossary file")
            except RepositoryException:
                if os.path.exists(file_path):
                    os.unlink(file_path)


class Migration(migrations.Migration):

    dependencies = [
        ("trans", "0126_auto_20210312_1348"),
    ]

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