# Generated by Django 2.2.18 on 2021-03-03 10:59

import contextlib

from urllib.parse import urlparse, urlunparse

from django.db import migrations


def move_proxy_creds_up(apps, schema_editor):
    Remote = apps.get_model('core', 'Remote')
    for remote in Remote.objects.all():
        if remote.proxy_url and "@" in remote.proxy_url:
            with contextlib.suppress(Exception):
                parsed_url = urlparse(remote.proxy_url)
                netloc = parsed_url.netloc
                auth, url = netloc.rsplit("@", maxsplit=1)
                remote.proxy_username, remote.proxy_password = auth.split(":", maxsplit=1)
                remote.proxy_url = urlunparse(parsed_url._replace(netloc=url))
                remote.save()


def move_proxy_creds_down(apps, schema_editor):
    Remote = apps.get_model('core', 'Remote')
    for remote in Remote.objects.all():
        if remote.proxy_url and remote.proxy_username and remote.proxy_password:
            with contextlib.suppress(Exception):
                parsed_url = urlparse(remote.proxy_url)
                url = parsed_url.netloc
                netloc = remote.proxy_username + ":" + remote.proxy_password + "@" + url
                remote.proxy_username = None
                remote.proxy_password = None
                remote.proxy_url = urlunparse(parsed_url._replace(netloc=netloc))
                remote.save()


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0059_proxy_creds'),
    ]

    operations = [
        migrations.RunPython(move_proxy_creds_up, reverse_code=move_proxy_creds_down, elidable=True),
    ]
