project('luasocket', ['c'], meson_version: '>=0.56')
cc=meson.get_compiler('c')

deps_path = get_option('deps_dir')
deps_libs = [
    join_paths(meson.project_source_root(), deps_path),
    join_paths(meson.project_build_root(), deps_path)
]
extra_inc = []

luaver = get_option('lua_version')

if luaver == 'luajit'
    lua_dep = dependency('luajit')
elif luaver != 'auto' and luaver != 'custom' and luaver != 'vendor'
    lua_dep = dependency('lua' + luaver, required: false)
    if not lua_dep.found()
        lua_dep = dependency('lua-' + luaver, required: false)
    endif
    if not lua_dep.found()
        lua_dep = dependency('lua' + ''.join(luaver.split('.')), required: false)
    endif
    if not lua_dep.found()
        lua_dep = dependency('lua')
    endif
    if not lua_dep.version().startswith(luaver)
        error('required lua version not found (got @0@)'
            .format(lua_dep.version()))
    endif
elif luaver == 'custom'
    lua_dep = dependency('', required: false)
elif luaver == 'vendor'
    lua_dep = dependency('', required: false)
    extra_inc += include_directories(join_paths(deps_path, 'include'))
else
    lua_dep = dependency('lua')
endif

luaver_maj = '5'
luaver_num = cc.compute_int(
    'LUA_VERSION_NUM',
    dependencies: lua_dep, include_directories: extra_inc
)
luaver_min = luaver_num - 500
luaver_str = '@0@.@1@'.format(luaver_maj, luaver_min)

if luaver_min < 1
    error('Lua 5.1 or newer is required')
endif

# follow what lua does, i.e. .so everywhere except windows
plugin_suffix = 'so'

if host_machine.system() == 'windows'
    plugin_suffix = 'dll'
endif

if host_machine.system() == 'windows'
    # msys2, etc
    lua_adep = cc.find_library('lua', dirs: deps_libs, required: false)
    if not lua_adep.found()
        # lua 5.1 uses lua5.1.dll/lib
        lua_adep = cc.find_library(
            'lua@0@.@1@'.format(luaver_maj, luaver_min),
            dirs: deps_libs, required: false
        )
    endif
    if not lua_adep.found()
        # lua 5.2 onwards uses lua5.2.dll/lib
        lua_adep = cc.find_library(
            'lua@0@@1@'.format(luaver_maj, luaver_min), dirs: deps_libs
        )
    endif
else
    lua_adep = lua_dep.partial_dependency(compile_args: true, includes: true)
endif