#!/usr/bin/python
import os
import glob
import sys

options = Options('options.cache', ARGUMENTS)
options.Add(PathOption('install_prefix', 'The prefix where the application will be installed', ''))
options.Add(PathOption('clam_prefix', 'The prefix where CLAM was installed', ''))
options.Add(BoolOption('release', 'Enabling compiler optimizations', 'no') )
options.Add(BoolOption('verbose', 'Display the full command line instead a short command description', 'no') )


def scanFiles(pattern, paths) :
	files = []
	for path in paths :
		files+=glob.glob(os.path.join(path,pattern))
	return files

def recursiveDirs(root) :
	return filter( (lambda a : a.rfind( ".svn")==-1 ),  [ a[0] for a in os.walk(root)]  )


env = Environment(ENV=os.environ, tools=['default'], options=options)
options.Save('options.cache', env)
Help(options.GenerateHelpText(env))

env.SConsignFile() # Single signature file

CLAMInstallDir = env['clam_prefix']
clam_sconstoolspath = os.path.join(CLAMInstallDir,'share','clam','sconstools')
CLAMVmQtPath = 'vmqt'

env.Tool('qt4', toolpath=[clam_sconstoolspath])
env.Tool('clam', toolpath=[clam_sconstoolspath])
env.Tool('nsis', toolpath=[clam_sconstoolspath])
if sys.platform=='darwin' : env.Tool('bundle', toolpath=[clam_sconstoolspath])
env.Tool('dmg', toolpath=[clam_sconstoolspath])
sys.path.append(clam_sconstoolspath)
import versionInfo
version, fullVersion = versionInfo.takeFromChangeLog("CHANGES", "MusicAnnotator")
print "Version: ", version
print "Package version: ", fullVersion
versionInfo.generateVersionSources(os.path.join('src','MusicAnnotatorVersion'), "MusicAnnotator", fullVersion)



env['CXXFILESUFFIX'] = '.cxx'
env['QT4_UICDECLSUFFIX'] = '.hxx'
env['QT4_MOCHPREFIX'] = os.path.join('generated','moc_')
env['QT4_UICDECLPREFIX'] = os.path.join('generated','ui_')
env['QT4_QRCCXXPREFIX'] = os.path.join('generated','qrc_')
if not env['verbose']:
	env['CXXCOMSTR'] = '== Compiling $SOURCE'
	env['LINKCOMSTR'] = '== Linking $TARGET'
	env['SHLINKCOMSTR'] = '== Linking library $TARGET'
	env['QT4_RCCCOMSTR'] = '== Embeding resources $SOURCE'
	env['QT4_UICCOMSTR'] = '== Compiling interface $SOURCE'
	env['QT4_LRELEASECOMSTR'] = '== Compiling translation $TARGET'
	env['QT4_MOCFROMHCOMSTR'] = '== Generating metaobjects for $SOURCE'
	env['QT4_MOCFROMCXXCOMSTR'] = '== Generating metaobjects for $SOURCE'

env.EnableClamModules([
	'clam_core',
	'clam_audioio',
	'clam_processing',
	] , CLAMInstallDir)

env.EnableQt4Modules([
	'QtCore',
	'QtGui',
	'QtOpenGL',
#	'QtSql',
#	'QtNetwork',
#	'QtTest',
#	'QtXml',
#	'QtSvg',
#	'Qt3Support',
	], debug=False)

mainSources = {
	'Annotator' : os.path.join('src','main.cxx'),
	'ClamExtractorExample' : os.path.join('src','ClamExtractorExample.cxx'),
}

sourcePaths = [
	'src',
	os.path.join('src','generated'),
	os.path.join('src','InstantViews'),
	os.path.join('src','InstantViews','generated'),
]
extraPaths = []
extraPaths += recursiveDirs(CLAMVmQtPath+"/plot")
extraPaths += recursiveDirs(CLAMVmQtPath+"/render")
extraPaths += recursiveDirs(CLAMVmQtPath+"/data")
extraPaths += recursiveDirs(CLAMVmQtPath+"/util")
extraPaths += recursiveDirs(CLAMVmQtPath+"/player")
extraPaths += recursiveDirs(CLAMVmQtPath+"/misc")
extraPaths += recursiveDirs(CLAMVmQtPath+"/widget")
extraPaths += [
	CLAMInstallDir+'/include',
	CLAMInstallDir+'/include/CLAM', # KLUDGE to keep old style includes
	os.path.join('SimacServicesClient'),
	os.path.join('SimacServicesClient','generated'),
]
includePaths = sourcePaths + extraPaths

sources = scanFiles('*.cxx', sourcePaths)
sources = filter( (lambda a : a.rfind( "moc_")==-1 ),  sources )
sources = filter( (lambda a : a.rfind( "qrc_")==-1 ),  sources )
sources = dict.fromkeys(sources).keys()
for mainSource in mainSources.values() :
	sources.remove(mainSource)

qrcfiles = scanFiles("*.qrc", sourcePaths)
if qrcfiles : sources += env.Qrc(source=qrcfiles)

uifiles = scanFiles("*.ui", sourcePaths)
if uifiles: uiheaders = env.Uic4(source=uifiles)

if sys.platform=="win32" :
	sources += env.RES(source=["resources/Annotator.rc"])

env.Append(CPPPATH=includePaths)
env.Append(LIBPATH=[CLAMVmQtPath])
env.Append(LIBS="clam_vmqt4")
if sys.platform=='darwin' :
	env.Append(CPPFLAGS='-DRESOURCES_BASE="\\"Annotator.app/Contents/Resources\\""')
else :
	env.Append(CPPFLAGS='-DRESOURCES_BASE="\\"' + env['install_prefix'] + '/share/annotator\\""')
if sys.platform=='win32' :
	env.Append(CPPFLAGS=['-D_USE_MATH_DEFINES']) # to have M_PI defined
else:
	# TODO: This should not be hardcoded neither install_prefix (because package intall)
	env.Append(CPPFLAGS='-DDATA_EXAMPLES_PATH="\\"%s\\""'%env['install_prefix'] + '/share/annotator/example-data')

if sys.platform=='linux2' :
	if env['release'] :
		env.Append( CCFLAGS=['-g','-O3','-fomit-frame-pointer','-Wall'] )
	else :
		env.Append( CCFLAGS=['-g', '-Wall'] )
#	env.Append( LINKFLAGS=['-rdynamic'] ) # TODO: Is it needed?


programs = []
for main in mainSources.items() :
#	print sources , main
	programs += [ env.Program(target=main[0], source = sources+[main[1]]) ]

manpages = [
	'resources/man/man1/Annotator.1',
	'resources/man/man1/ClamExtractorExample.1',
	]
example_data = [
	'Samples/Chords.pro'
	]

chordSources = scanFiles("*.cxx", ["src/ChordExtractor"])
chordSources = filter ( (lambda a : a.rfind( "Test")==-1 ),  chordSources )
chordSources = filter ( (lambda a : a.rfind( "cppunit")==-1 ),  chordSources )

programs += [ env.Program(target='ChordExtractor', source = chordSources) ]

"""
onsetSources = scanFiles("*.cpp", ["src/OnsetExtractor"])
onsetSources = filter ( (lambda a : a.rfind( "Test")==-1 ),  onsetSources )
onsetSources = filter ( (lambda a : a.rfind( "cppunit")==-1 ),  onsetSources )
programs += [ env.Program(target='OnsetExtractor', source = onsetSources, LIBS=['fftw3','sndfile']) ]
"""

env.Uic4(source="SimacServicesClient/GUI.ui")
bocaClientSources = [
	"SimacServicesClient/BocaClientMain.cxx",
	env.Moc4("SimacServicesClient/BocaClientGui.hxx"),
	"SimacServicesClient/BocaTaskRunner.cxx",
]
programs += [ env.Program(target="BocaClient", source = bocaClientSources) ]


# Manual step: lupdate-qt4 *xx *ui -ts Annotator_ca.ts
tsfiles = scanFiles("*.ts", ["src/i18n/"])
env.Precious(tsfiles) # TODO: this is not enough!! scan -c will delete ts files!!!
translatableSources = scanFiles('*.cxx', sourcePaths);
translatableSources+= scanFiles('*.hxx', sourcePaths);
translatableSources+= scanFiles('*.ui', sourcePaths);
translatableSources = filter( (lambda a : a.rfind( "generated/")==-1 ),  translatableSources )
translations = []
if len(tsfiles) : 
#	tsNodes = env.Ts(target=tsfiles, source = translatableSources)
	translations = env.Qm(source = tsfiles)


examples = []
for ext in ['pro', 'sc']:
	examples += scanFiles('*.%s'%ext, ['Samples'])

song_examples = []
for ext in ['pool', 'chords', 'mp3', 'wav', 'ogg']:
	song_examples += scanFiles('*.%s'%ext, ['Samples/SongsTest'])

menuEntries = glob.glob('resources/*.desktop')

installation = {
	'/bin' : programs,
	'/share/applications': menuEntries,
	'/share/man/man1' : manpages,
	'/share/annotator/i18n': translations,
	'/share/annotator/example-data': examples,
	'/share/annotator/example-data/SongsTest': song_examples,
}

installTargets = [
	env.Install( env['install_prefix']+path, files ) for path, files in installation.items() ]

if sys.platform=='win32' : 
	installTargets += [
		env.Install(
			env['install_prefix']+"/bin", 
			os.path.join(env['QTDIR'],'lib',"Qt"+dll+"4.dll")
			) for dll in 'Core', 'Gui', 'OpenGL']
	env.Append(NSIS_OPTIONS=['/DVERSION=%s' % fullVersion ])
	env.Append(NSIS_OPTIONS=['/DQTDIR=$QTDIR'])
	externalsDllDir = os.environ['EXTERNALDLLDIR']
	env.Append(NSIS_OPTIONS=['/DEXTERNALDLLDIR=%s' % externalsDllDir ])
	# Get the visual studio runtimes path
	for vcRuntimeDir in os.environ['PATH'].split(";") :
		vcRuntimeDir = os.path.normpath(vcRuntimeDir)
		if os.access(os.path.join(vcRuntimeDir,"msvcr71.dll"),os.R_OK) :
			break
	env.Append(NSIS_OPTIONS=['/DVCRUNTIMEDIR=%s' % vcRuntimeDir ])
	win_packages = [env.Nsis( source='resources\\clam_annotator.nsi')]
	env.Alias('package', win_packages)

if sys.platform=='darwin' :
	# TODO: Review why those flags were added# TODO: Review why those flags were added# TODO: Review why those flags were added
	env.Append(CPPFLAGS='-DRESOURCES_BASE="\\"Annotator.app/Contents/Resources\\""')
	env.AppendUnique( LINKFLAGS=['-dynamic','-bind_at_load'])

	#TODO install resources
	installTargets = []
	
	mac_bundle = env.Bundle( 
		BUNDLE_NAME='Annotator', 
		BUNDLE_BINARIES=programs,
		BUNDLE_RESOURCEDIRS=['foo','bar'],
		BUNDLE_PLIST='resources/Info.plist',
		BUNDLE_ICON='resources/CLAM-MusicAnnotator.icns',
	 )
	env.Alias('bundle', mac_bundle)

	#TODO mac_bundle should be dependency of Dmga:	
	mac_packages = env.Dmg('CLAM_Annotator-%s.dmg'%fullVersion, [env.Dir('Annotator.app/')]+installTargets )
	env.Alias('package', mac_packages)

env.Alias('install', installTargets )

env.Default(programs, translations)

