# FindOpenWatcom.cmake
#
# Locate an Open Watcom v2 toolchain usable for building the 16-bit DOS
# mars-nwe DOS utilities on a Linux host.
#
# Result variables:
#   OpenWatcom_FOUND
#   OPENWATCOM_WCL
#   OPENWATCOM_WCC
#   OPENWATCOM_WASM
#   OPENWATCOM_WLINK
#   OPENWATCOM_BIN_DIR
#   OPENWATCOM_ROOT
#   OPENWATCOM_ENV
#
# This module intentionally does not enable a CMake language/toolchain. The
# DOS utilities are built via custom commands. OPENWATCOM_ENV is provided so
# wcl can find its helper programs such as wcc, wlink and include files.

set(_OPENWATCOM_HINTS)

if(DEFINED ENV{WATCOM})
    list(APPEND _OPENWATCOM_HINTS "$ENV{WATCOM}")
endif()

list(APPEND _OPENWATCOM_HINTS
    /opt/watcom
    /usr/local/watcom
    /usr/local/open-watcom-v2
    /opt/open-watcom-v2
)

find_program(OPENWATCOM_WCL
    NAMES wcl owcc
    HINTS ${_OPENWATCOM_HINTS}
    PATH_SUFFIXES binl binnt binw bin
)

find_program(OPENWATCOM_WCC
    NAMES wcc
    HINTS ${_OPENWATCOM_HINTS}
    PATH_SUFFIXES binl binnt binw bin
)

find_program(OPENWATCOM_WASM
    NAMES wasm
    HINTS ${_OPENWATCOM_HINTS}
    PATH_SUFFIXES binl binnt binw bin
)

find_program(OPENWATCOM_WLINK
    NAMES wlink
    HINTS ${_OPENWATCOM_HINTS}
    PATH_SUFFIXES binl binnt binw bin
)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(OpenWatcom
    REQUIRED_VARS
        OPENWATCOM_WCL
        OPENWATCOM_WCC
        OPENWATCOM_WASM
        OPENWATCOM_WLINK
)

if(OpenWatcom_FOUND)
    get_filename_component(OPENWATCOM_BIN_DIR "${OPENWATCOM_WCL}" DIRECTORY)
    get_filename_component(OPENWATCOM_ROOT "${OPENWATCOM_BIN_DIR}" DIRECTORY)

    # wcl starts helper tools such as wcc/wlink by name. Therefore finding the
    # absolute wcl path is not enough; the Watcom bin directory must be in PATH
    # at build time. WATCOM and INCLUDE are also expected by many installations.
    set(OPENWATCOM_ENV
        "WATCOM=${OPENWATCOM_ROOT}"
        "INCLUDE=${OPENWATCOM_ROOT}/h:${OPENWATCOM_ROOT}/h/nt:${OPENWATCOM_ROOT}/h/os2"
        "EDPATH=${OPENWATCOM_ROOT}/eddat"
        "PATH=${OPENWATCOM_BIN_DIR}:$ENV{PATH}"
    )
endif()

mark_as_advanced(
    OPENWATCOM_WCL
    OPENWATCOM_WCC
    OPENWATCOM_WASM
    OPENWATCOM_WLINK
)
