# vim: set sts=2 ts=8 sw=2 tw=99 et ft=python:
import os

def ResolveEnvPath(env, folder):
  if env in os.environ:
    path = os.environ[env]
    if os.path.isdir(path):
      return path
    return None

  head = os.getcwd()
  oldhead = None
  while head != None and head != oldhead:
    path = os.path.join(head, folder)
    if os.path.isdir(path):
      return path
    oldhead = head
    head, tail = os.path.split(head)

  return None

def Normalize(path):
  return os.path.abspath(os.path.normpath(path))

class SteamWorksConfig(object):
  def __init__(self):
    self.binaries = []
    self.mms_root = None
    self.sm_root = None
    self.steamworks_root = None
    self.extensions = []

    # Note: only one architecture supported per build right now.
    if builder.options.target:
        builder.cxx = builder.DetectCxx(target_arch = builder.options.target)
    else:
        builder.cxx = builder.DetectCxx(target_arch = 'x86')

  @property
  def tag(self):
    if builder.options.debug == '1':
      return 'Debug'
    return 'Release'

  def detectDeps(self):
    #METAMOD:SOURCE
    if builder.options.mms_path:
      self.mms_root = builder.options.mms_path
    else:
      self.mms_root = ResolveEnvPath('MMSOURCE110', 'mmsource-1.10')
      if not self.mms_root:
        self.mms_root = ResolveEnvPath('MMSOURCE10', 'metamod-1.10')
      if not self.mms_root:
        self.mms_root = ResolveEnvPath('MMSOURCE_DEV', 'mmsource-central')

    if not self.mms_root or not os.path.isdir(self.mms_root):
      raise Exception('Could not find a source copy of Metamod:Source')
    self.mms_root = Normalize(self.mms_root)
	
	#SOURCEMOD
    if builder.options.sm_path:
      self.sm_root = builder.options.sm_path
    else:
      self.sm_root = ResolveEnvPath('SOURCEMOD16', 'sourcemod-1.6')
      if not self.sm_root:
        self.sm_root = ResolveEnvPath('SOURCEMOD', 'sourcemod-1.6')
      if not self.sm_root:
        self.sm_root = ResolveEnvPath('SMCENTRAL', 'sourcemod-central')

    if not self.sm_root or not os.path.isdir(self.sm_root):
      raise Exception('Could not find a source copy of Sourcemod')
    self.sm_root = Normalize(self.sm_root)
	
	#STEAMWORKS
    if builder.options.steamworks_path:
      self.steamworks_root = builder.options.steamworks_path
    else:
      self.steamworks_root = ResolveEnvPath('STEAMWORKS', 'steamworks-sdk')
      if not self.steamworks_root:
        self.steamworks_root = ResolveEnvPath('STEAMWORKS', 'steamworks')
      if not self.steamworks_root:
        self.steamworks_root = ResolveEnvPath('STEAMWORKS', 'opensteamworks')

    if not self.steamworks_root or not os.path.isdir(self.steamworks_root):
      raise Exception('Could not find a source copy of SteamWorks')
    self.steamworks_root = Normalize(self.steamworks_root)

  def configure(self):
    builder.AddConfigureFile('pushbuild.txt')

    # Only one compiler to configure.
    self.configure_cxx(builder.cxx)

  def configure_cxx(self, cxx):
    if cxx.like('gcc'):
      cxx.defines += [
        'stricmp=strcasecmp',
        '_stricmp=strcasecmp',
        '_snprintf=snprintf',
        '_vsnprintf=vsnprintf',
        'HAVE_STDINT_H',
        'GNUC',
      ]
      cxx.cflags += [
        '-pipe',
        '-fno-strict-aliasing',
        '-Wall',
        '-Werror',
        '-Wno-unused',
        '-Wno-switch',
        '-Wno-format',
        '-Wno-format-security',
        '-Wno-array-bounds',
      ]
      cxx.cxxflags += [
          '-std=c++17',
      ]

      if cxx.target.arch == 'x86':
        cxx.cflags += ['-msse', '-m32']
        cxx.linkflags += ['-m32']
        if cxx.family == 'gcc':
          cxx.cflags += ['-mfpmath=sse']
      elif cxx.target.arch == 'x86_64':
        cxx.cflags += ['-m64']
        cxx.linkflags += ['-m64']

      have_gcc = cxx.family == 'gcc'
      have_clang = cxx.family == 'clang'
      if have_clang or (have_gcc and cxx.version >= '4'):
        cxx.cflags += ['-fvisibility=hidden']
        cxx.cxxflags += ['-fvisibility-inlines-hidden']
        if have_clang or (have_gcc and cxx.version >= '4.6'):
          cxx.cflags += ['-Wno-narrowing']
        if (have_gcc and cxx.version >= '4.7') or (have_clang and cxx.version >= '3'):
          cxx.cxxflags += ['-Wno-delete-non-virtual-dtor']
        if have_gcc and cxx.version >= '4.8':
          cxx.cflags += ['-Wno-unused-result']
      if have_clang:
        cxx.cxxflags += ['-Wno-implicit-exception-spec-mismatch']
        if (cxx.target.platform == 'mac' and cxx.version >= '5.1') or cxx.version >= '3.4':
          cxx.cxxflags += ['-Wno-deprecated-register']
        else:
          cxx.cxxflags += ['-Wno-deprecated']
        cxx.cflags += ['-Wno-sometimes-uninitialized']

      cxx.cxxflags += [
        '-fno-exceptions',
        '-fno-threadsafe-statics',
        '-Wno-non-virtual-dtor',
        '-Wno-overloaded-virtual',
      ]
    elif cxx.like('msvc'):
      if builder.options.debug == '1':
        cxx.cflags += ['/MTd']
        cxx.linkflags += ['/NODEFAULTLIB:libcmt']
      else:
        cxx.cflags += ['/MT']
      cxx.defines += [
        '_CRT_SECURE_NO_DEPRECATE',
        '_CRT_SECURE_NO_WARNINGS',
        '_CRT_NONSTDC_NO_DEPRECATE',
        '_ITERATOR_DEBUG_LEVEL=0',
      ]
      cxx.cflags += [
        '/W3',
      ]
      cxx.cxxflags += [
        '/EHsc',
        '/GR-',
        '/TP',
        '/std:c++17',
      ]
      cxx.linkflags += [
        '/MACHINE:X64' if cxx.target.arch == 'x86_64' else '/MACHINE:X86',
        '/SUBSYSTEM:WINDOWS',
        'kernel32.lib',
        'user32.lib',
        'gdi32.lib',
        'winspool.lib',
        'comdlg32.lib',
        'advapi32.lib',
        'shell32.lib',
        'ole32.lib',
        'oleaut32.lib',
        'uuid.lib',
        'odbc32.lib',
        'odbccp32.lib',
      ] 

    # Optimization
    if builder.options.opt == '1':
      cxx.defines += ['NDEBUG']
      if cxx.like('gcc'):
        cxx.cflags += ['-O3']
      elif cxx.like('msvc'):
        cxx.cflags += ['/Ox']
        cxx.linkflags += ['/OPT:ICF', '/OPT:REF']

    # Debugging
    if builder.options.debug == '1':
      cxx.defines += ['DEBUG', '_DEBUG']
      if cxx.like('msvc'):
        cxx.cflags += ['/Od', '/RTC1']
        if cxx.version >= 1600:
          cxx.cflags += ['/d2Zi+']

    # This needs to be after our optimization flags which could otherwise disable it.
    if cxx.like('msvc'):
      # Don't omit the frame pointer.
      cxx.cflags += ['/Oy-']

    # Platform-specifics
    if cxx.target.platform == 'linux':
      cxx.defines += ['_LINUX', 'POSIX']
      if cxx.family == 'gcc':
        cxx.linkflags += ['-static-libgcc']
      elif cxx.family == 'clang':
        cxx.linkflags += ['-lgcc_eh']
      cxx.linkflags += ['-static-libstdc++']
    elif cxx.target.platform == 'windows':
      cxx.defines += ['WIN32', '_WINDOWS']
	  
  def ConfigureForExtension(self, context, compiler):
    compiler.cxxincludes += [
      os.path.join(context.currentSourcePath),
      os.path.join(context.currentSourcePath, 'sdk'),
      os.path.join(self.sm_root, 'public'),
      os.path.join(self.sm_root, 'public', 'extensions'),
      os.path.join(self.sm_root, 'sourcepawn', 'include'),
      os.path.join(self.sm_root, 'public', 'amtl', 'amtl'),
      os.path.join(self.sm_root, 'public', 'amtl'),
    ]
    return compiler
	
  def ConfigureForHL2(self, binary):
    compiler = binary.compiler

    mms_path = os.path.join(self.mms_root, 'core')

    compiler.cxxincludes += [
      os.path.join(mms_path),
      os.path.join(mms_path, 'sourcehook'),
    ]

    return binary

  def HL2Project(self, context, name):
    project = context.LibraryProject(name)
    self.ConfigureForExtension(context, context.cxx)
    return project

  def HL2Config(self, project, cxx, name):
    binary = project.Configure(cxx, name, '{0}'.format(self.tag))
    return self.ConfigureForHL2(binary)

SteamWorks = SteamWorksConfig()
SteamWorks.detectDeps()
SteamWorks.configure()

BuildScripts = ['Extension/AMBuilder']

builder.Build(BuildScripts, { 'SteamWorks': SteamWorks })
builder.Build('buildbot/PackageScript', { 'SteamWorks': SteamWorks })
