## -*- coding: utf-8; mode: python; -*-
# -*- coding: utf-8; -*-
"""
Development Tasks for ${name}
"""

import os
import shutil
import sys

from invoke import task


here = os.path.abspath(os.path.dirname(__file__))


@task
def bootstrap(c):
    """
    Bootstrap a development environment.
    """
    if not inside_virtualenv():
        print("\nNot running inside a virtual environment!\n\n"
              "Please create and activate that first, e.g. like:\n\n"
              "    python -m venv /srv/envs/${slug}\n"
              "    source /srv/envs/${slug}/bin/activate\n")
        return

    envdir = sys.prefix

    # install ${name}
    project = os.path.abspath(os.path.join(here, os.pardir))
    c.run('pip install -e {}'.format(project))

    # TODO: these should come from user input
    db = {
        'host': 'localhost',
        'name': '${python_name}',
        'user': 'rattail',
        'pass': 'rattailpass',
    }

    # appdir
    appdir = os.path.join(envdir, 'app')
    if not os.path.exists(appdir):
        c.run('rattail make-appdir')

    # rattail.conf
    if not os.path.exists(os.path.join(appdir, 'rattail.conf')):
        with open('rattail.conf') as f:
            contents = f.read()
        contents = contents.replace('<ENVDIR>', envdir)
        contents = contents.replace('<DBHOST>', db['host'])
        contents = contents.replace('<DBNAME>', db['name'])
        contents = contents.replace('<DBUSER>', db['user'])
        contents = contents.replace('<DBPASS>', db['pass'])
        with open(os.path.join(appdir, 'rattail.conf'), 'w') as f:
            f.write(contents)

    # quiet.conf
    if not os.path.exists(os.path.join(appdir, 'quiet.conf')):
        c.run('rattail make-config -T quiet -O {}'.format(appdir))

    # web.conf
    if not os.path.exists(os.path.join(appdir, 'web.conf')):
        with open('web.conf') as f:
            contents = f.read()
        contents = contents.replace('<ENVDIR>', envdir)
        with open(os.path.join(appdir, 'web.conf'), 'w') as f:
            f.write(contents)

    print("\n\n============================================================\n")
    print("congrats, you should be all ready to go now!\n")
    print("start your development web app with this command:\n")
    print("    cd {}".format(envdir))
    print("    bin/pserve --reload file+ini:app/web.conf\n")
    print("then check out your development web app at:\n")
    print("    http://localhost:9080/\n")


def inside_virtualenv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
