# -*- python -*-

# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os

# This block will most likely need updating whenever libchrome gets updated.
# The order of the libs below doesn't matter (as scons will take care of
# building things in the required order).  The split between them is purely
# to reduce over linking of 3rd party libraries.  i.e. 'core' should require
# only the C library (and glib), and all other 3rd party libraries should
# get a unique 'xxx' name.
base_name = 'base'
base_libs = [
  {
    'name' : 'core',
    'sources' : """
                at_exit.cc
                atomicops_internals_x86_gcc.cc
                base_switches.cc
                callback_internal.cc
                command_line.cc
                debug/alias.cc
                debug/debugger.cc
                debug/debugger_posix.cc
                debug/stack_trace.cc
                debug/stack_trace_posix.cc
                environment.cc
                file_descriptor_shuffle.cc
                file_path.cc
                json/json_reader.cc
                json/json_writer.cc
                json/string_escape.cc
                lazy_instance.cc
                location.cc
                logging.cc
                memory/ref_counted.cc
                memory/ref_counted_memory.cc
                memory/singleton.cc
                memory/weak_ptr.cc
                message_pump.cc
                message_pump_default.cc
                metrics/histogram.cc
                pickle.cc
                platform_file.cc
                platform_file_posix.cc
                profiler/alternate_timer.cc
                profiler/tracked_time.cc
                safe_strerror_posix.cc
                string16.cc
                string_number_conversions.cc
                string_piece.cc
                stringprintf.cc
                string_split.cc
                string_util.cc
                synchronization/condition_variable_posix.cc
                synchronization/lock.cc
                synchronization/lock_impl_posix.cc
                synchronization/waitable_event_posix.cc
                sys_info_posix.cc
                sys_string_conversions_posix.cc
                third_party/dmg_fp/dtoa.cc
                third_party/dmg_fp/g_fmt.cc
                third_party/dynamic_annotations/dynamic_annotations.c
                third_party/icu/icu_utf.cc
                third_party/nspr/prtime.cc
                threading/non_thread_safe_impl.cc
                threading/platform_thread_posix.cc
                threading/thread_checker_impl.cc
                threading/thread_collision_warner.cc
                threading/thread_local_posix.cc
                threading/thread_local_storage_posix.cc
                threading/thread_restrictions.cc
                time.cc
                time_posix.cc
                tracked_objects.cc
                utf_string_conversions.cc
                utf_string_conversion_utils.cc
                values.cc
                vlog.cc
                """,
    'libs' : 'pthread rt',
    'pc_libs' : '',
  },
  {
    'name' : 'glib',
    'sources' : """
                debug/trace_event.cc
                debug/trace_event_impl.cc
                file_util.cc
                file_util_posix.cc
                message_pump_glib.cc
                process_posix.cc
                process_util.cc
                process_util_linux.cc
                process_util_posix.cc
                rand_util.cc
                rand_util_posix.cc
                scoped_temp_dir.cc
                """,
    'libs' : '',
    'pc_libs' : 'glib-2.0',
  },
  {
    'name' : 'event',
    'sources' : """
                message_loop.cc
                message_loop_proxy.cc
                message_loop_proxy_impl.cc
                message_pump_libevent.cc
                pending_task.cc
                task_runner.cc
                threading/post_task_and_reply_impl.cc
                threading/thread.cc
                tracking_info.cc
                """,
    'libs' : 'event base-glib-${bslot}',
    'pc_libs' : 'glib-2.0',
  },
  {
    'name' : 'dl',
    'sources' : """
                native_library_posix.cc
                """,
    'libs' : 'dl',
    'pc_libs' : '',
  },
]

env = Environment()

BASE_VER = os.environ.get('BASE_VER', '0')
PKG_CONFIG = os.environ.get('PKG_CONFIG', 'pkg-config')

env.Append(
  CPPPATH=['files'],
  CCFLAGS=['-g']
)
for key in Split('CC CXX AR RANLIB LD NM CFLAGS CCFLAGS'):
  value = os.environ.get(key)
  if value:
    env[key] = Split(value)

env['CCFLAGS'] += ['-fPIC',
                   '-fno-exceptions',
                   '-Wall',
                   '-Werror',
                   '-DOS_CHROMEOS=1',
                   '-DTOOLKIT_VIEWS=1',
                   '-DUSE_AURA=1',
                   '-DUSE_SYSTEM_LIBEVENT=1',
                   '-I..']

# Fix issue with scons not passing some vars through the environment.
for key in Split('PKG_CONFIG SYSROOT'):
  if os.environ.has_key(key):
    env['ENV'][key] = os.environ[key]

all_base_libs = []
all_pc_libs = ''
all_libs = []
all_scons_libs = []

# Build all the shared libraries.
for lib in base_libs:
  pc_libs = lib['pc_libs'].replace('${bslot}', BASE_VER)
  all_pc_libs += ' ' + pc_libs

  libs = Split(lib['libs'].replace('${bslot}', BASE_VER))
  all_libs += libs

  name = '%s-%s-%s' % (base_name, lib['name'], BASE_VER)
  all_base_libs += [name]
  corename = '%s-core-%s' % (base_name, BASE_VER)
  # Automatically link the sub-libs against the main core lib.
  # This is to keep from having to explicitly mention it in the
  # table above (i.e. lazy).
  if name != corename:
    libs += [corename]

  e = env.Clone()
  e.Append(
    LIBS = Split(libs),
    LIBPATH = ['.'],
    LINKFLAGS = ['-Wl,--as-needed', '-Wl,-z,defs',
                 '-Wl,-soname,lib%s.so' % name],
  )
  if pc_libs:
    e.ParseConfig(PKG_CONFIG + ' --cflags --libs %s' % pc_libs)
  all_scons_libs += [ e.SharedLibrary(name, Split(lib['sources'])) ]


# Build the random text files (pkg-config and linker script).

def lib_list(libs):
  return ' '.join(['-l' + l for l in libs])

subst_dict = {
  '@BSLOT@' : BASE_VER,
  '@PRIVATE_PC@' : all_pc_libs,
  '@BASE_LIBS@' : lib_list(all_base_libs),
  '@LIBS@' : lib_list(all_libs),
}
env = Environment(tools = ['textfile'], SUBST_DICT = subst_dict)

env.Substfile('libchrome-%s.pc' % BASE_VER,
              [Value("""
prefix=/usr
includedir=${prefix}/include
bslot=@BSLOT@

Name: libchrome
Description: chrome base library
Version: ${bslot}
Requires:
Requires.private: glib-2.0 @PRIVATE_PC@
Libs: -lbase-${bslot}
Libs.private: @BASE_LIBS@ @LIBS@
Cflags: -I${includedir}/base-${bslot}
""")])

env.Substfile('libbase-%s.so' % BASE_VER,
              [Value('GROUP ( AS_NEEDED ( @BASE_LIBS@ ) )')])
