# vi: syntax=python
import glob, os, re

def revision(**kw):
    # update the revision
    revision = os.popen("svnversion -n").read()
    print "Setting revision to %s." % revision
    f = file("c/version.c")
    t = re.sub(r"\$Revision.*?\$", "$Revision %s$" % revision, f.read())
    f.close()
    file("c/version.c", "w").write(t)

# We put all generated files into this directory, but scons can't create it itself
try: os.mkdir("scons")
except OSError: pass

# program name is like directory name
PROGRAM_NAME = os.path.split(os.getcwd())[1]

# Cross compile using mingw
crosscompile = ARGUMENTS.get("crosscompile", "")

debug = ARGUMENTS.get("debug", "")
profile = ARGUMENTS.get("profile", "")
efence = ARGUMENTS.get("efence", "")

pyfiles = glob.glob("src/*.py")
pyfiles += glob.glob("src/*/*.py")

extrafiles = []

# Environment to generate includes.
includeenv = Environment(ENV = {'PATH' : os.environ['PATH']})
includeenv.SConsignFile("scons/signatures")
includeenv.BuildDir("include/land", "src", duplicate = False)
# This means, if the same .c or .h is created, then it should be treated as
# unmodified (does this really work?)
includeenv.TargetSignatures("content")

includeenv.BuildDir("c", "src", duplicate = False)

# Main environment.
env = Environment()

for py in pyfiles:
    h = "c/" + py[4:-3] + ".h"
    c = "c/" + py[4:-3] + ".c"
    name = py[4:-3]
    includeenv.Command([c, h], py, "./scramble.py -i %s -c %s -h %s -n %s" % (py, c, h, name))

includeenv.AlwaysBuild("c/version.c")
includeenv.AddPostAction("c/version.c", revision)

print "platform", env["PLATFORM"]
print crosscompile and "cross" or "native", debug and "debug" or "release", "build"

env.SConsignFile("scons/signatures")

env.Append(CCFLAGS = "-g")
env.Append(CCFLAGS = "-W -Wall")
env.Append(CCFLAGS = "-Wmissing-prototypes -Wstrict-prototypes")
env.Append(CCFLAGS = "-Wshadow")
env.Append(CCFLAGS = "-Wpointer-arith -Wcast-align")
env.Append(CCFLAGS = "-Wwrite-strings -Wsign-compare")
env.Append(CCFLAGS = "-Wmissing-noreturn -Wredundant-decls")
env.Append(CCFLAGS = "-Wpacked")
env.Append(CCFLAGS = "-Wdisabled-optimization")
#env.Append(CCFLAGS = "-Wunreachable-code")
env.Append(CCFLAGS = "-Wmissing-declarations")
env.Append(CCFLAGS = "-Wno-unused-parameter")
env.Append(CCFLAGS = "--std=c99")

env.Append(CCFLAGS = "-O3")
BUILDDIR = "scons/build/%s/release" % (env["PLATFORM"])

env.Append(CPPPATH = ["c"])

env.ParseConfig("allegro-config --shared release")

env.Append(LIBS = ["agl", "GL", "GLU", "freetype",
    "fudgefont", "ldpng", "png", "jpgal", "aldmb", "dumb",
    "apeg", "theora", "vorbis", "ogg"])

env.ParseConfig("allegro-config --cflags release")

duplicate = False

env.BuildDir(BUILDDIR, "c", duplicate = duplicate)
sources = [BUILDDIR + "/" + x[4:-3] + ".c" for x in pyfiles]
program = env.Program(PROGRAM_NAME, sources + extrafiles)
env.Default(["src", program])

