# This scripts retrieves the proper options to be used to link against
# the libpython, in a machine-independant way. It invokes the official
# script python-config (which thankfully deals with all the details).

import sys
newerpython = (sys.version_info[0] == 3 and sys.version_info[1] > 7)

if newerpython:
  # From now on avoid duplicating python-config, which evolves on its own.
  # Invoke 'python-config --ldflags --embed'. The embed option (under
  # Python 3) adds the libpython itself, whose name is highly
  # unpredictible under the variety of machines and configurations we
  # support
  import subprocess
  import os
  output = subprocess.check_output([os.environ['GAG_PYTHON_EXE']+'-config', '--ldflags','--embed'])
  output = output.decode('utf-8')
  #print(output)

  args = output.split()

  output = ''
  for arg in args:
    # Discard /usr/lib* path which causes troubles on the link command
    # line, as it basically overrides all other custom paths coming after
    # it. No need to put these paths on command line, they are found
    # implicitly by the linker.
    if arg not in ['-L/usr/lib','-L/usr/lib32','-L/usr/lib64']:
      output += arg+' '

  print(output)

else:
  # DUPLICATE of "python-config --ldflags", fixed for the library location
  # This proved to work gracefully up to Python 3.5 (exact limit unclear)

  # This utility is known to work with:
  #  python2.6 (system install)   under SL6.4
  #  python2.7 (custom install)   under SL6.4
  #  python3.4 (custom install)   under SL6.4
  #  python3.7 (custom install)   under Debian12
  #  python2.7 (system install)   under Fedora20
  #  python2.7 (Apple install)    under MacOSX
  #  python2.7 (MacPorts install) under MacOSX
  #  python3.4 (MacPorts install) under MacOSX

  import sys
  import sysconfig

  pyver = sysconfig.get_config_var('VERSION')
  getvar = sysconfig.get_config_var

  libs = getvar('LIBS').split() + getvar('SYSLIBS').split()
  if (hasattr(sys,'abiflags')):
    libs.append('-lpython' + pyver + sys.abiflags)
  else:
    libs.append('-lpython' + pyver)

  # Add the library path, except /usr/lib* which causes troubles
  # on the link command line, as it basically overrides all other
  # custom paths coming after it. No need to put these paths on
  # command line, they are found implicitly by the linker.
  ldpath = getvar('LIBDIR')
  if ldpath not in ['/usr/lib','/usr/lib32','/usr/lib64']:
    libs.insert(0, '-L' + getvar('LIBDIR'))

  # Framework (specific for Mac)
  if not getvar('PYTHONFRAMEWORK'):
      libs.extend(getvar('LINKFORSHARED').split())

  print(' '.join(libs))
