import sys
import os
import platform
import ctypes
from shutil import copy, copytree
import argparse
import subprocess
jp = os.path.join

parser = argparse.ArgumentParser()
parser.add_argument('--daalroot', help='daal install root')
parser.add_argument('--version', help='expected version of pydaal')
args = parser.parse_args()
args.prefix = os.getenv('PREFIX')

# Need a particular license file for pydaal
copy(jp(os.environ['RECIPE_DIR'],'LICENSE'),os.getcwd())

os.environ['DAALROOT'] = args.daalroot
os.chdir('pydaal_sources')

# Check version
ver = subprocess.Popen(['python', 'setup.py', '--version'], stdout=subprocess.PIPE).communicate()[0].decode('ascii').strip()
assert ver == args.version, 'found pyDAAL version ' + ver + ' != ' + args.version

# Build pydaal
if platform.system() == 'Darwin':
    os.environ['LDFLAGS'] += ' -headerpad_max_install_names'
try:
    subprocess.check_call([sys.executable, 'setup.py', 'install', '--old-and-unmanageable'])
except subprocess.CalledProcessError:
    sys.exit("'python setup.py install' of pydaal failed. Check logs for compilation error.")

# Add the runtime libs
# FIXME: False until we can be sure we are not going to write to libs (try to patch them)
use_link = False

dstroot = args.prefix

if platform.system() == 'Windows':
    libroot = jp(args.daalroot, '..', 'redist', 'intel64_win', 'daal')
    filelist = [
        "daal_core.dll",
        "daal_sequential.dll",
        "daal_thread.dll",
    ]
    destdir = "DLLs"
    filemap = dict(zip(filelist,[destdir] * len(filelist)))
elif platform.system() == 'Linux':
    libroot = args.daalroot
    libroot = jp(libroot, 'lib', 'intel64_lin')
    filelist = [
        "libdaal_core.so",
        "libdaal_sequential.so",
        "libdaal_thread.so",
    ]
    destdir = "lib"
    filemap = dict(zip(filelist,[destdir] * len(filelist)))
elif platform.system() == 'Darwin':
    libroot = args.daalroot
    libroot = jp(libroot, 'lib')
    filelist = [
        "libdaal_core.dylib",
        "libdaal_sequential.dylib",
        "libdaal_thread.dylib",
    ]
    destdir = 'lib'
    filemap = dict(zip(filelist, [destdir] * len(filelist)))
    # Have to copy the libs on Mac so we can patch them
    use_link = False
else:
    raise "OS not supported"

if platform.system() == 'Windows':
    def win_hardlink(src,dst):
        if not ctypes.windll.kernel32.CreateHardLinkA(dst.encode(), src.encode(), 0):
            raise OSError
    hardlink = win_hardlink if use_link else copy
else:
    if use_link and libroot.startswith("/localdisk") and dstroot.startswith("/localdisk"):
        hardlink = os.link
    else:
        hardlink = copy

# Add pydaal examples to package
examples_dir = jp(os.environ['SRC_DIR'], 'examples', 'python')
examples_dest = jp(args.prefix, 'share', 'pydaal_examples', 'examples', 'python')
copytree(examples_dir, examples_dest)

# Add data files for examples
data_dir = jp(os.environ['SRC_DIR'], 'examples', 'data')
data_dest = jp(args.prefix, 'share', 'pydaal_examples', 'examples', 'data')
copytree(data_dir, data_dest)

for f, dest in filemap.items():
    dstpath = jp(dstroot,dest)
    if not os.path.isdir(dstpath):
        os.makedirs(dstpath)
    srcpath = jp(libroot,f)
    bn = os.path.basename(srcpath)
    dstpath = jp(dstpath,bn)
    hardlink(srcpath,dstpath)
