"""
Call this like ``python create_python_env.py``; it will
refresh the project-boot.py script

-prerequisite:

- virtualenv

- python project-boot.py --unzip-setuptools --no-site-packages --clear --type-install=local <path_to_venv>

"""

import os
import subprocess
import re
import sys


here = os.path.dirname(os.path.abspath(__file__))
base_dir = here
script_name = os.path.join(base_dir, 'project-boot.py')

import virtualenv

# things to install
# - psycopg2 -> pip
# - PIL -> pip
# - pyxml -> pip
# - 4Suite-xml - easy_install ftp://ftp.4suite.org/pub/4Suite/4Suite-XML-1.0.2.tar.bz2
# - pylucene  - script

src_base = os.path.join(here,"res","src").replace("\\","/")
lib_path = os.path.abspath(os.path.join(here,"res","lib")).replace("\\","/")

EXTRA_TEXT  = "URLS = { \n"

EXTRA_TEXT += "    'DISTRIBUTE' : { 'setup': 'distribute', 'url': 'http://pypi.python.org/packages/source/d/distribute/distribute-0.6.14.tar.gz', 'local': '"+ os.path.abspath(os.path.join(src_base,"distribute-0.6.14.tar.gz")).replace("\\","/")+"'},\n"
EXTRA_TEXT += "    'MERCURIAL' : { 'setup': 'distribute', 'url': 'http://pypi.python.org/packages/source/d/mercurial/mercurial-1.7.5.tar.gz', 'local': '"+ os.path.abspath(os.path.join(src_base,"mercurial-1.7.5.tar.gz")).replace("\\","/")+"'},\n"
EXTRA_TEXT += "}\n"

EXTRA_TEXT += "import sys\n"
EXTRA_TEXT += "sys.path.append('"+lib_path+"')\n"

EXTRA_TEXT += """

import shutil
import tarfile
import zipfile
import urllib
import platform


INDEX_URL = 'http://pypi.python.org/simple/'


def extend_parser(parser):
    parser.add_option(
        '--index-url',
        metavar='INDEX_URL',
        dest='index_url',
        default='',
        help='base URL of Python Package Index')
    parser.add_option(
        '--type-install',
        metavar='type_install',
        dest='type_install',
        default='local',
        help='type install : local, url, setup')
    parser.add_option(
        '--ignore-packages',
        metavar='ignore_packages',
        dest='ignore_packages',
        default=None,
        help='list of comma separated keys for package to ignore')



def adjust_options(options, args):
    pass


def after_install(options, home_dir):
    home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
    base_dir = os.path.dirname(home_dir)
    src_dir = join(home_dir, 'src')
    tmp_dir = join(home_dir, 'tmp')
    ensure_dir(src_dir)
    ensure_dir(tmp_dir)
    system_str = platform.system()
    
    res_source_key = options.type_install
    
    ignore_packages = []
    
    if options.ignore_packages :
        ignore_packages = options.ignore_packages.split(",")
    
    logger.indent += 2
    try:
        NORMAL_INSTALL = [ #(key,method, option_str, extra_env)
            ('DISTRIBUTE', 'pip', None, None),
            ('MERCURIAL', 'pip', None, None),
            ]

            
        for key, method, option_str, extra_env in NORMAL_INSTALL:
            if key not in ignore_packages:
                normal_install(key, method, option_str, extra_env, res_source_key, home_dir, tmp_dir)
                        
        logger.notify("Clear source dir")
        shutil.rmtree(src_dir)

    finally:
        logger.indent -= 2
    script_dir = join(base_dir, bin_dir)
    logger.notify('Run "%s Package" to install new packages that provide builds'
                  % join(script_dir, 'easy_install'))


def normal_install(key, method, option_str, extra_env, res_source_key, home_dir, tmp_dir):
    logger.notify("Install %s from %s with %s" % (key,URLS[key][res_source_key],method))
    if method == 'pip':
        if sys.platform == 'win32':
            args = [os.path.abspath(os.path.join(home_dir, 'Scripts', 'pip')), 'install', '-E', os.path.abspath(home_dir), URLS[key][res_source_key]]
        else:
            args = [os.path.abspath(os.path.join(home_dir, 'bin', 'pip')), 'install', '-E', os.path.abspath(home_dir), URLS[key][res_source_key]]
        if option_str :
            args.insert(4,option_str)
        call_subprocess(args,
                cwd=os.path.abspath(tmp_dir),
                filter_stdout=filter_python_develop,
                show_stdout=True,
                extra_env=extra_env)
    else:
        if sys.platform == 'win32':
            args = [os.path.abspath(os.path.join(home_dir, 'Scripts', 'easy_install')), URLS[key][res_source_key]]
        else:
            args = [os.path.abspath(os.path.join(home_dir, 'bin', 'easy_install')), URLS[key][res_source_key]]
        if option_str :
            args.insert(1,option_str)
        call_subprocess(args,
                cwd=os.path.abspath(tmp_dir),
                filter_stdout=filter_python_develop,
                show_stdout=True,
                extra_env=extra_env)
    

def ensure_dir(dir):
    if not os.path.exists(dir):
        logger.notify('Creating directory %s' % dir)
        os.makedirs(dir)

def filter_python_develop(line):
    if not line.strip():
        return Logger.DEBUG
    for prefix in ['Searching for', 'Reading ', 'Best match: ', 'Processing ',
                   'Moving ', 'Adding ', 'running ', 'writing ', 'Creating ',
                   'creating ', 'Copying ']:
        if line.startswith(prefix):
            return Logger.DEBUG
    return Logger.NOTIFY
"""

def main():
    python_version = ".".join(map(str,sys.version_info[0:2]))
    text = virtualenv.create_bootstrap_script(EXTRA_TEXT, python_version=python_version)
    if os.path.exists(script_name):
        f = open(script_name)
        cur_text = f.read()
        f.close()
    else:
        cur_text = ''
    print 'Updating %s' % script_name
    if cur_text == 'text':
        print 'No update'
    else:
        print 'Script changed; updating...'
        f = open(script_name, 'w')
        f.write(text)
        f.close()

if __name__ == '__main__':
    main()

