# -*- mode: python; -*-

import libdeps

Import("env")
Import("get_option")

env = env.Clone()

if not env['MONGO_HAVE_LIBMONGOC']:
    Return()

if get_option('install-mode') == 'hygienic':
    env.AutoInstall(
        'share/doc/mongoc_embedded',
        source=[
            '#/LICENSE-Community.txt',
            '../LICENSE-Embedded.txt',
        ],
        INSTALL_ALIAS=[
            'embedded-dev',
        ],
    )

def create_mongoc_env(env):
    mongocEnv = env.Clone()
    if mongocEnv['MONGO_HAVE_LIBMONGOC'] == "framework":
        mongocEnv.AppendUnique(FRAMEWORKS=['bson', 'mongoc'])
    else:
        mongocEnv.AppendUnique(LIBS=['bson-1.0', 'mongoc-1.0'])
    return mongocEnv

mongocEmbeddedEnv = create_mongoc_env(env)

mongocEmbeddedEnv.AppendUnique(
    CPPDEFINES=[
        'MONGOC_EMBEDDED_COMPILING',
     ],
)

if get_option('link-model') == 'static':
    mongocEmbeddedEnv.AppendUnique(
        CPPDEFINES=[
            'MONGOC_EMBEDDED_STATIC',
        ],
    )

# Please see the note in ../mongo_embedded/SConscript about how to
# interpret and adjust the current and compatibility versinos.
mongocEmbeddedEnv.AppendUnique(
    SHLINKFLAGS=[
        '$MONGO_EXPORT_FILE_SHLINKFLAGS',
    ],
)

if mongocEmbeddedEnv.TargetOSIs('darwin'):
    # Please see the note in ../mongo_embedded/SConscript about how to
    # interpret and adjust the current and compatibility versinos.
    mongocEmbeddedEnv.AppendUnique(
        SHLINKFLAGS=[
            '-Wl,-current_version,1',
            '-Wl,-compatibility_version,1',
        ],
    )

mongocEmbeddedTargets = mongocEmbeddedEnv.Library(
    target='mongoc_embedded',
    source=[
        'mongoc_embedded.cpp',
    ],
    LIBDEPS=[
        # No LIBDEPS or LIBDEPS_PRIVATE to mongo libraries are allowed in this library. They would get duplicated in mongo_embedded_capi.
        '$BUILD_DIR/mongo/embedded/mongo_embedded/mongo_embedded',
    ],
    INSTALL_ALIAS=[
        'embedded-dev',
    ],
)

if get_option('install-mode') == 'hygienic':
    env.AutoInstall(
        'include/mongoc_embedded/v1/mongoc_embedded',
        source=['mongoc_embedded.h'],
        INSTALL_ALIAS=[
            'embedded-dev',
        ],
    )

yamlEnv = env.Clone()
yamlEnv.InjectThirdPartyIncludePaths(libraries=['yaml'])

if get_option('link-model') != 'dynamic-sdk':
    mongocEmbeddedTestEnv = create_mongoc_env(yamlEnv)
    clientTest = mongocEmbeddedTestEnv.Program(
        target='mongoc_embedded_test',
        source=[
            'mongoc_embedded_test.cpp',
        ],
        LIBDEPS=[
            '$BUILD_DIR/mongo/base',
            '$BUILD_DIR/mongo/db/server_options_core',
            '$BUILD_DIR/mongo/unittest/unittest',
            '$BUILD_DIR/mongo/util/options_parser/options_parser',
            'mongoc_embedded',
        ],
        INSTALL_ALIAS=[
            'embedded-test',
        ],
    )

    env.RegisterUnitTest(clientTest[0]);

# Frameworkization craziness begins here. Honestly, we should do this
# better in the future in some re-usable way, but we need to get this
# thing out the door, so here goes.

# First, we only do this in hygienic mode for the mobile targets,
# which are darwin but not macOS. For all others, we abort here. Maybe
# this should be a build flag? Since we aren't doing this for macOS,
# we can also ignore all the framework version nonsense.
if get_option('link-model') != 'dynamic-sdk' or get_option('install-mode') != 'hygienic' or not env.TargetOSIs('darwin') or env.TargetOSIs('macOS'):
    Return()

frameworkDir = env.Dir('$INSTALL_DIR/Frameworks/mongoc_embedded.framework')
env.Alias('install-embedded-dev', frameworkDir)

resourceDir = frameworkDir
if env.TargetOSIs('macOS'):
    resourceDir = resourceDir.Dir('Resources')

env.Install(
    target=resourceDir,
    source=env.File(
        name=[
            'LICENSE-Community.txt',
            'LICENSE-Embedded.txt',
        ],
        directory=env.Dir('$INSTALL_DIR/share/doc/mongoc_embedded'),
    ),
)

env.Install(
    target=frameworkDir.Dir('Headers'),
    source=env.File('mongoc_embedded.h'),
)

env.InstallAs(
    target=frameworkDir.File('Modules/module.modulemap'),
    source="mongoc_embedded.modulemap"
)

mongocEmbeddedPlist = env.Substfile(
    target="Info.plist",
    source='../Info.plist.in',
    SUBST_DICT=[
        ('@CFBundleExecutable@', 'mongoc_embedded'),
        ('@CFBundleIdentifier@', 'org.mongodb.mongoc-embedded'),
        ('@CFBundleVersion@', env['PLIST_MONGO_BUNDLE_VERSION']),
        ('@CFBundleShortVersionString@', env['PLIST_MONGO_BUNDLE_VERSION']),
        ('@MinimumOSVersion@', env['PLIST_MINIMUM_OS_VERSION'])
    ]
)

env.Install(
    target=resourceDir,
    source=mongocEmbeddedPlist,
)

mongocEmbeddedFwLib = env.InstallAs(
    target=frameworkDir.File('mongoc_embedded'),
    source=mongocEmbeddedTargets[0],
)

env.AddPostAction(
    files=mongocEmbeddedFwLib,
    action=[
        "install_name_tool -delete_rpath @loader_path/../lib $TARGET",
        "install_name_tool -id @rpath/mongoc_embedded.framework/mongoc_embedded $TARGET",
        "install_name_tool -change @rpath/libmongo_embedded.dylib @rpath/mongo_embedded.framework/mongo_embedded $TARGET",
    ],
)

mongocEmbeddedDSYM = getattr(mongocEmbeddedTargets[0].attributes, "separate_debug_file", None)
if mongocEmbeddedDSYM:
    frameworkDSYMDir = '$INSTALL_DIR/Frameworks/mongoc_embedded.framework.dSYM'
    env.Alias('install-embedded-dev', frameworkDSYMDir)

    env.InstallAs(
        target=frameworkDSYMDir,
        source=mongocEmbeddedDSYM,
    )

mongocEmbeddedBCSymbolMap = getattr(mongocEmbeddedTargets[0].attributes, "bcsymbolmap_file", None)
if mongocEmbeddedBCSymbolMap:
    env.Install(
        target=frameworkDir.Dir('BCSymbolMaps'),
        source=mongocEmbeddedBCSymbolMap,
    )
