# Generated by Django 2.0.9 on 2018-11-14 08:55

from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


def update_public_key_format(apps, schema_editor):
    """
    Reserialize keys in proper format (PKCS#8 instead of #1)
    https://github.com/friendica/friendica/issues/7771#issuecomment-603019826
    """
    Actor = apps.get_model("federation", "Actor")

    local_actors = list(
        Actor.objects.exclude(private_key="")
        .exclude(private_key=None)
        .only("pk", "private_key", "public_key")
        .order_by("id")
    )

    total = len(local_actors)
    if total:
        print("{} keys to update...".format(total))
    else:
        print("Skipping")
        return

    from cryptography.hazmat.primitives import serialization as crypto_serialization
    from cryptography.hazmat.backends import default_backend

    for actor in local_actors:
        private_key = crypto_serialization.load_pem_private_key(
            actor.private_key.encode(), password=None, backend=default_backend()
        )
        public_key = private_key.public_key().public_bytes(
            crypto_serialization.Encoding.PEM,
            crypto_serialization.PublicFormat.SubjectPublicKeyInfo,
        )
        actor.public_key = public_key.decode()

    Actor.objects.bulk_update(local_actors, ["public_key"])
    print("Done!")


def skip(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [("federation", "0025_auto_20200317_0820")]

    operations = [
        migrations.RunPython(update_public_key_format, skip),
    ]
