
set(scripts
    dump metview-mail mvrun mvrun_c mvrun_lnx
    logrun metview_stat metview_create_user_dir
    metview_patches
    mvusage metview_help set_mars_env
    document_macros.pl mv_grib_dump
    metview_local.${MV_ENVIRON} metview_local2.${MV_ENVIRON}
    MarsTiggeWrapper
    MarsOdbWrapper
    generate_video
    mv_compress mv_mail mv_uniquename
    mv_eccharts.py
    mv_odbsql mv_obstat
    mv_mars_catalog.py
    mv_flextra_prep.mv mv_flextra_prep mv_flextra_run
    mv_flexpart_run mv_flexpart_pp
    mv_met3d_prep.mv
    mv_preview.mv
    mv_rttov_run
    mv_scm_run mv_scm_vis.mv
    mv_vapor_prep.mv mv_vapor_gui
    select_mars_config
)

set(generated_scripts )

if(AT_ECMWF)
    list(APPEND scripts mv_debug_env.sh)
endif()

if(HAVE_PPROC_MIR)
    list(APPEND scripts MarsMirWrapper DivrotMirWrapper)
endif()

if(HAVE_PPROC_EMOS)
    list(APPEND scripts MarsEmosWrapper DivrotEmosWrapper)
endif()

if(ENABLE_STVL)
    list(APPEND generated_scripts mv_stvl)
endif()



# handle these script files

foreach( script ${scripts} )
    # ensure that the target/dependency relationship is correct
    configure_file( ${script} ${CMAKE_BINARY_DIR}/bin COPYONLY)

    # copy to the build 'bin' directory, setting exe permissions
    file(COPY ${script}
         DESTINATION ${CMAKE_BINARY_DIR}/bin
         FILE_PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ OWNER_EXECUTE GROUP_EXECUTE
         )
endforeach()


foreach( script ${generated_scripts} )
    configure_file( "${script}.in" ${CMAKE_BINARY_DIR}/bin/${script} @ONLY)
endforeach()


foreach( script ${scripts} ${generated_scripts} )
    # ensure file is installed at install time
    install( FILES ${CMAKE_BINARY_DIR}/bin/${script}
             DESTINATION ${MV_BIN_DIR}
             PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
endforeach()






# remove unnecessary items from a colon-separated list (e.g. /usr/lib64, which can interfere if we use non-default compilers)
function(removeUnwantedCompileItemsFromColonString colonString)
    string (REPLACE ":"  ";"   LOC_AS_LIST "${${colonString}}")
    list(REMOVE_ITEM LOC_AS_LIST "/usr/lib")
    list(REMOVE_ITEM LOC_AS_LIST "/usr/lib64")
    string (REPLACE ";"  ":"   LOC_AS_STRING "${LOC_AS_LIST}")
    set (${colonString} ${LOC_AS_STRING} PARENT_SCOPE)
endfunction()


# remove non-compiler items and unnecessary items from the string
function(removeUnwantedCompileItems compileList)
    set(loc ${${compileList}})
    list(REMOVE_ITEM loc "debug")        
    list(REMOVE_ITEM loc "optimized")
    list(REMOVE_ITEM loc "/usr/lib")
    list(REMOVE_ITEM loc "/usr/lib64")
    list(REMOVE_ITEM loc "-L/usr/lib")
    list(REMOVE_ITEM loc "-L/usr/lib64")
    list(REMOVE_ITEM loc "-Wl,-rpath,/usr/lib")
    list(REMOVE_ITEM loc "-Wl,-rpath,/usr/lib64")

    # items could themselves be lists, e.g. rpath=/usr/lib:/usr/local/lib
    foreach (item ${loc})
        set(item1 ${item})
        removeUnwantedCompileItemsFromColonString(item1)
        list(APPEND final_result ${item1})
    endforeach()

    set (${compileList} ${final_result} PARENT_SCOPE)
endfunction()


function(removeUnwantedCompileItemsFromString compileString)
    # convert from string to list, remove items, then convert back to string
    string (REPLACE " "  ";"   LOC_AS_LIST "${${compileString}}")
    removeUnwantedCompileItems(LOC_AS_LIST)
    string (REPLACE ";"  " "   LOC_AS_STRING "${LOC_AS_LIST}")
    set (${compileString} " ${LOC_AS_STRING}" PARENT_SCOPE) # preserve leading space
endfunction()



##############################################################
#
# generate the 'compile' script for inline C/Fortran in Macro




# for GRIB_API, we *might* get something like
# grib_api;grib_api_f77;grib_api_f90;/usr/lib64/libjasper.so;/usr/lib64/libjpeg.so;/usr/lib64/libm.so
# which is not all that we need to link. So we convert 'grib_api' into '-lgrib_api'
# and for the Fortran libraries.

#get_target_property(OUT marsclient LINK_LIBRARIES)
#message(STATUS "LINK_LIBRARIES ${OUT}")
#get_target_property(OUT marsclient INCLUDE_DIRECTORIES)
#message(STATUS "INCLUDE_DIRECTORIES ${OUT}")
#get_target_property(OUT marsclient INTERFACE_INCLUDE_DIRECTORIES)
#message(STATUS "INTERFACE_INCLUDE_DIRECTORIES ${OUT}")
#get_target_property(OUT marsclient INTERFACE_LINK_LIBRARIES)
#message(STATUS "INTERFACE_LINK_LIBRARIES ${OUT}")
#message(STATUS  "GRIB_API_LIBRARIES : ${GRIB_API_LIBRARIES}")

set(GRIB_API_LIBRARIES_STR " ${GRIB_API_LIBRARIES}") # add a space to the beginning

string (REPLACE ";"         " "           GRIB_API_LIBRARIES_STR    "${GRIB_API_LIBRARIES_STR}")
set (GRIB_API_LIBRARIES_STR  "${GRIB_API_LIBRARIES_STR} -leccodes")

if (HAVE_METVIEW_FORTRAN)
    set (GRIB_API_LIBRARIES_STR  "${GRIB_API_LIBRARIES_STR} -leccodes_f90")
endif()

set(GRIB_API_LIBRARIES_STR "${GRIB_API_LIBRARIES_STR} ${PTHREAD_LIB}") # add pthread in case needed


# we may need to add the netCDF lib dir to the rpath. We don't seem to have a variable
# which tells us this directly, so we need to make an educated guess...
if(DEFINED NETCDF_INCLUDE_DIR)
    set(NETCDF_LIB_RPATH "-Wl,-rpath,${NETCDF_INCLUDE_DIR}/../lib64:${NETCDF_INCLUDE_DIR}/../lib")
    set(GRIB_API_LIBRARIES_STR "${GRIB_API_LIBRARIES_STR} ${NETCDF_LIB_RPATH}")
endif()

set(GRIB_API_LIBRARIES_STR_ORIGINAL "${GRIB_API_LIBRARIES_STR}")       # keep a backup for later


# if we are linking with shared GRIB_API libraries, then in order to be able
# to run compiled inline Fortran/C/Macro programs, we will need to set
# LD_LIBRARY_PATH to where GRIB_API was installed (this should only be
# needed if GRIB_API was installed in a non-default location).

# print all variables
#get_cmake_property(_variableNames VARIABLES)
#foreach (_variableName ${_variableNames})
#    ecbuild_info("${_variableName}=${${_variableName}}")
#endforeach()

# first, if GRIB_API_PATH is not defined, then we need to compute the path
set( grib_handling_pkg grib_api )
if( eccodes_FOUND )
  set( grib_handling_pkg eccodes )
endif()
if(NOT GRIB_API_PATH)
    ###get_property(GRIB_LIB_PATH TARGET ${grib_handling_pkg} PROPERTY LIBRARY_OUTPUT_DIRECTORY)
    ###$<TARGET_FILE:odc>
    if(GRIB_LIB_PATH)
        set(GRIB_API_PATH ${GRIB_LIB_PATH}/..)
    else()
        if (grib_api_BASE_DIR)
            set(GRIB_API_PATH ${grib_api_BASE_DIR})
        else()
            if(CMAKE_PREFIX_PATH)
                set(GRIB_API_PATH ${CMAKE_PREFIX_PATH})
            endif()
        endif()
    endif()
    ecbuild_info("Computed GRIB_PATH: ${GRIB_API_PATH}")
endif()


if(GRIB_API_PATH)
    set(GRIB_API_RPATH "${GRIB_API_PATH}/lib:${GRIB_API_PATH}/lib64")
endif()


# for each of the GRIB library's dependencies, we should find the directory name
# and add it to the -L and to the rpath

foreach (gtpl ${GRIB_API_TPL_LIBRARIES})
    get_filename_component(gtpl_i ${gtpl} PATH)  # DIRECTORY only in CMake > 2.8.12+
    list(APPEND GRIB_LIB_TPL_DIRS ${gtpl_i})
endforeach()

if (GRIB_LIB_TPL_DIRS)
    list(REMOVE_DUPLICATES GRIB_LIB_TPL_DIRS)
    string (REPLACE ";" ":"   GRIB_LIB_TPL_RPATH    "${GRIB_LIB_TPL_DIRS}")
endif()
set(GRIB_API_RPATH "${GRIB_API_RPATH}:${GRIB_LIB_TPL_RPATH}")

set(GRIB_API_LIBRARIES_STR "-L${GRIB_API_PATH}/lib -L${GRIB_API_PATH}/lib64 -Wl,-rpath,${GRIB_API_RPATH} ${GRIB_API_LIBRARIES_STR}")
removeUnwantedCompileItemsFromString(GRIB_API_LIBRARIES_STR)


# add the GRIB include directories to the compiler directives
if(DEFINED GRIB_API_INCLUDE_DIRS)
    # linking with external eccodes
    foreach (inc ${GRIB_API_INCLUDE_DIRS})
        set(GRIB_API_INCLUDE_DIRS_STR "${GRIB_API_INCLUDE_DIRS_STR} -I${inc}")
    endforeach()
else()
    # linking with eccodes in a bundle
    set(GRIB_API_INCLUDE_DIRS_STR "-I${eccodes_BASE_DIR}/include -I${eccodes_BINARY_DIR}/src -I${eccodes_SOURCE_DIR}/src")
endif()
list(APPEND METVIEW_INLINE_DEFINITIONS ${GRIB_API_DEFINITIONS})

#
# something similar for fdb
#

if(fdb_FOUND)
    if(fdb_LIBRARY)  # fdb in bundle
        get_filename_component(FDB_LIB_DIR ${fdb_LIBRARY} PATH)
        set(FDB_LIBRARIES_STR "${FDB_LIBRARY} -Wl,-rpath,${FDB_LIB_DIR}")
    else()           # fdb not in bundle
        foreach(fdblib ${FDB_LIBRARIES})
            set(FDB_MINUS_L_LIBS " -l${fdblib} ${FDB_MINUS_L_LIBS}")
        endforeach()
        set(FDB_LIBRARIES_STR "")
        set(libdirs lib lib64)
        foreach(libdir ${libdirs})
            set(FDB_LIBRARIES_STR "-Wl,-rpath,${fdb_BASE_DIR}/${libdir} -L${fdb_BASE_DIR}/${libdir} ${FDB_LIBRARIES_STR}")
        endforeach()
        set(FDB_LIBRARIES_STR "${FDB_MINUS_L_LIBS} ${FDB_LIBRARIES_STR}")
    endif()
endif()


# in the case of a static libemos, we may need to be explicit about about the Fortran libraries when
# building inline C
foreach(fortlib ${CMAKE_Fortran_IMPLICIT_LINK_LIBRARIES})
    set(IMPLICIT_FORTRAN_LIBS "-l${fortlib}  ${IMPLICIT_FORTRAN_LIBS}")
endforeach()



configure_file(compile.in ${CMAKE_BINARY_DIR}/bin/compile @ONLY)



# in the case of a bundle, the GRIB_API and emoslib locations will have been
# set to their build directories, which is correct when running from 
# the build directory, but not once installed, so we have to change these
# to the location where they will be installed, and create another 'compile'
# script which is the one that will actually be installed. In the case where
# we're not building a bundle, these two compile scripts will be identical.

# this checks if ECCODES is inside a bundle with us
if(MV_BUNDLE_CONTAINS_ECCODES)
    set(GRIB_API_LIBRARIES_STR    "-L${CMAKE_INSTALL_PREFIX}/lib ${GRIB_API_LIBRARIES_STR_ORIGINAL}")
    set(GRIB_API_INCLUDE_DIRS_STR "-I${CMAKE_INSTALL_PREFIX}/include")
    set(GRIB_API_PATH ${CMAKE_INSTALL_PREFIX})
endif()

# this checks if emoslib is inside a bundle with us
if(MV_BUNDLE_CONTAINS_EMOSLIB)
	string(REPLACE "${CMAKE_BINARY_DIR}/lib"  "${CMAKE_INSTALL_PREFIX}/lib"  EMOS_LIBRARIES_STR  "${EMOS_LIBRARIES_STR}")
endif()


# it would be nice to be a bit neater here, but this aspect is hard-coded in ecCodes
# and the fact that the path for MMFS definitions is in /MEMFS is not accessible
# from CMake, so we need to duplicate that piece of information here

if(eccodes_HAVE_MEMFS)
    set(GRIB_API_SHARE_DIR "/MEMFS")
else()
    set(GRIB_API_SHARE_DIR "${GRIB_API_PATH}/share/${grib_handling_pkg}")
endif()


# export upwards so that CodesUI can use it if need be
set (GRIB_API_PATH ${GRIB_API_PATH} PARENT_SCOPE)


if( DEFINED NETCDF_PATH )
    set(NETCDF_BIN "${NETCDF_PATH}/bin")
else()
    set(NETCDF_BIN "")
endif()

if(MV_BUNDLE_CONTAINS_METVIEW)
    set(METVIEW_BUNDLE_SRC ${CMAKE_SOURCE_DIR})
endif()

if(MV_BUNDLE_CONTAINS_MAGICS)
    set(MV_BUNDLE_MAGICS_SRC ${CMAKE_SOURCE_DIR}/magics)
endif()


configure_file(compile.in ${CMAKE_BINARY_DIR}/bin/compile_install @ONLY)



install( FILES ${CMAKE_BINARY_DIR}/bin/compile_install  
         DESTINATION ${MV_BIN_DIR}
         RENAME      compile
         PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)




##################
#
# for metview_base





ecbuild_get_date(TODAYS_DATE)


# # Add certain paths to LD_LIBRARY_PATH.
# # If the given path is not a standard system one, then add it to our list
# # of paths to add to LD_LIBRARY_PATH on Metview's startup. We want to
# # avoid adding system paths here because they can override non-default
# # paths (case in point: the wrong OpenGL library has been known to be
# # picked up - used by VAPOR).
#
# NO - this is not really needed with the rpath, and it can lead, in the
# case of a bundle, to the build directory (Magics) going into the
# LD_LIBRARY_PATH even when installed (no harmful effect seen though).
# 
# set(SYS_LIBDIRS "/usr/lib64" "/usr/lib64/" "/usr/lib" "/usr/lib/" "")
# set(METVIEW_LD_PATHS "")
# 
# foreach(LIBPATH ${MAGICS_LIB_DIR} ${ODB_API_LIB_DIR} ${GRIB_API_LIB_DIR})
#     list(FIND SYS_LIBDIRS ${LIBPATH} IND)
#     if(IND EQUAL -1)  # path not in the list of system paths
#         set(METVIEW_LD_PATHS "${LIBPATH}:${METVIEW_LD_PATHS}")
#     endif()
# endforeach()



# MAGPLUS_HOME - under normal circumstances, we link with a specific
# Magics library which knows where it's been installed, so we don't
# need (or want) to set MAGPLUS_HOME, and in fact we want to avoid
# the situation where a user sets it to the wrong path (as can happen
# if a Magics module is set up by default in a user's environment).
# So the simplest thing is to unset MAGPLUS_HOME and let the library
# find its own resource files. This works fine if Magics has been
# installed, but not if we are linking with a Magics in the build tree.
# In this case MAGPLUS_HOME will need to point to the Magics source(!)
# directory. In Magics 2.27.0 onwards, this is all taken care of by the
# CMake variable MAFPLUS_HOME. If this is not set (i.e. earlier version
# of Magics) then we just unset it. MV_MAGPLUS_HOME_PATH_SET is used
# in metview_base.in.

if(DEFINED MAGPLUS_HOME)
    set(MV_MAGPLUS_HOME_PATH_SET "MAGPLUS_HOME=${MAGPLUS_HOME}")
else()
    set(MV_MAGPLUS_HOME_PATH_SET "unset MAGPLUS_HOME")
endif()

if(DEFINED INSTALL_LIB_DIR) # could be lib or lib64
    set(MV_INSTALL_LIB_DIR ${INSTALL_LIB_DIR})
else()
    set(MV_INSTALL_LIB_DIR "lib")
endif()



# MV_BUNDLE_TOOLS_BIN
# - in particular, where odb_migrator (from odb-tools) is located
if((MV_BUNDLE_CONTAINS_METVIEW) AND (NOT ENABLE_EXPOSE_SUBPACKAGES))
    set(MV_BUNDLE_TOOLS_BIN "$METVIEW_BIN/..")
endif()


# MetZoom installation dir supplied?
if (DEFINED METZOOM_START_CMD)
    set(METZOOM_ENV "MV_METZOOM_START_CMD=${METZOOM_START_CMD}")
else()
    set(METZOOM_ENV "")
endif()



# create the Metview startup script
configure_file(metview_base.in ${FULL_STARTUP_SCRIPT_PATH} @ONLY)


# create a 'production' version of this - just the same, but with
# METVIEW_VERSION=prod instead of dev

set(PROD_TEMPORARY_STARTUP_SCRIPT "${FULL_STARTUP_SCRIPT_PATH}_prod")

add_custom_command( 
    OUTPUT  ${PROD_TEMPORARY_STARTUP_SCRIPT}
    COMMAND sed "s/METVIEW_VERSION=dev/METVIEW_VERSION=prod/g" ${FULL_STARTUP_SCRIPT_PATH} > ${PROD_TEMPORARY_STARTUP_SCRIPT}
    DEPENDS ${FULL_STARTUP_SCRIPT_PATH}
)


ADD_CUSTOM_TARGET(mvs ALL DEPENDS ${FULL_STARTUP_SCRIPT_PATH} ${PROD_TEMPORARY_STARTUP_SCRIPT})


# when we install, we actually want to install the production script and rename it
# NOTE: if building as part of a bundle, then we have the option (EXPOSE_SUBPACKAGES)
# of installing everything apart from the startup script into a subdirectory so that
# libs and executables from other packages don't clash with anything else on
# the system. If we elect to do this (NOT EXPOSE_SUBPACKAGES) then we will have already
# modified the CMAKE_INSTALL_PREFIX (in the bundle's top-level CMakeLists.txt file) to
# put everything two levels deeper. But... we want the startup script to go
# into the original CMAKE_INSTALL_PREFIX/bin directory

if((MV_BUNDLE_CONTAINS_METVIEW) AND (NOT ENABLE_EXPOSE_SUBPACKAGES))
    if(MV_BIN_DIR STREQUAL "bin")
        # 3 levels up because otherwise we install into ${CMAKE_INSTALL_PREFIX}/lib/metview-bundle/bin
        set (STARTUP_SCRIPT_INSTALL_DIR "${INSTALL_BIN_DIR}/../../../bin")
    else()
        # 4 levels up because otherwise we install into ${CMAKE_INSTALL_PREFIX}/lib/metview-bundle/bin/metview_bin
        set (STARTUP_SCRIPT_INSTALL_DIR "${INSTALL_BIN_DIR}/../../../../bin")
    endif()
else()
    set (STARTUP_SCRIPT_INSTALL_DIR bin)
endif()
ecbuild_info("Startup script will be installed to: ${STARTUP_SCRIPT_INSTALL_DIR}")

set (INSTALLED_METVIEW_STARTUP_SCRIPT "${CMAKE_INSTALL_PREFIX}/${STARTUP_SCRIPT_INSTALL_DIR}/${METVIEW_SCRIPT}" PARENT_SCOPE)

install( FILES       ${PROD_TEMPORARY_STARTUP_SCRIPT}
         RENAME      ${METVIEW_SCRIPT}
         DESTINATION ${STARTUP_SCRIPT_INSTALL_DIR} # NOT ${MV_BIN_DIR}!
         PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)



## TODO
## If we are building this outside ECMWF, then we want different proxy settings
## (used currently by the OGC clients). We achieve this by simply changing the
## default setting in the ConfigDef file. We can do this with a  a search/replace
## operation. This relies very much on the proxy setting having a uniqe 'signature'
## so that the search/replace can operate on a single line.
#
#if test "x$SITE_NAME" != 'xecmwf'; then
#    configdef=share/metview/etc/ConfigDef
#    configtmp=${configdef}.tmp
#    echo "Not at ECMWF: resetting the default proxy setting in ${configdef}."
#    chmod u+w $configdef
#    sed "s/	} = yes/	} = no/g"  $configdef > $configtmp
#    mv $configtmp $configdef
#fi

#ecbuild_dont_pack(FILES metview_local.ecmwf metview_local2.ecmwf)

ecbuild_dont_pack(FILES "update_MetApps_files.sh")

