# Copyright Thomas Nagy 2005
# Copyright Ralf Habacker 2005
# BSD license (see COPYING)
def exists(env):
	return true

def findFileInPath( paths, file ):
	import os, fnmatch;

	for p in paths:
		for path, subdirs, files in os.walk( p ):
			for name in files:
				if fnmatch.fnmatch( name, file ):
					return path
	return None

def check_for_lib( env, name, incpaths, includes, libpaths, libs ):
	if env['CC'] == 'cl':
		libext	= '.lib'
	else:
		libext	= '.a'

	path = incpaths
	if env.has_key('EXTRAINCLUDES'):
		path += env['EXTRAINCLUDES']
	
	hpaths = []
	for h in includes:
		p = findFileInPath( path, h )
		if p == None:
			return 0
		found = False
		for t in hpaths:
			found = ( t == p )
			if found:
				break
		if not found:
			hpaths.append( p )

	path = libpaths
	if env.has_key('EXTRALIBS'):
		path += env['EXTRALIBS']
	lpaths = []
	for l in libs:
		p = findFileInPath( path, l+libext )
		if p == None:
			return 0
		found = False
		for t in lpaths:
			found = ( t == p )
			if found:
				break
		if not found:
			lpaths.append( p )

	env['CACHED_'+name ]  = 1
	env['CCFLAGS_'+name ] = [ '-DHAVE_'+name ]
	env['CPPPATH_'+name ] = hpaths
	env['LIBPATH_'+name ] = lpaths
	env['LIB_'+name]	  = libs
	
	return 1

def generate(env):

	def Check_libpng(context):
		import SCons.Util
		context.Message('Checking for libpng... ')
		ret = 0

		if env['WINDOWS']:
			ret = check_for_lib( env, 'PNG', ['c:\\png\\include'], ['png.h','pngconf.h'], ['c:\\png\\lib'], ['libpng'] )

		context.Result(ret)
		return ret

	from SCons.Options import Options
	from SCons.Tool import Tool
	import os

	optionFile = env['CACHEDIR'] + 'libpng.cache.py'
	opts = Options(optionFile)
	opts.AddOptions(
		('CACHED_PNG', 'Whether libpng is available'),
		('CXXFLAGS_PNG',''),
		('CCFLAGS_PNG',''),
		('LINKFLAGS_PNG',''),
		('CPPPATH_PNG',''),
		('LIB_PNG',''),
		('LIBPATH_PNG',''),
		)
	opts.Update(env)
	opts.Save(optionFile, env)

	if not env['HELP'] and (env['_CONFIGURE_'] or not env.has_key('CACHED_PNG')):
		if env['WINDOWS']:
			conf = env.Configure(custom_tests =	 { 'Check_libpng' : Check_libpng} )
			have_png = conf.Check_libpng()
			if not have_png:
				print 'libpng not found (mandatory).'
			env = conf.Finish()
		else:
			env['CACHED_PNG'] = 0
			pkgs = Tool('pkgconfig', ['./bksys'])
			pkgs.generate(env)

			have_png = env.pkgConfig_findPackage('PNG', 'libpng', '1.0')

    		dest=open(env.join(env['_BUILDDIR_'], 'config-libpng.h'), 'w')
    		dest.write('/* libpng configuration created by bksys */\n')
		if have_png:
			dest.write('#define HAVE_LIBPNG_H 1\n');
			env['CACHED_PNG'] = 1
		dest.close()
		env['_CONFIG_H_'].append('libpng')
		opts.Save(optionFile, env)
