#!/usr/bin/env python

"""PGSync bootstrap."""
import json
import logging

import click

from pgsync.sync import Sync
from pgsync.utils import get_config

logger = logging.getLogger(__name__)


@click.command()
@click.option(
    '--config',
    '-c',
    help='Schema config',
    type=click.Path(exists=True),
)
@click.option('--host', '-h', help='PG_HOST overide')
@click.option('--password', is_flag=True, help='Prompt for database password')
@click.option('--port', '-p', help='PG_PORT overide', type=int)
@click.option(
    '--teardown',
    '-t',
    is_flag=True,
    help='Teardown database triggers and replication slots',
)
@click.option('--user', '-u', help='PG_USER overide')
@click.option(
    '--verbose',
    '-v',
    is_flag=True,
    default=False,
    help='Turn on verbosity',
)
def main(teardown, config, user, password, host, port, verbose):
    """Application onetime Bootstrap."""
    params = {
        'user': user,
        'host': host,
        'port': port,
    }
    if password:
        params['password'] = click.prompt(
            "Password",
            type=str,
            hide_input=True,
        )
    params = {
        key: value for key, value in params.items() if value is not None
    }

    config = get_config(config)

    for document in json.load(open(config)):
        sync = Sync(document, verbose=verbose, **params)
        if teardown:
            sync.teardown()
            continue
        sync.setup()
        logger.info(f'Bootstrap: {sync.database}')


if __name__ == '__main__':
    main()
