#encoding: latin-1

# libzzub, Buz, Aldrin
# Modular Sequencer
# Copyright (C) 2006 The Aldrin Development Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

VERSION = "0.7"

import os, glob, sys, time

posix = os.name == 'posix'
win32 = os.name == 'nt'
mac = os.name == 'mac'

######################################
#
# init environment and define options
#
######################################

def tools_converter(value):
	return value.split(',')
	
def bool_converter(value):
	if value == 'True':
		return True
	elif value == 'False':
		return False
	return bool(value)

opts = Options( 'options.conf', ARGUMENTS )
opts.Add("PREFIX", 'Set the install "prefix" ( /path/to/PREFIX )', "/usr/local")
opts.Add("LIBDIR", 'Set the install "libdir", will be concatenated to PREFIX', "/lib") 
opts.Add("DESTDIR", 'Set the root directory to install into ( /path/to/DESTDIR )', "")
opts.Add("LADSPA", 'Support LADSPA plugins', False, None, bool_converter)
opts.Add("DSSI", 'Support DSSI plugins', False, None, bool_converter)
opts.Add("ASIO", 'Support ASIO', win32 == True, None, bool_converter)
opts.Add("USE_SIGNATURE", 'Use signature to bond plugins and host (strongly recommended)', True, None, bool_converter)
opts.Add("OSC", "Support OpenSoundControl (requires liblo)", False, None, bool_converter)
opts.Add("SNDFILE", 'Support loading of waves via libsndfile', True, None, bool_converter)
opts.Add("ZXM", 'Support loading/saving of ZXM files', True, None, bool_converter)
if win32:
	opts.Add("BUZE", 'Compile Buze on Win32', False, None, bool_converter)
opts.Add("BUZZ2ZZUB", "Compile buzz2zzub", win32 == True, None, bool_converter)
opts.Add("REVISION", 'Revision number (will be set automatically)', '??')
opts.Add("SIGNATURE", 'Host signature (will be set automatically)', '')
opts.Add("TOOLS", 'Compiler suite to use', 'default', None, tools_converter)

env = Environment(ENV = os.environ, options=opts)
# get revision

svnversionpath = env.WhereIs('svnversion', os.environ['PATH'])
revision = env['REVISION']

if os.path.isdir('.svn') and (svnversionpath != None):
	rev = os.popen('svnversion .').readline().strip()

	if rev != "" and rev != "exported":
		revision = rev
	else:
		print "WARNING: svnversion returned empty string. build will not carry version information."
else:
	pass

env['REVISION'] = revision

env.SConsignFile()

######################################
#
# settings
#
######################################

USE_LADSPA = env['LADSPA']
USE_SNDFILE = env['SNDFILE']
USE_ASIO = env['ASIO']
USE_ZXM = env['ZXM']

######################################
#
# build settings
#
######################################


env['ROOTPATH'] = os.getcwd()

env.Append(CCFLAGS=['-D__SCONS__'])
env.Append(LIBPATH=['${ROOTPATH}/lib'])

if posix:
	env.Append(CCFLAGS=[
		'-DPOSIX',
	])
	env.Append(LINKFLAGS=[
		'--rpath${PREFIX}${LIBDIR}',
	])
elif win32:
	env.Append(CCFLAGS=[
		'-D_WIN32',
		'-DWIN32',
		'-DSTRICT',
		'-D_WINDOWS',
		'-D_WIN32_WINNT=0x0500',
#		'-DNDEBUG',		
		'-D_DEBUG',
		'-DDEBUG',
	])
	env.Append(LINKFLAGS=[
		'-DEBUG',
	])
	env.Append(LIBS=[
		'kernel32',
		'user32',
	])

gcc = env['CC'] == 'gcc'
cl = env['CC'] == 'cl'

if gcc:
	env['CXXFLAGS'] += ['--no-rtti']
	
	env.Append(CCFLAGS=[
		'-g',
	])

if cl:
	env.Append(CCFLAGS=[
		'-nologo',
		'-MTd',
		'-EHsc',
		'-W3',
		'-Zi'   # Debug info
	])

######################################
#
# signature
#
######################################

import stat
import socket

env['SIGNATURE'] = 'libzzub %s r%s %s-%s %s' % (VERSION,env['REVISION'],env['CC'],sys.platform,socket.gethostname())

######################################
# save config
######################################

opts.Save('options.conf', env)
Help( opts.GenerateHelpText( env ) )

######################################
#
# install paths
#
######################################

try:
	umask = os.umask(022)
	#print 'setting umask to 022 (was 0%o)' % umask
except OSError:     # ignore on systems that don't support umask
	pass

import SCons
from SCons.Script.SConscript import SConsEnvironment
SConsEnvironment.Chmod = SCons.Action.ActionFactory(os.chmod,
		lambda dest, mode: 'Chmod: "%s" with 0%o' % (dest, mode))

def InstallPerm(env, dir, source, perm):
	obj = env.Install(dir, source)
	for i in obj:
		env.AddPostAction(i, env.Chmod(str(i), perm))
	return dir

SConsEnvironment.InstallPerm = InstallPerm

rootpath = "${DESTDIR}${PREFIX}"
binpath = "${DESTDIR}${PREFIX}/bin"
libpath = "${DESTDIR}${PREFIX}${LIBDIR}"
includepath = "${DESTDIR}${PREFIX}/include"
pluginpath = "${DESTDIR}${PREFIX}${LIBDIR}/zzub"

def install(target, source, perm=None):
	if not perm:
		env.Install(dir=target, source=source)
	else:
		env.InstallPerm(dir=target, source=source, perm=perm)

env.Alias(target='install', source=rootpath)

def install_root(source):
	install(rootpath, source)
def install_lib(source):
	install(libpath, source)
def install_bin(source):
	install(binpath, source)
def install_plugin(source):
	install(pluginpath, source)
def install_plugin_help(name, files):
	install("${DESTDIR}${PREFIX}/share/doc/zzub/plugins/"+name, files, 0644)

env['DSPLIB_SRC_PATH'] = '${ROOTPATH}/src/dsplib'
env['ASIOSDK_SRC_PATH'] = '${ROOTPATH}/src/ASIOSDK2'
env['PORTAUDIO_SRC_PATH'] = '${ROOTPATH}/src/portaudio'
env['PORTMIDI_SRC_PATH'] = '${ROOTPATH}/src/portmidi'
env['LIBZZUB_SRC_PATH'] = '${ROOTPATH}/src/libzzub'
env['MINIZIP_SRC_PATH'] = '${ROOTPATH}/src/minizip'
env['PLUGINS_SRC_PATH'] = '${ROOTPATH}/src/plugins'
env['BMXPLAY_SRC_PATH'] = '${ROOTPATH}/src/bmxplay'

env['LIB_BUILD_PATH'] = '${ROOTPATH}/lib'
env['BIN_BUILD_PATH'] = '${ROOTPATH}/bin'

######################################
#
# configure
#
######################################

#~ all_args = sys.argv[1:]
#~ parser = OptionParser()
#~ o, targets = parser.parse_args(all_args)

#~ if not env.GetOption('clean') and 'configure' in targets:
	#~ config = env.Configure()
	#~ if not config.CheckHeader('portmidi.h'):
		#~ print "PortMidi seems to be missing. You need PortMidi to compile."
		#~ Exit(1)
	#~ config.Finish()

#~ env.Alias(target="configure")

env.Append(CPPPATH=['${ROOTPATH}/include'])
if win32:
	env.Append(CPPPATH=['${ROOTPATH}/include/win32'])

#######################################
#
# SConscripts
#
#######################################

vs_projects=[]

Export(
	'install_lib',
	'install_plugin',
	'install_bin',
	'install',
	'install_root',
	'install_plugin_help',
	
	'gcc','cl',
	
	'posix','win32',
	
	'env',
    
	'vs_projects',
)

# generate buildconfig if tool is available
if os.path.isfile('tools/make_signature.py'):
	env.Command('include/zzub/signature.h',
		'options.conf', 
		'python tools/make_signature.py $TARGET $SOURCE')

env.SConscript('${BMXPLAY_SRC_PATH}/SConscript')

env.SConscript('${LIBZZUB_SRC_PATH}/SConscript')
env.SConscript('${PLUGINS_SRC_PATH}/SConscript')
env.SConscript('${ROOTPATH}/Aldrin.SConscript')
if win32 and env["BUZE"]:
	env.SConscript('${ROOTPATH}/src/audioimportlib/SConscript')
	env.SConscript('${ROOTPATH}/src/buze/SConscript')

#######################################
#
# Rest
#
#######################################

if hasattr(env, 'MSVSSolution'):
	env.MSVSSolution(
		target='zzub' + env['MSVSSOLUTIONSUFFIX'],
		projects=vs_projects,
		variant=[]
	)

# install zzub plugin and type headers
install(includepath+'/zzub', 'include/zzub/plugin.h')
install(includepath+'/zzub', 'include/zzub/types.h')
install(includepath+'/zzub', 'include/zzub/signature.h')

