# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-27 17:32
from __future__ import unicode_literals

import os
import shutil

from django.conf import settings
from django.db import migrations


def from_files_to_text(apps, schema_editor):
    Root = apps.get_model('core', 'RootCrt')
    Site = apps.get_model('core', 'SiteCrt')

    for root in Root.objects.all():
        root.key_text = root.key.read().decode()
        root.crt_text = root.crt.read().decode()
        root.save()

    for site in Site.objects.all():
        site.key_text = site.key.read().decode()
        site.crt_text = site.crt.read().decode()
        site.save()

    if os.path.exists(settings.MEDIA_ROOT):
        if os.path.islink(settings.MEDIA_ROOT):
            os.unlink(settings.MEDIA_ROOT)
        else:
            shutil.rmtree(settings.MEDIA_ROOT)


def from_text_to_files(apps, schema_editor):
    Root = apps.get_model('core', 'RootCrt')
    Site = apps.get_model('core', 'SiteCrt')

    if not os.path.exists(settings.MEDIA_ROOT):
        os.mkdir(settings.MEDIA_ROOT)
    if not os.path.exists(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH)):
        os.mkdir(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH))

    for root in Root.objects.all():
        with open(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH, 'rootCA.crt'), 'wb') as f:
            f.write(root.crt_text.encode())
            root.crt = os.path.relpath(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH, 'rootCA.crt'), settings.MEDIA_ROOT)
            root.crt_text = None
            root.save()

        with open(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH, 'rootCA.key'), 'wb') as f:
            f.write(root.key_text.encode())
            root.key = os.path.relpath(os.path.join(settings.MEDIA_ROOT, settings.ROOT_CRT_PATH, 'rootCA.key'), settings.MEDIA_ROOT)
            root.key_text = None
            root.save()

    for site in Site.objects.all():
        if not os.path.exists(os.path.join(settings.MEDIA_ROOT, site.cn)):
            os.mkdir(os.path.join(settings.MEDIA_ROOT, site.cn))

        with open(os.path.join(settings.MEDIA_ROOT, site.cn, site.cn + '.crt'), 'wb') as f:
            f.write(site.crt_text.encode())
            site.crt = os.path.relpath(os.path.join(settings.MEDIA_ROOT, site.cn, site.cn + '.crt'), settings.MEDIA_ROOT)
            site.crt_text = None
            site.save()

        with open(os.path.join(settings.MEDIA_ROOT, site.cn, site.cn + '.key'), 'wb') as f:
            f.write(site.key_text.encode())
            site.key = os.path.relpath(os.path.join(settings.MEDIA_ROOT, site.cn, site.cn + '.key'), settings.MEDIA_ROOT)
            site.key_text = None
            site.save()


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0002_auto_20170627_1416')
    ]

    operations = [
        migrations.RunPython(from_files_to_text, reverse_code=from_text_to_files),
    ]
