#!/usr/bin/python
# Project: Soar <http://soar.googlecode.com>
# Author: Mazin Assanie

import os
import sys

Import('env', 'InstallDir')
clone = env.Clone()

# Set up variables (some are hardcoded for now)
LIB_NAME = 'tclsoarlib'

if clone.PrepareForCompilingWithTcl(clone["TCL_PATH"], clone["TCL_SUFFIX"]):
    print(f'{env["INDENT"]}TclSoarLib is buildable')
elif clone['TCL_REQUIRED']:
    raise ValueError('Tcl was requested by user explicitly, but Tcl is not available')
else:
    print(f'{env["INDENT"]}TclSoarLib is *not* buildable')
    Return()

# Add include directories not related to Tcl
include_dirs = [ clone.Dir(('#Core/%s/src') % d).abspath for d in 'ElementXML'.split() ]
includes = ' '.join(' -I%s' % d for d in include_dirs)
cpps = ' '.join(' %s' % d for d in include_dirs)
clone.Append(CXXFLAGS = Split('-I' + includes))
clone.Append(CPPPATH = Split(cpps))

# Set up non-Tcl-related compiler flags
clone.Append(CPPFLAGS = ['-w'])

# Prevent "Command line warning D9025 : overriding '/W2' with '/w'"
if '/W2' in clone['CPPFLAGS']:
  clone['CPPFLAGS'].remove('/W2')

if os.name == 'posix':
    clone.Append(CXXFLAGS = Split('-Wno-unused -fno-strict-aliasing'))

if sys.platform == 'darwin':
    install_name = os.path.join('@loader_path', clone['LIBPREFIX'] + 'TclSoarLib' + clone['SHLIBSUFFIX'])
    clone.Append(LINKFLAGS = ['-install_name', install_name])

elif sys.platform.startswith('linux'):
    clone.Append(LIBS = ['Soar'])
elif sys.platform == 'win32':
    # Windows DLLs need to get linked to dependencies, whereas Linux and Mac shared objects do not
    # (not sure if this is really needed for TclSoarLib)
    clone.Append(LIBS = ['advapi32'])
    clone.Append(LIBS = ['Soar'])

# Copy tcl scripts that library needs
tcl_scripts = InstallDir(clone, clone['OUT_DIR'] + '/tcl', 'tcl')

# Create the TclSoarLib dll and tclindex file
lib = clone.SharedLibrary(LIB_NAME, Glob('src/*.cpp'))[0]

# Install TclSoarLib and return
t = clone.Install(clone.Dir(clone['OUT_DIR']), lib)
clone.Alias('tclsoarlib', [t, tcl_scripts])
