# skip-if: True

import os
import sys
import subprocess
sys.path.append(os.path.dirname(__file__) + "/../lib")
from test_helper import run_test

"""
Using this test file.

The /bin/python is the pyston executable so if you recompile pyston, you need to run this
script again to update it.

"""

def print_progress_header(text):
    print "\n>>>"
    print ">>> " + text + "..."
    print ">>>"

ENV_NAME = "zope_test_env_" + os.path.basename(sys.executable)
DEPENDENCIES = ["nose==1.3.7", "six"]
SRC_DIR = ENV_NAME
PYTHON_EXE = os.path.abspath(ENV_NAME + "/bin/python")
EASY_INSTALL_EXE = os.path.abspath(ENV_NAME + "/bin/easy_install")
MK_ZOPE_INSTANCE_EXE = os.path.abspath(ENV_NAME + "/bin/mkzopeinstance")
HOME_DIR = os.path.expanduser('~')
ZOPE_DIR = HOME_DIR + '/Zope-2.13.24-pakcages'
ZOPE_ENV_PATH = os.path.abspath(ENV_NAME)
INSTANCE_DIR = os.path.abspath(ENV_NAME + "/instance")

def creat_zope_virtual_dir():
    if not os.path.exists(ENV_NAME) or os.stat(sys.executable).st_mtime > os.stat(ENV_NAME + "/bin/python").st_mtime:
        print "Creating virtualenv to install testing dependencies..."
        VIRTUALENV_SCRIPT = os.path.dirname(__file__) + "/../lib/virtualenv/virtualenv.py"

        try:
            args = [sys.executable, VIRTUALENV_SCRIPT, "-p", sys.executable, ENV_NAME]
            print "Running", args
            subprocess.check_call(args)

            subprocess.check_call([ENV_NAME + "/bin/pip", "install"] + DEPENDENCIES)
        except:
            print "Error occurred; trying to remove partially-created directory"
            ei = sys.exc_info()
            try:
                subprocess.check_call(["rm", "-rf", ENV_NAME])
            except Exception as e:
                print e
            raise ei[0], ei[1], ei[2]


import shutil
def mk_ZOPE_DIR():
    # Make sure we are in a clean dir.
    if os.path.exists(ZOPE_DIR):
        shutil.rmtree(ZOPE_DIR)

    os.makedirs(ZOPE_DIR)

# ********************************
# ********************************
# **** Modified Zope Packages ****
# ********************************
# ********************************
modified_list = [
        ("Acquisition-2.13.9", "https://lab.nexedi.com/Daetalus/Acquisition-2.13.9/repository/archive.zip?ref=pyston_patch"),
        ("AccessControl-2.13.14", "https://lab.nexedi.com/Daetalus/AccessControl-2.13.14/repository/archive.zip?ref=master"),
        ("ExtensionClass-2.13.2", "https://lab.nexedi.com/Daetalus/ExtensionClass-2.13.2/repository/archive.zip?ref=pyston_patch"),
        ("zope.container-3.11.2", "https://lab.nexedi.com/Daetalus/zope.container-3.11.2/repository/archive.zip?ref=pyston_patch"),
        ("zope.proxy-3.6.1", "https://lab.nexedi.com/Daetalus/zope.proxy-3.6.1/repository/archive.zip?ref=pyston_patch"),
        ("zope.security-3.7.4", "https://lab.nexedi.com/Daetalus/zope.security-3.7.4/repository/archive.zip?ref=pyston_patch"),
        ("DocumentTemplate-2.13.2", "https://lab.nexedi.com/Daetalus/DocumentTemplate-2.13.2/repository/archive.zip?ref=pyston_patch"),
        ("RestrictedPython-3.6.0", "https://lab.nexedi.com/Daetalus/RestrictedPython-3.6.0/repository/archive.zip?ref=pyston_patch"),
        ("ZODB3-3.10.5", "https://lab.nexedi.com/Daetalus/ZODB3-3.10.5/repository/archive.zip?ref=pyston_patch"),
        ("Zope2-2.13.24", "https://lab.nexedi.com/Daetalus/Zope2-2.13.24/repository/archive.zip?ref=master"),]

# Download zope packages except the packages listed in modified_list
zope_packages = open(os.path.dirname(__file__) + "/getZope.sh")
zope_download_list = zope_packages.read().splitlines()

m_pkg_link = []
um_pkg_link = []

for each_pkg in zope_download_list:
    modified = None
    for modified_pkg in modified_list:
        pkg_name = modified_pkg[0]
        pkg_link = modified_pkg[1]
        a = pkg_name in each_pkg
        if pkg_name in each_pkg:
            modified = modified_pkg
            m_link = ''.join(['wget ', pkg_link, ' -O ', pkg_name, '.zip'])
            m_pkg_link.append(m_link)
            break
    if modified is None:
        um_pkg_link.append(each_pkg)
    else:
        modified_list.remove(modified)

# print(zope_download_list)
# print(um_pkg_link)

print(len(zope_download_list))
print(len(um_pkg_link))
print(m_pkg_link)


# the package list is something like
# ['wget url', 'wget url'...]
def download_zope_packages(package_list):
    for each_line in package_list:
        commands = each_line.split(' ')
        subprocess.check_call(commands, cwd=ZOPE_DIR)


def createZopeInstance():
    try:
        print_progress_header("Creating Zope instance")
        commands = [MK_ZOPE_INSTANCE_EXE, '-d', INSTANCE_DIR, '-u', 'nexedi:270']
        print(commands)
        subprocess.check_call(commands, cwd=ZOPE_ENV_PATH)
    except:
        raise


def buildZope():
    try:
        print_progress_header("Building Zope packages")
        commands = [EASY_INSTALL_EXE, '-H', 'None', '-i', ZOPE_DIR, 'Zope2']
        # print(ZOPE_DIR)
        # print(ZOPE_ENV_PATH)
        # print(EASY_INSTALL_EXE)
        subprocess.check_call(commands, cwd=ZOPE_ENV_PATH)
    except:
        raise

creat_zope_virtual_dir()
# mk_ZOPE_DIR()
# download_zope_packages(um_pkg_link)
download_zope_packages(m_pkg_link)
buildZope()
createZopeInstance()



print("Passed")
