#!/usr/bin/python
#INTEL CONFIDENTIAL
#Copyright (c) 2009-2012  Intel Corporation All Rights Reserved. 
#The source code contained or described herein and all documents related to the
#source code ("Material") are owned by Intel Corporation or its suppliers or
#licensors. Title to the Material remains with Intel Corporation or its
#suppliers and licensors. The Material contains trade secrets and proprietary
#and confidential information of Intel or its suppliers and licensors.
#The Material is protected by worldwide copyright and trade secret laws and
#treaty provisions.No part of the Material may be used, copied, reproduced,
#modified, published,uploaded, posted, transmitted, distributed, or disclosed in
#any way without Intel.s prior express written permission.
#
#No license under any patent, copyright, trade secret or other intellectual
#property right is granted to or conferred upon you by disclosure or delivery of
#the Materials, either expressly, by implication, inducement, estoppel or
#otherwise. Any license under such intellectual property rights must be express
#and approved by Intel in writing.


# shmemcc is a wrapper script for the compilation of SHMEM C programs.
# The main purpose of the script is to call the C compiler with additional
# options to specify the SHMEM include directory, the SHMEM library
# directory, and to link in the SHMEM library appropriately. shmemcc
# automatically determines the correct directories by finding them
# relative to its own location. The standard directory layout of the 
# Intel SHMEM software is assumed.
# 
# The default C compiler is gcc, and this can be overriden by specifying
# a compiler with the $SHMEM_CC environment variable.
# 
# If -show is in the options given to shmemcc, it will show the command
# line that would be used to invoke the C compiler but the C compiler
# will not be invoked. All other arguments to shmemcc are passed through
# to the C compiler without modification.
# 
# A user can use the C compiler directly without using shmemcc. In
# that case the user must arrange for the following:
# 
# * Compilations need the option:
# 
#     -I $SHMEM_DIR/include
# 
# * Linkages need the options:
# 
#     -Wl,--export-dynamic,--allow-shlib-undefined
#     -L $SHMEM_DIR/lib64/default
#     -lintel_shmem
# 
# where $SHMEM_DIR denotes the top-level directory of the SHMEM
# installation, typically /usr/shmem/intel. The -L option uses
# the default version of the SHMEM libraries. The default is actually a
# symbolic link to libraries built for a specific MPI implementation.
# However, this choice does not constrain the SHMEM binary, and it 
# can be run over any of the supported MPIs.
#
# Note that if the SHMEM RPM is installed with --prefix=usr then the
# -I option is not necessary since the header files are in system 
# default locations. All of the linkage options are still required.
#
# The rationale for the "-Wl,--export-dynamic,--allow-shlib-undefined" option
# is to prevent other library and symbol dependencies in the SHMEM library
# from percolating up into the application binaries. These symbols include
# those from the underlying MPI implementation, There is no need to couple 
# the application binary to a particular MPI, and these symbols will be 
# correctly resolved at run-time. The advantage of this approach is that SHMEM
# application binaries will be portable across different implementations of
# the Intel SHMEM library, including portability over different underlying
# MPIs.
 
import os
import re
import stat
import string
import subprocess
import sys

my_cmd_name = os.path.basename(sys.argv[0])

shmemcc_verbose = 0
if 'SHMEMCC_VERBOSE' in os.environ and os.environ['SHMEMCC_VERBOSE'] != '' :
  shmemcc_verbose = 1

def is_executable (pathname) :
  if os.path.isfile(pathname) :
    filestat = os.stat(pathname)
    st_mode = filestat[stat.ST_MODE]
    s_imode = stat.S_IMODE(st_mode)
    if (s_imode & 0111) != 0 :
      return True
  return False

def find_executable (name) :
  if name == '' or name[0] == '/' :
    return name
  else :
    path = os.environ['PATH']
    for pathdir in string.split(path, ':') :
      pathname = '%s/%s' % (pathdir, name)
      if is_executable(pathname) :
        return pathname
  return name

def find_shmem_dir () :
  my_name = sys.argv[0]
  my_dir = os.path.dirname(sys.argv[0])
  if my_dir == '' :
    my_dir = os.path.dirname(find_executable(sys.argv[0]))
  return os.path.abspath('%s/..' % my_dir)

shmem_dir = find_shmem_dir()
shmem_library_name = 'intel_shmem'
include_dir = '%s/%s' % (shmem_dir, 'include')
lib_dir = '%s/%s' % (shmem_dir, 'lib64/default')

show = 0
run = 1
compiling = 1
linking = 1

compiler = 'gcc'
if 'SHMEM_CC' in os.environ and os.environ['SHMEM_CC'] != '' :
  compiler = os.environ['SHMEM_CC']
compiler = find_executable(compiler)

compile_args = []
linkage_args = ['-Wl,--export-dynamic,--allow-shlib-undefined']

if shmem_dir != '/usr' :
  compile_args.extend(['-I', include_dir])

linkage_args.extend(['-L', lib_dir])
linkage_args.append('-l%s' % shmem_library_name)

full_library_filename = '%s/lib%s.so' % (lib_dir, shmem_library_name)

outargv = [compiler]

if len(sys.argv) == 1 :
  compiling = 0
  linking = 0
else :
  for arg in sys.argv[1:] :
    include = 1
    if arg == '-show' :
      show = 1
      run = 0
      include = 0
    elif arg in ['-c', '-S', '-E'] :
      linking = 0
    if include :
      outargv.append(arg)

if compiling :
  outargv.extend(compile_args)

if linking :
  outargv.extend(linkage_args)

if show or shmemcc_verbose :
  for arg in outargv :
    print arg,
  print

result = 0

if run :
  if not is_executable(compiler) :
    print '%s fatal error: cannot execute %s' % \
      (os.path.basename(sys.argv[0]), compiler)
    sys.exit(-1)

  # This is the straightforward way to run the compiler:
  # os.execv(compiler, outargv)

  # Instead, we run the compiler as a sub-process, and post-process its 
  # stderr to eliminate annoying linker warnings
  command = outargv  
  try :
    child = subprocess.Popen(command, env=os.environ, stderr=subprocess.PIPE)
  except :
    print >>sys.stderr, '%s fatal error: cannot run command "%s"' % \
          (my_cmd_name, str(command))
    result = -1
  if result == 0 :
    try :
      (child_stdout, child_stderr) = child.communicate()
      # filter out this annoying linker warning
      message = '/usr/bin/ld: warning: .*, needed by %s, not found' % \
                full_library_filename
      lines = string.split(child_stderr, '\n')
      for lineno in range(0, len(lines) - 1) :
        line = lines[lineno]
        # skip last line if empty
        if len(line) == 0 and lineno == len(lines) - 1 :
          continue
        if not re.match(message, line) :
          print >>sys.stderr, '%s' % line
      result = child.returncode
      if shmemcc_verbose :
        print '%s: completed with result %d' % (my_cmd_name, result)
    except :
      print >>sys.stderr, \
            '%s fatal error: command failed for some other reason' % \
            my_cmd_name
      result = -1

sys.exit(result)
