# Part of the A-A-P recipe executive: Testing of automatic dependencies

# Copyright (C) 2002-2003 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

#
# Building two programs from the same source file, using a different CPPFLAGS
# value.  Check that the file is compiled twice and the dependencies are
# checked twice.  Also check that cleanup removes both dependency recipes.
#
# Requires a C compiler.
#

import sys, os, shutil, glob, string

def runaap(args):
    return os.system("%s ..%sMain.py %s" % (sys.argv[1], os.sep, args))

os.chdir("rectest")

# Create a recipe with a different filetype for the target, so that a different
# build action will be used.
# Check that the right action is used.
rec = "rectest.aap"
out = "rectest.out"
inp = "rectest.c"
if os.name in [ 'nt', 'dos', 'os2' ]:
    obj = "rectest.obj"
    prog1 = "rectestprog1.exe"
    prog2 = "rectestprog2.exe"
else:
    obj = "rectest.o"
    prog1 = "rectestprog1"
    prog2 = "rectestprog2"

def cleanup():
    for file in [ rec, out, inp, prog1, prog2 ]:
	try:
	    os.remove(file)
	except:
	    pass
    try:
	for dir in glob.glob('build-*'):
	    shutil.rmtree(dir)
    except:
	pass

cleanup()

# Create the recipe.
f = open(rec, "w")
f.write("""
BDIR = build-one
:program %s : %s {var_CPPFLAGS = -Done}
BDIR = build-two
:program %s : %s {var_CPPFLAGS = -Dtwo}
""" % (prog1, inp, prog2, inp))
f.close()


# Create the source file.
f = open(inp, "w")
f.write("""
#include <stdio.h>
int main() { printf("Hello World!\\n"); return 0;}
""")
f.close()

def check_out(expected):
    f = open(out)
    actual = f.read()
    f.close()
    actual = string.replace(actual, "\\", "/")
    if actual != expected:
        print "Expected:\n-----\n%s-----\n" % expected
        print "Got:\n-----\n%s-----\n" % actual
        return 1
    return 0

def doit():
    res = 0

    # Build the programs.
    if runaap("-f %s >%s" % (rec, out)):
        print "Building failed"
        res = 1
    else:
        # Check that all the expected output files exist.
        for n in [ "build-one/%s.aap" % inp,
                   "build-one/%s" % obj,
                   prog1,
                   "build-two/%s.aap" % inp,
                   "build-two/%s" % obj,
                   prog2 ]:
            try:
                f = open(n)
                f.close()
            except:
                print "Could not open %s" % n
                res = 1

    # Cleanup.
    if runaap("-f %s clean >%s" % (rec, out)):
        print "Cleaning failed"
        res = 1
    else:
        res = res + check_out("""Aap: Deleted "build-one/%s.aap"
Aap: Deleted "build-one/%s"
Aap: Deleted "%s"
Aap: Deleted "build-two/%s.aap"
Aap: Deleted "build-two/%s"
Aap: Deleted "%s"
""" % (inp, obj, prog1, inp, obj, prog2))

    return res

res = doit()

cleanup()

sys.exit(res)


# vim: set sw=4 et sts=4 tw=79 fo+=l:
