#!/usr/bin/env python
"""
From <https://github.com/joyent/node/blob/master/configure-gyp>
"""

import optparse
import os
import json
import sys
import glob
import shutil

root_dir = os.path.dirname(__file__)

sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib'))
import gyp

# parse our options
parser = optparse.OptionParser()

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

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

parser.add_option("--arch",
    action="store",
    dest="arch",
    help="Select the default architecture (ia32,x64,arm)")

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

parser.add_option("--without-fat",
    action="store_true",
    dest="skinny",
    help="Compile in Skinny mode, removing less commonly used features, but reducing footprint.")

(options, args) = parser.parse_args()


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 uname(switch):
  f = os.popen('uname %s' % switch)
  s = f.read().strip()
  f.close()
  return s


def host_arch():
  """Host architecture. One of arm, ia32 or x64."""

  if sys.platform == "win32":
      return 'ia32'

  if sys.platform == "darwin":
      return 'ia32'

  arch = uname('-p')

  if arch == 'unknown':
    arch = uname('-m')

  return {
    'arm': 'arm',
    'x86': 'ia32',
    'i386': 'ia32',
    'i486': 'ia32',
    'i586': 'ia32',
    'i686': 'ia32',
    'x86_64': 'x64',
    'amd64': 'x64',
  }.get(arch, arch)


def target_arch():
  # TODO act on options.dest_cpu
  return host_arch()


def configure_lev(o):
  # TODO add gdb and dest_cpu
  o['variables']['lev_debug'] = 'true' if options.debug else 'false'
  o['variables']['lev_prefix'] = options.prefix if options.prefix else ''
  o['variables']['host_arch'] = host_arch()
  o['variables']['target_arch'] = options.arch if options.arch else target_arch()
  o['variables']['without_ssl'] = 'true' if options.without_ssl else 'false'
  o['variables']['lev_skinny'] = 'true' if options.skinny else 'false'

  t_os = gyp.common.GetFlavor({})
  t_arch = o['variables']['target_arch']
  possible_dirs = ['deps/openssl/openssl-configs/%s-%s' % (t_os, t_arch),
                   'deps/openssl/openssl-configs/%s' % t_arch,
                   'deps/openssl/openssl-configs/%s' % t_os]
  for d in possible_dirs:
      if os.path.exists(d):
          return

  print ""
  print "Error: Unsupported target architecture: %s-%s" % (t_os, t_arch)
  print ""
  print "Could not find configuration for openssl in one of: \n  %s" % ('\n  '.join(possible_dirs))
  sys.exit(1)

print "configure options:", options

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

configure_lev(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
}

fn = os.path.join(root_dir, 'options.gypi')
print "creating ", fn

f = open(fn, 'w+')
f.write("# Do not edit. Generated by the configure script.\n")
json.dump(output, f, indent=2, skipkeys=True)
f.write("\n")
f.close()

print "Generating build system with GYP..."

def render_openssl_symlinks(src, dest):
    src = os.path.abspath(src)
    dest = os.path.abspath(dest)
    for x in glob.glob(os.path.join(src, '*.h')):
        with open(x) as f:
            d = f.read().strip()
            srcf = os.path.abspath(os.path.join(src, d))
            destf = os.path.join(dest, os.path.basename(srcf))
            # use copy2, so we preserve mtimes, reducing rebuilds
            shutil.copy2(srcf, destf)

if sys.platform == "win32":
    render_openssl_symlinks('deps/openssl/openssl/include/openssl',
        'deps/openssl/openssl-configs/realized/openssl')
    code = os.system("python tools\gyp_lev -f msvs -G msvs_version=2010")
else:
    code = os.system("tools/gyp_lev")

if code == 0:
    print ""
    print "Done!"
    print ""
    if sys.platform == "win32":
        print "Now run `python build.py` to build!"
    else:
        print "Now run `make -C out` to build!"
    print ""
else:
    print ""
    print "Error occured. Please investigate details above."
    print ""

