#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
if sys.version_info[0] == 2:
    import __builtin__ as builtins
else:
    import builtins

pkgdatadir = None
datadir = None
import jhbuild
srcdir = os.path.abspath(os.path.join(os.path.dirname(jhbuild.__file__), '../..'))

builtins.__dict__['PKGDATADIR'] = pkgdatadir
builtins.__dict__['DATADIR'] = datadir
builtins.__dict__['SRCDIR'] = srcdir

jhb_env = {}

def addpath_override(oldfunc, *args, **kwargs):
    global jhb_env
    variable = args[0]
    import os
    oldenv = os.environ.get(variable, '').split(os.pathsep)
    jhbvalues = jhb_env.get(variable, [])
    oldfunc(*args, **kwargs)
    newenv = {i: val
              for i, val in enumerate(os.environ[variable].split(os.pathsep))}
    for i, val in newenv.items():
        if val in oldenv + jhbvalues:
            continue
        situation = jhb_env.setdefault(variable, [])
        situation.insert(-1 if i != 0 else 0, val)

import jhbuild.main
import jhbuild.environment as env
from functools import partial

def create_environment_vars(env):
    from os import environ, pathsep
    csh = 'csh' in environ.get('SHELL', 'bash')
    if csh:
        export = 'setenv'
        sep = ' '
    else:
        export = 'export'
        sep = '='
    string = []
    for var, val in env.items():
        string.append(sep.join((' '.join([export, var]), pathsep.join(val))))
    return '\n'.join(string)+'\n'


def create_environment_script(env):
    from os import environ, path
    prefix = environ['JHBUILD_PREFIX']
    root = path.join(prefix, 'bin')
    if not path.isdir(root):
        return
    filename = path.join(root, 'bigdftvars.sh')
    bigdft_env = {'BIGDFT_ROOT': [root]}
    for k, v in env.items():
        bigdft_env[k] = v + ['$'+k]
    ofile = open(filename, 'w')
    ofile.write(create_environment_vars(bigdft_env))
    ofile.close()


old_addpath = env.addpath
env.addpath = partial(addpath_override, old_addpath)
jhbuild.main.main(sys.argv[1:])

create_environment_script(jhb_env)
