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

Import("environment rejoy_build_shared")

# We use cxxflags.txt as a pseudo-source.
# This is used by both Cargo and SCons to force a rebuild if CXXFLAGS change.
# It might be possible to avoid this if we could build the shim within SCons,
# however since it requires some files generated by the Rust build script we
# would need to invoke the Rust build process multiple times.
#
# This also allows us to (potentially) parse the args here in Python and then
# give them as line-separated strings to Rust, then std::process::Command::args
# will properly understand them.

env = os.environ

# Set the CXX/CC value to be consumed by Cargo
env["CXX"] = str(environment["CXX"])
env["CC"] = str(environment["CC"])

# Pass the location of rejoy_util in an environment variable.

DELIMIT = '\n'
CXXFLAGSPATH = "cxxflags.txt"

# Write the CXX flags, if they have changed.
cxxflags_file = None
try:
    cxxflags_file = open(CXXFLAGSPATH, "r")
    cxxflags = cxxflags.read()
except:
    cxxflags = ""
finally:
    if cxxflags_file:
        cxxflags_file.close()

# Construct the new flags
new_cxxflags = str(environment["CXXFLAGS"]).split()
if rejoy_build_shared and "-fPIC" not in new_cxxflags and "-fpic" not in new_cxxflags:
    new_cxxflags.append("-fPIC")
old_cxxflags = cxxflags.split(DELIMIT)

if new_cxxflags != old_cxxflags:
    cxxflags_file = open(CXXFLAGSPATH, "w")
    cxxflags_file.write(DELIMIT.join(new_cxxflags))
    cxxflags_file.close()

rust_lib="librejoy_evdev" + environment['LIBSUFFIX']
src = []

for s in ("rejoy_evdev.hpp", "rejoy_evdev.cpp", "build.rs", CXXFLAGSPATH):
    src.append(os.path.join(os.getcwd(), s))
for s in glob.glob("Cargo.*") + glob.glob("src/*.rs"):
    src.append(os.path.join(os.getcwd(), s))

rejoy_evdev_rs = environment.Command(
    target=os.path.join(os.getcwd(), "target", "debug", rust_lib),
    source=src,
    action="cargo build",
    chdir=os.getcwd())

Return("rejoy_evdev_rs")
