# Generated by Django 4.2.3 on 2023-07-20 12:41

from django.db import migrations, models

category_choices = [
    ("secret_read", "secret_read"),
    ("secret_elevated_superuser_read", "secret_elevated_superuser_read"),
    ("secret_permission_violation", "secret_permission_violation"),
    ("secret_changed", "secret_changed"),
    ("secret_needs_changing_reminder", "secret_needs_changing_reminder"),
    ("secret_legacy_access_requests", "secret_legacy_access_requests"),
    ("secret_shared", "secret_shared"),
    ("secret_superuser_shared", "secret_superuser_shared"),
    ("user_activated", "user_activated"),
    ("user_deactivated", "user_deactivated"),
    ("user_settings_changed", "user_settings_changed"),
    ("miscellaneous", "miscellaneous"),
]


def categorize_log_entries(apps, schema_editor):
    log_entry_model = apps.get_model('audit', 'LogEntry')

    mapping = {
        r"^.* used superuser privileges to read '.*'$": "secret_superuser_read",
        r"^.* read '.*'$": "secret_read",
        r"^.* tried to access '.*' without permission$": "secret_permission_violation",
        r"^.* shared '.* with .*$": "secret_shared",
        r"^.* granted access to \w+ '.*'.*$": "secret_shared",
        r"^.* set a new secret for '.*' \([\w\d]+->[\w\d]+\)$": "secret_changed",
        r"^.* deleted '.*' \(\d+:\d+\)$": "secret_changed",
        r"^.* restore '.*' \(\d+:\d+\)$": "secret_changed",
        r"^.* has \w+ access request #\d+ for .*, ?\w* allowing access to '.*'$": "secret_legacy_access_requests",
        r"^secret '.*' needs changing because user '.*' was deactivated$": "secret_needs_changing_reminder",
        r"^.* reactivated .*": "user_activated$",
        r"^.* deactivated .*, \d+ secrets marked for changing": "user_deactivated$",
    }

    for regex, category in mapping.items():
        log_entry_model.objects.filter(message__regex=regex).update(category=category)


class Migration(migrations.Migration):
    dependencies = [
        ("audit", "0002_auto_20170313_1544"),
    ]

    operations = [
        migrations.AddField(
            model_name="logentry",
            name="category",
            field=models.CharField(
                choices=category_choices,
                default="miscellaneous",
                max_length=64,
            ),
        ),
        migrations.RunPython(
            code=categorize_log_entries,
        ),
        migrations.AlterField(
            model_name="logentry",
            name="category",
            field=models.CharField(
                choices=category_choices,
                max_length=64,
            ),
        ),
    ]
