# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/

import os
import sys
import glob

def GetLinkableLibrary(lib):
    if os.name == 'nt':
        if len(lib) == 1:
            return lib[0]
        else:
            return lib[1]

AddOption('--target', dest = 'target', nargs=1, action='store', help =
"Override target architecture.")

new_target = GetOption('target')
if new_target:
    print("Using target architecture " + new_target)
    environment = Environment(ENV = os.environ, TARGET_ARCH=new_target)
else:
    environment = Environment(ENV = os.environ)

rejoy_drivers = []

AddOption('--enable-xinput', dest = 'enable-xinput', nargs=1, action='store', help =
"Use XInput, disabled by default.")

AddOption('--enable-dinput', dest = 'enable-dinput', nargs=1, action='store', help =
"Use DirectInput, enabled by default on Windows.")

AddOption('--enable-bsd', dest = 'enable-bsd', nargs=1, action='store', help =
"Use the BSD backend libusbhid, enabled by default on BSD systems")

AddOption('--enable-evdev', dest = 'enable-evdev', nargs=1, action='store', help =
"Use the evdev backend, enabled by default on Linux and FreeBSD systems")

AddOption('--build-shared', dest = 'build-shared', nargs=1, action='store', help =
"Build shared library, disabled by default.")

AddOption('--build-shared-modules', dest = 'build-shared-modules', nargs=1, action='store', help =
"Build driver modules as shared libraries, disabled by default.")

CC = environment["CC"]
if CC == "cl":
    environment.Append(
        CCFLAGS=" /W3 /EHsc /Zi ",
        LINKFLAGS="/DEBUG")    
else:
    environment.Append(
        CXXFLAGS=" -std=c++98 -fno-rtti -fno-exceptions -Os ",
        CFLAGS=" -ansi -O2",
        LINKFLAGS=" -g",
        CCFLAGS="-g  -Wall -Wextra -pedantic ")
    if 'openbsd' in sys.platform.lower():
        environment.Append(CCFLAGS=" -fstrict-aliasing")

def DefaultDriverOption(Driver, Default):
    if Default:
        if GetOption('enable-' + Driver) != 'n':
            rejoy_drivers.append(Driver)
    else:
        if GetOption('enable-' + Driver) == 'y':
            rejoy_drivers.append(Driver)

DefaultDriverOption('xinput', os.name == 'nt')
DefaultDriverOption('dinput', os.name == 'nt')
DefaultDriverOption('bsd', 'bsd' in sys.platform.lower())
DefaultDriverOption('evdev', 'freebsd' in sys.platform.lower() or 'linux' in sys.platform.lower())

if os.name == 'nt':
    rejoy_build_shared = True

if GetOption('build-shared') == 'y':
    rejoy_build_shared = True
elif GetOption('build-shared') == 'n' or os.name != 'nt':
    rejoy_build_shared = False

if GetOption('build-shared-modules') == 'y':
    rejoy_build_shared_modules = True
    if os.name == 'nt':
        rejoy_build_shared = True # Required on Windows.
else:
    rejoy_build_shared_modules = False

if rejoy_build_shared:
    if os.name == 'nt':
        environment.Append(CPPDEFINES=["REJOY_INTERNAL_DLL=1"])
    environment.Append(CPPDEFINES=["REJOY_SHARED=1"])
else:
    environment.Append(CPPDEFINES=["REJOY_SHARED=0"])

rejoy_util = SConscript(dirs=["util"], exports=["CC", "environment"])

environment.Append(CPPPATH=os.path.join(os.getcwd(), "util"))

# Default source
rejoy_source = ["rejoy.cpp", "rejoy_c.cpp"]
rejoy_libs = []

# Dict of libraries indexed by driver backend.
rejoy_lib_dict = {
    "dinput":["dinput8", "dxguid.lib", "user32"],
    "xinput":["xinput"],
    "bsd":["usbhid"],
    "evdev":["dl", "pthread"]
}

# Drivers which require the Unix source to be included.
rejoy_unix_drivers = (
    "bsd",
    "joy",
    "evdev"
)

# Add up the drivers, also checking for requirement of unix.
use_unix = False
for driver in rejoy_drivers:
    if driver in rejoy_unix_drivers:
        use_unix = True
        break

if use_unix:
    rejoy_unix = SConscript(dirs=["unix"], exports=["environment"])

depends_on_unix = []
for driver in rejoy_drivers:
    if driver in rejoy_lib_dict:
        rejoy_libs += rejoy_lib_dict[driver]
    # Check if there is a SConscript file to read or not.
    if os.path.isfile(os.path.join(driver, "SConscript")):
        lib = SConscript(dirs=[driver], exports=["CC", "environment", "rejoy_build_shared"])
        rejoy_libs.append(lib)
        if driver in rejoy_unix_drivers:
            environment.Depends(lib, rejoy_unix)
            environment.Depends(lib, rejoy_util)
    else:
        rejoy_source += glob.glob(os.path.join(driver, "*.cpp"))
        rejoy_source += glob.glob(os.path.join(driver, "*.c"))
    environment.Append(CPPDEFINES=["REJOY_DRIVER_" + driver.upper() + "=1"])

rejoy_dep_libs = rejoy_libs + [rejoy_util]
if use_unix:
    rejoy_dep_libs.append(rejoy_unix)

if rejoy_build_shared:
    rejoy = environment.SharedLibrary('rejoy', rejoy_source, LIBS=rejoy_dep_libs)
else:
    rejoy = environment.StaticLibrary('rejoy', rejoy_source, LIBS=rejoy_dep_libs)

if not rejoy_build_shared:
    demo_libs = [rejoy] + rejoy_libs + [rejoy_util]
    if use_unix:
        demo_libs.append(rejoy_unix)
else:
    demo_libs = [rejoy]

demo = environment.Program(['rejoy_demo.cpp'],  LIBS=demo_libs)

# AlwaysBuild(rejoy)
