import getpass
from fabric import task
from invoke import Context

DEV_COMPOSE_CMD = "docker-compose exec -T {container} /bin/bash -c '{command}'"

ENV_NAME = "prod"
REMOTE_DB_NAME = "aemo_fr"


@task
def download_remote_data(conn):
    """
    Dump remote (production) data,  download it and sync media files

    Don't forget to set host in command line `fab -H <HOST> download-remote-data`
    """
    local = Context()

    conn.config["sudo"]["password"] = getpass.getpass(
        "Enter the sudo password (on the server):"
    )

    local.run('echo "Dump DB: Start"')
    conn.run(f"touch {REMOTE_DB_NAME}.backup && chmod o+rw {REMOTE_DB_NAME}.backup")
    conn.sudo(
        f'pg_dump --no-owner -Fc -b -f "{REMOTE_DB_NAME}.backup" {REMOTE_DB_NAME}',
        user="postgres",
    )
    local.run('echo "Dump DB: End"')

    local.run('echo "Download DB: Start"')
    conn.get(f"{REMOTE_DB_NAME}.backup", f"./data/{ENV_NAME}/")
    local.run('echo "Download DB: End"')


@task
def import_db_in_dev(conn):
    local = Context()

    local.run('echo "Import DB in dev: Start"')
    local.run(
        DEV_COMPOSE_CMD.format(
            container="db",
            command=(
                "dropdb -U ${POSTGRES_USER} --if-exists --force ${POSTGRES_DB} && "
                "createdb -U ${POSTGRES_USER} -O ${POSTGRES_USER} ${POSTGRES_DB}"
            ),
        )
    )
    local.run(
        DEV_COMPOSE_CMD.format(
            container="db",
            command=f'pg_restore -U ${{POSTGRES_USER}} -d ${{POSTGRES_DB}} --no-owner "/data/{ENV_NAME}/{REMOTE_DB_NAME}.backup"',
        )
    )
    local.run('echo "Import DB in dev: End\n\n"')


@task
def create_admin_in_dev(conn):
    local = Context()

    local.run('echo "Create superuser: Start"')
    local.run(
        DEV_COMPOSE_CMD.format(
            container="web",
            command=(
                "DJANGO_SUPERUSER_USERNAME=admin "
                "DJANGO_SUPERUSER_PASSWORD=admin "
                "DJANGO_SUPERUSER_EMAIL=admin@dev.dev "
                "python3 ./manage.py createsuperuser --no-input"
            ),
        )
    )
    local.run('echo "Create superuser: End\n\n"')
