import os
import sys
import roslib
import sipconfig
import subprocess
from PyQt4 import pyqtconfig

if len(sys.argv) != 4:
  print 'usage: %s build-dir sip-file output_dir' % (sys.argv[0])
  exit(1)

# The base folder of the c++ library, the SIP build folder, the SIP file and the output directory.
build_dir, sip_file, output_dir = sys.argv[1:]

# The name of the SIP build file generated by SIP and used by the build system.
build_file = 'pyqtscripting.sbf'

# Get the PyQt configuration information.
config = pyqtconfig.Configuration()

# Get the extra SIP flags needed by the imported qt module.  Note that
# this normally only includes those flags (-x and -t) that relate to SIP's
# versioning system.
qt_sip_flags = config.pyqt_sip_flags

try:
  os.makedirs(build_dir)
except OSError:
  pass

# Run SIP to generate the code.  Note that we tell SIP where to find the qt
# module's specification files using the -I flag.
os.system(' '.join([
  config.sip_bin,
  '-c', build_dir,
  '-b', os.path.join(build_dir, build_file),
  '-I', config.pyqt_sip_dir,
  '-w',
  qt_sip_flags,
  sip_file
]))

# Create the Makefile.  The QtModuleMakefile class provided by the
# pyqtconfig module takes care of all the extra preprocessor, compiler and
# linker flags needed by the Qt library.
makefile = pyqtconfig.QtGuiModuleMakefile(
  dir=build_dir,
  configuration=config,
  build_file=build_file
)

# for ros diamondback's tinyxml this specific flag is needed
makefile.CXXFLAGS.append('-DTIXML_USE_STL')

# add ros packages dependencies
cmd = ['rospack', 'cflags-only-I', '--deps-only', 'rviz']
po = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = po.communicate()
outlist = [x for x in out.strip().split() if x]
makefile.extra_include_dirs.extend(outlist)

cmd = ['rospack', 'libs-only-L', '--deps-only', 'rviz']
po = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = po.communicate()
outlist = [x for x in out.strip().split() if x]
makefile.extra_lib_dirs.extend(outlist)

cmd = ['rospack', 'libs-only-l', '--deps-only', 'rviz']
po = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = po.communicate()
outlist = [x for x in out.strip().split() if x]
makefile.extra_libs.extend(outlist)

cmd = ['rospack', 'libs-only-other', '--deps-only', 'rviz']
po = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = po.communicate()
outlist = [x for x in out.strip().split() if x]
makefile.LFLAGS.extend(outlist)

# special case for our own code
rviz_package_path = roslib.packages.get_pkg_dir('rviz')
makefile.extra_include_dirs.append(os.path.join(rviz_package_path, 'src'))

# redirect location of generated library
makefile._target = os.path.join(output_dir, makefile._target)

# Generate the Makefile itself
makefile.generate()
