# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# Generated by Django 1.11.7 on 2017-12-08 17:35

from django.db import migrations

"""
On December 4 2017, we migrated all the active users and their tokens
from Crash-stats into symbols.mozilla.org. The script that did the
importing (useradmin/management/commands/import-uploaders.py) had a bug
in it which was discovered after it had been run.
The bug was that it only created the users and the tokens but failed to
attach the necessary permission to the upload tokens. The list is
known and will be listed here but in an obfuscated form.
"""

# The list of actual tokens is known because I (peterbe) sent them
# as a gpg encrypted .json file to CloudOps to run into the production
# server. Since I retained this file locally, I know exactly the
# token keys and their email addresses. Let's only fix exactly these.
AFFECTED_TOKENS = (
    # FIRST KEY CHAR, LAST KEY CHAR, FIRST EMAIL CHAR, LAST EMAIL CHAR
    ("9", "7", "c", "m"),
    ("8", "e", "c", "m"),
    ("1", "1", "e", "g"),
    ("5", "b", "g", "m"),
    ("c", "5", "j", "m"),
    ("a", "1", "s", "g"),
    ("3", "f", "w", "m"),
)


def correct_migrated_tokens_permissions(apps, schema_editor):
    Token = apps.get_model("tokens", "Token")
    Permission = apps.get_model("auth", "Permission")
    try:
        permission = Permission.objects.get(codename="upload_symbols")
    except Permission.DoesNotExist:
        # If the permission doesn't exist, it's because you're starting
        # the system for the very first time ever.
        # See https://bugzilla.mozilla.org/show_bug.cgi?id=1443156
        # If this is the case you definitely don't need to worry about
        # updating some existing Tokens.
        return
    for first_key, last_key, first_email, last_email in AFFECTED_TOKENS:
        try:
            token = Token.objects.get(
                key__startswith=first_key,
                key__endswith=last_key,
                user__email__startswith=first_email,
                user__email__endswith=last_email,
            )
        except Token.DoesNotExist:
            # The user might have simply deleted it.
            continue
        token.permissions.add(permission)


class Migration(migrations.Migration):
    dependencies = [
        ("tokens", "0002_auto_20170727_1411"),
    ]

    operations = [
        migrations.RunPython(correct_migrated_tokens_permissions),
    ]
