"""Install

The install command creates the .excenturyrc file. This file
is autogenerated and should not be modified manually.

"""

import os
import sys
import site
import textwrap
import os.path as pth

DESC = """
Create the .excenturyrc file and source it in your .bash_profile or
.bashrc file. This will make sure that you can use the excentury
script and that the excentury libraries are all available to the g++
compiler and the other languages.

"""


def add_parser(subp, raw):
    """Add a parser to the main subparser. """
    subp.add_parser('install', help='install excentury',
                    formatter_class=raw,
                    description=textwrap.dedent(DESC))


def disp(msg):
    "Print message to stdout. "
    sys.stdout.write(msg)


def source_excenturyrc():
    """Source the .excenturyrc file in the .bashrc file. """
    bash_map = {
        'Darwin': '.bash_profile',
        'darwin': '.bash_profile',
        'Linux': '.bashrc',
        'linux': '.bashrc',
    }
    platform = sys.platform
    try:
        bashrc_path = pth.expandvars('$HOME/%s' % bash_map[platform])
    except KeyError:
        disp('Error: %s platform not supported\n' % platform)
        exit(2)
    disp('checking %s ... ' % bashrc_path)
    if pth.exists(bashrc_path):
        expr = [
            'source ~/.excenturyrc\n',
            'source $HOME/.excenturyrc\n',
            pth.expandvars('source $HOME/.excenturyrc\n'),
        ]
        for content_line in open(bashrc_path, 'r'):
            for line in expr:
                if line == content_line:
                    disp('ok\n')
                    return
    with open(bashrc_path, 'a') as content_file:
        disp('\n    including .excenturyrc\n')
        content_file.write('source ~/.excenturyrc\n')


def append_variable(cfile, var, val):
    """Writes a bash command to check if a variable is missing a
    value."""
    cfile.write('if [[ ":$%s:" != *":%s:"* ]]; then\n' % (var, val))
    cfile.write('    export %s=%s:$%s\n' % (var, val, var))
    cfile.write('fi\n')


def make_dir(path):
    "Create a directory if it does not exist and return True. "
    if pth.exists(path):
        return False
    os.makedirs(path)
    return True


def make_dirs():
    """Creates standard directories to place binaries and libraries
    created by excentury. """
    root = site.getuserbase()
    make_dir(root+'/lib')
    make_dir(root+'/lib/excentury')
    make_dir(root+'/lib/excentury/bin')
    make_dir(root+'/lib/excentury/lib')
    make_dir(root+'/lib/excentury/cpp')
    make_dir(root+'/lib/excentury/matlab')
    make_dir(root+'/lib/excentury/python')
    make_dir(root+'/lib/excentury/tmp')


def excenturyrc():
    """Create the excenturyrc file. """
    userbase = site.getuserbase()
    rc_path = pth.expandvars('$HOME/.excenturyrc')
    disp('writing %s ... ' % rc_path)
    with open(rc_path, 'w') as rcfile:
        disp('\n    system wide path: %s/bin\n' % sys.prefix)
        append_variable(rcfile, 'PATH', '%s/bin' % sys.prefix)
        disp('    user path: %s/bin\n' % userbase)
        append_variable(rcfile, 'PATH', '%s/bin' % userbase)
        # include
        path = pth.abspath(pth.dirname(__file__)+'/../_external/include')
        disp('    include: %s\n' % path)
        append_variable(rcfile, 'C_INCLUDE_PATH', path)
        append_variable(rcfile, 'CPLUS_INCLUDE_PATH', path)
        # matlab
        path = pth.abspath(pth.dirname(__file__)+'/../_external/matlab')
        disp('    matlab: %s\n' % path)
        append_variable(rcfile, 'MATLABPATH', path)
        # excentury/bin
        append_variable(rcfile,
                        'PATH',
                        '%s/lib/excentury/bin' % userbase)
        # excentury/lib
        append_variable(rcfile,
                        'LD_LIBRARY_PATH',
                        '%s/lib/excentury/lib' % userbase)
        # excentury/matlab
        append_variable(rcfile, 
                        'MATLABPATH', 
                        '%s/lib/excentury/matlab' % userbase)
        # excentury/python
        append_variable(rcfile, 
                        'PYTHONPATH', 
                        '%s/lib/excentury/python' % userbase)


def run(_):
    """Run the command. """
    source_excenturyrc()
    make_dirs()
    excenturyrc()
