from django.core.management.base import (
    BaseCommand,
    CommandError,
)

from staff.keys.models import GPGKey
from staff.person_profile.controllers.gpg_key import gpg_fingerprint


class Command(BaseCommand):
    help = 'Пересчитывает fingerprint у всех GPG ключей'

    def handle(self, *args, **options):
        try:
            all_keys = GPGKey.objects.all()
            for key in all_keys:
                old_fpr = key.fingerprint
                try:
                    new_fpr = gpg_fingerprint(key.key)
                    if new_fpr != old_fpr:
                        key.fingerprint = new_fpr
                        key.save()
                        print('Changed: %s' % key.id)
                    else:
                        print('Similar: %s' % key.id)
                except Exception as e:
                    print('Problem: %s' % key.id)
                    print(e)
        except Exception as e:
            raise CommandError(e)
