from pkgutil import get_data
from git_remote_run import Remote, setup_repo, upload_hook_command, upload_command
from io import BytesIO
from subprocess import run, PIPE


def deploy_setup(remote_name):
    """
    Setup all needed directories.
    """

    remote = Remote(remote_name)
    url = run(['git', 'remote', 'get-url', remote_name], stdout=PIPE).stdout.decode('latin1')
    _, service_name, git_dir = url.rstrip().rsplit('/', 2)

    # Create the project directory and bare repository.
    setup_repo(remote)
    cmd = []

    # Upload the hook which triggers a deployment.
    cmd.append(upload_hook_command(
        BytesIO(get_data('deploy_setup', 'templates/post-update')),
        'post-update'
    ))

    # Upload the main Makefile.
    cmd.append(upload_command(
        BytesIO(get_data('deploy_setup', 'templates/Makefile')),
        '$REPO_DIR/../Makefile'
    ))

    cmd.append("""mkdir -p $REPO_DIR/../etc""")

    cmd.append('''if [ ! -e $REPO_DIR/../etc/deployment.cfg ]; then''')

    # Upload the deployment configuration template.
    cfg = get_data('deploy_setup', 'templates/deployment.cfg.template').decode('utf-8')
    cfg = cfg.format(
        git_dir=git_dir,
        service_name=service_name,
    )
    cfg = cfg.encode('utf-8')
    cmd.append(upload_command(
        BytesIO(cfg),
        '$REPO_DIR/../etc/deployment.cfg'
    ))

    cmd.append('fi')

    # Upload the make script for copying configuration.
    cmd.append(upload_command(
        BytesIO(get_data('deploy_setup', 'templates/supply-configuration.mk')),
        '$REPO_DIR/../etc/.supply-configuration.mk'
    ))

    cmd.append(upload_command(
        BytesIO(get_data('deploy_setup', 'templates/manage.py')),
        '$REPO_DIR/../manage.py'
    ))
    cmd.append('chmod +x $REPO_DIR/../manage.py')

    res = remote.run("\n\n".join(cmd))
    print(res['stderr'].decode('utf-8'))
