# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-04-05 17:30
from __future__ import unicode_literals

from django.db import migrations, models
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType

from osf.models import OSFUser


def fix_osfuser_view_permissions(*args):
    view_osfuser_permission = Permission.objects.get(codename='view_osfuser')
    wrong_osfuser_permission = Permission.objects.get(codename='view_user')

    wrong_osfuser_permission.delete()

    read_only = Group.objects.get(name='read_only')
    osf_admin = Group.objects.get(name='osf_admin')

    read_only.permissions.add(view_osfuser_permission)
    osf_admin.permissions.add(view_osfuser_permission)

    read_only.save()
    osf_admin.save()


def revert_osfuser_view_permissions(*args):
    ctype = ContentType.get_for_model(OSFUser)
    wrong_osfuser_permission = Permission.objects.create(codename='view_user', name='Can view user details', content_type=ctype)
    view_osfuser_permission = Permission.objects.get(codename='view_osfuser')

    osf_admin = Group.objects.get(name='osf_admin')
    read_only = Group.objects.get(name='read_only')

    osf_admin.permissions.add(wrong_osfuser_permission)
    read_only.permissions.add(wrong_osfuser_permission)

    read_only.permissions.remove(view_osfuser_permission)
    osf_admin.permissions.remove(view_osfuser_permission)

    osf_admin.save()
    read_only.save()


class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0011_auto_20170410_1711'),
    ]

    operations = [
        migrations.RunPython(fix_osfuser_view_permissions, revert_osfuser_view_permissions),
    ]

Add proper view_osfuser permission to read_only and admin groups
Add proper view_osfuser permission to read_only and admin groups
