# Generated by Django 2.2.5 on 2019-11-25 01:31

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


def get_storage_data(s):
    from common.utils import signer
    import json

    value = s.value
    encrypted = s.encrypted
    if encrypted:
        value = signer.unsign(value)
    try:
        value = json.loads(value)
    except:
        value = {}
    return value


def get_setting(apps, schema_editor, key):
    model = apps.get_model("settings", "Setting")
    db_alias = schema_editor.connection.alias
    setting = model.objects.using(db_alias).filter(name=key)
    if not setting:
        return
    return setting[0]


def init_storage_data(model):
    model.objects.update_or_create(
        name="null",
        type="null",
        is_default=False,
        defaults={
            "name": "null",
            "type": "null",
            "comment": "Do not save",
            "meta": "{}",
        },
    )
    model.objects.update_or_create(
        name="default",
        type="server",
        is_default=True,
        defaults={
            "name": "default",
            "type": "server",
            "comment": "Store locally",
            "meta": "{}",
        },
    )


def migrate_command_storage(apps, schema_editor):
    model = apps.get_model("terminal", "CommandStorage")
    init_storage_data(model)


def migrate_replay_storage(apps, schema_editor):
    model = apps.get_model("terminal", "ReplayStorage")
    init_storage_data(model)


def migrate_endpoints(apps, schema_editor):
    Endpoint = apps.get_model("terminal", "Endpoint")
    # migrate default
    default_data = {
        "id": "00000000-0000-0000-0000-000000000001",
        "name": "Default",
        "host": "",
        "https_port": 0,
        "http_port": 0,
        "created_by": "System",
    }
    Endpoint.objects.create(**default_data)

    if not settings.TERMINAL_RAZOR_ENABLED:
        return
    # migrate xrdp
    xrdp_addr = settings.TERMINAL_RDP_ADDR
    if ":" in xrdp_addr:
        host, rdp_port = xrdp_addr.strip().split(":")
    else:
        host, rdp_port = xrdp_addr, 3389
    host = host.strip()
    if host in ["localhost", "127.0.0.1"]:
        host = ""
    if not host:
        return
    if isinstance(rdp_port, str) and rdp_port.isdigit():
        rdp_port = int(rdp_port)
    elif isinstance(rdp_port, int) and (0 <= rdp_port <= 65535):
        rdp_port = rdp_port
    else:
        rdp_port = 3389
    xrdp_data = {
        "name": "Razor",
        "host": host,
        "https_port": 0,
        "http_port": 0,
        "ssh_port": 0,
        "rdp_port": rdp_port,
        "mysql_port": 0,
        "mariadb_port": 0,
        "postgresql_port": 0,
        "created_by": "System",
    }
    xrdp_endpoint = Endpoint.objects.create(**xrdp_data)

    EndpointRule = apps.get_model("terminal", "EndpointRule")
    xrdp_rule_data = {
        "name": "Razor",
        "ip_group": ["*"],
        "priority": 20,
        "endpoint": xrdp_endpoint,
        "created_by": "System",
    }
    EndpointRule.objects.create(**xrdp_rule_data)


class Migration(migrations.Migration):
    dependencies = [
        ("settings", "0001_initial"),
        ("terminal", "0002_auto_20171228_0025"),
    ]

    operations = [
        migrations.RunPython(migrate_command_storage),
        migrations.RunPython(migrate_replay_storage),
        migrations.RunPython(migrate_endpoints),
    ]
