#!/usr/bin/env python
import optparse
import os
import pprint
import re
import subprocess
import sys

CC = os.environ.get('CC', 'cc')

root_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(root_dir, 'deps', 'v8', 'tools'))

# parse our options
parser = optparse.OptionParser()

parser.add_option("--debug",
    action="store_true",
    dest="debug",
    help="Also build debug build")

parser.add_option("--prefix",
    action="store",
    dest="prefix",
    help="Select the install prefix (defaults to /usr/local)")

parser.add_option("--without-npm",
    action="store_true",
    dest="without_npm",
    help="Don\'t install the bundled npm package manager")

parser.add_option("--without-waf",
    action="store_true",
    dest="without_waf",
    help="Don\'t install node-waf")

parser.add_option("--without-ssl",
    action="store_true",
    dest="without_ssl",
    help="Build without SSL")

parser.add_option("--without-snapshot",
    action="store_true",
    dest="without_snapshot",
    help="Build without snapshotting V8 libraries. You might want to set"
         " this for cross-compiling. [Default: False]")

parser.add_option("--shared-v8",
    action="store_true",
    dest="shared_v8",
    help="Link to a shared V8 DLL instead of static linking")

parser.add_option("--shared-v8-includes",
    action="store",
    dest="shared_v8_includes",
    help="Directory containing V8 header files")

parser.add_option("--shared-v8-libpath",
    action="store",
    dest="shared_v8_libpath",
    help="A directory to search for the shared V8 DLL")

parser.add_option("--shared-v8-libname",
    action="store",
    dest="shared_v8_libname",
    help="Alternative lib name to link to (default: 'v8')")

parser.add_option("--openssl-use-sys",
    action="store_true",
    dest="openssl_use_sys",
    help="Use the system OpenSSL instead of one included with Node")

parser.add_option("--openssl-includes",
    action="store",
    dest="openssl_includes",
    help="A directory to search for the OpenSSL includes")

parser.add_option("--openssl-libpath",
    action="store",
    dest="openssl_libpath",
    help="A directory to search for the OpenSSL libraries")

parser.add_option("--no-ssl2",
    action="store_true",
    dest="no_ssl2",
    help="Disable OpenSSL v2")

parser.add_option("--shared-zlib",
    action="store_true",
    dest="shared_zlib",
    help="Link to a shared zlib DLL instead of static linking")

parser.add_option("--shared-zlib-includes",
    action="store",
    dest="shared_zlib_includes",
    help="Directory containing zlib header files")

parser.add_option("--shared-zlib-libpath",
    action="store",
    dest="shared_zlib_libpath",
    help="A directory to search for the shared zlib DLL")

parser.add_option("--shared-zlib-libname",
    action="store",
    dest="shared_zlib_libname",
    help="Alternative lib name to link to (default: 'z')")

parser.add_option("--with-dtrace",
    action="store_true",
    dest="with_dtrace",
    help="Build with DTrace (default is true on supported systems)")

parser.add_option("--without-dtrace",
    action="store_true",
    dest="without_dtrace",
    help="Build without DTrace")

# CHECKME does this still work with recent releases of V8?
parser.add_option("--gdb",
    action="store_true",
    dest="gdb",
    help="add gdb support")

parser.add_option("--dest-cpu",
    action="store",
    dest="dest_cpu",
    help="CPU architecture to build for. Valid values are: arm, ia32, x64")

(options, args) = parser.parse_args()


def b(value):
  """Returns the string 'true' if value is truthy, 'false' otherwise."""
  if value:
    return 'true'
  else:
    return 'false'


def pkg_config(pkg):
  cmd = os.popen('pkg-config --libs %s' % pkg, 'r')
  libs = cmd.readline().strip()
  ret = cmd.close()
  if (ret): return None

  cmd = os.popen('pkg-config --cflags %s' % pkg, 'r')
  cflags = cmd.readline().strip()
  ret = cmd.close()
  if (ret): return None

  return (libs, cflags)


def host_arch_cc():
  """Host architecture check using the CC command."""

  try:
    p = subprocess.Popen(CC.split() + ['-dM', '-E', '-'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
  except OSError:
    print '''Node.js configure error: No acceptable C compiler found!

        Please make sure you have a C compiler installed on your system and/or
        consider adjusting the CC environment variable if you installed
        it in a non-standard prefix.
        '''
    sys.exit()

  p.stdin.write('\n')
  out = p.communicate()[0]

  out = str(out).split('\n')

  k = {}
  for line in out:
    import shlex
    lst = shlex.split(line)
    if len(lst) > 2:
      key = lst[1]
      val = lst[2]
      k[key] = val

  matchup = {
    '__x86_64__'  : 'x64',
    '__i386__'    : 'ia32',
    '__arm__'     : 'arm',
  }

  rtn = 'ia32' # default

  for i in matchup:
    if i in k and k[i] != '0':
      rtn = matchup[i]
      break

  return rtn


def host_arch_win():
  """Host architecture check using environ vars (better way to do this?)"""

  arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')

  matchup = {
    'AMD64'  : 'x64',
    'x86'    : 'ia32',
    'arm'    : 'arm',
  }

  return matchup.get(arch, 'ia32')


def host_arch():
  """Host architecture. One of arm, ia32 or x64."""
  if os.name == 'nt':
    arch = host_arch_win()
  else:
    arch = host_arch_cc()
  return arch


def target_arch():
  return host_arch()

def cc_version():
  try:
    proc = subprocess.Popen([CC, '-v'], stderr=subprocess.PIPE)
  except OSError:
    return None
  lines = proc.communicate()[1].split('\n')
  version_line = None
  for i, line in enumerate(lines):
    if 'version' in line:
      version_line = line
  if not version_line:
    return None
  version = version_line.split("version")[1].strip().split()[0].split(".")
  if not version:
    return None
  return ['LLVM' in version_line] + version

def configure_node(o):
  # TODO add gdb
  o['variables']['node_prefix'] = options.prefix if options.prefix else ''
  o['variables']['node_install_npm'] = b(not options.without_npm)
  o['variables']['node_install_waf'] = b(not options.without_waf)
  o['variables']['host_arch'] = host_arch()
  o['variables']['target_arch'] = options.dest_cpu or target_arch()
  o['default_configuration'] = 'Debug' if options.debug else 'Release'

  # turn off strict aliasing if gcc < 4.6.0 unless it's llvm-gcc
  # see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45883
  # see http://code.google.com/p/v8/issues/detail?id=884
  o['variables']['strict_aliasing'] = b(
    'clang' in CC or cc_version() >= [False, 4, 6, 0])

  # clang has always supported -fvisibility=hidden, right?
  if 'clang' not in CC and cc_version() < [False, 4, 0, 0]:
    o['variables']['visibility'] = ''

  # By default, enable DTrace on SunOS systems. Don't allow it on other
  # systems, since it won't work.  (The MacOS build process is different than
  # SunOS, and we haven't implemented it.)
  if sys.platform.startswith('sunos'):
    o['variables']['node_use_dtrace'] = b(not options.without_dtrace);
    # Strict aliasing causes problems with the V8 snapshots on SunOS
    o['variables']['strict_aliasing'] = b(False);
  elif b(options.with_dtrace) == 'true':
    raise Exception('DTrace is currently only supported on SunOS systems.')
  else:
    o['variables']['node_use_dtrace'] = 'false'


def configure_libz(o):
  o['variables']['node_shared_zlib'] = b(options.shared_zlib)

  # assume shared_zlib if one of these is set?
  if options.shared_zlib_libpath:
    o['libraries'] += ['-L%s' % options.shared_zlib_libpath]
  if options.shared_zlib_libname:
    o['libraries'] += ['-l%s' % options.shared_zlib_libname]
  elif options.shared_zlib:
    o['libraries'] += ['-lz']
  if options.shared_zlib_includes:
    o['include_dirs'] += [options.shared_zlib_includes]


def configure_v8(o):
  o['variables']['v8_use_snapshot'] = b(not options.without_snapshot)
  o['variables']['node_shared_v8'] = b(options.shared_v8)

  # assume shared_v8 if one of these is set?
  if options.shared_v8_libpath:
    o['libraries'] += ['-L%s' % options.shared_v8_libpath]
  if options.shared_v8_libname:
    o['libraries'] += ['-l%s' % options.shared_v8_libname]
  elif options.shared_v8:
    o['libraries'] += ['-lv8']
  if options.shared_v8_includes:
    o['include_dirs'] += [options.shared_v8_includes]
    o['variables']['node_shared_v8_includes'] = options.shared_v8_includes


def configure_openssl(o):
  o['variables']['node_use_openssl'] = b(not options.without_ssl)

  if options.without_ssl:
    return

  if options.no_ssl2:
    o['defines'] += ['OPENSSL_NO_SSL2=1']

  if not options.openssl_use_sys:
    o['variables']['node_use_system_openssl'] = b(False)
  else:
    out = pkg_config('openssl')
    (libs, cflags) = out if out else ('', '')

    if options.openssl_libpath:
      o['libraries'] += ['-L%s' % options.openssl_libpath, '-lssl', '-lcrypto']
    else:
      o['libraries'] += libs.split()

    if options.openssl_includes:
      o['include_dirs'] += [options.openssl_includes]
    else:
      o['cflags'] += cflags.split()

    o['variables']['node_use_system_openssl'] = b(
      libs or cflags or options.openssl_libpath or options.openssl_includes)


output = {
  'variables': {},
  'include_dirs': [],
  'libraries': [],
  'defines': [],
  'cflags': [],
}

configure_node(output)
configure_libz(output)
configure_v8(output)
configure_openssl(output)

# variables should be a root level element,
# move everything else to target_defaults
variables = output['variables']
del output['variables']
output = {
  'variables': variables,
  'target_defaults': output
}
pprint.pprint(output, indent=2)

def write(filename, data):
  filename = os.path.join(root_dir, filename)
  print "creating ", filename
  f = open(filename, 'w+')
  f.write(data)

write('config.gypi', "# Do not edit. Generated by the configure script.\n" +
  pprint.pformat(output, indent=2) + "\n")

write('config.mk', "# Do not edit. Generated by the configure script.\n" +
  ("BUILDTYPE=%s\n" % ('Debug' if options.debug else 'Release')))

if os.name == 'nt':
  subprocess.call(['python', 'tools/gyp_node', '-f', 'msvs',
                                               '-G', 'msvs_version=2010'])
else:
  subprocess.call(['tools/gyp_node', '-f', 'make'])