# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-11 18:40
from django.db import migrations


def copy_primary_ip(apps, schema_editor):
    Device = apps.get_model('dcim', 'Device')
    for d in Device.objects.select_related('primary_ip'):
        if not d.primary_ip:
            continue
        if d.primary_ip.family == 4:
            d.primary_ip4 = d.primary_ip
        elif d.primary_ip.family == 6:
            d.primary_ip6 = d.primary_ip
        d.save()


def restore_primary_ip(apps, schema_editor):
    Device = apps.get_model('dcim', 'Device')
    for d in Device.objects.select_related('primary_ip4', 'primary_ip6'):
        if d.primary_ip:
            continue
        # Prefer IPv6 over IPv4
        if d.primary_ip6:
            d.primary_ip = d.primary_ip6
        elif d.primary_ip4:
            d.primary_ip = d.primary_ip4
        d.save()


class Migration(migrations.Migration):

    dependencies = [
        ('dcim', '0006_add_device_primary_ip4_ip6'),
    ]

    operations = [
        migrations.RunPython(copy_primary_ip, restore_primary_ip),
    ]
