#
#  Copyright (C) 2019, Thomas Maier-Komor
#
#  This file is part of xjobs.
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

cmake_minimum_required(VERSION 3.0.0)

include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckLibraryExists)
include(CheckSymbolExists)
include(CMakePrintHelpers)

project(xjobs C)

find_package(FLEX)

add_compile_options("-Wall")

check_include_file(sys/wait.h HAVE_WAIT_H)
check_include_file(ncurses.h HAVE_NCURSES_H)
check_include_file(curses.h HAVE_CURSES_H)
check_include_file(term.h HAVE_TERM_H)

check_symbol_exists(wait4 sys/wait.h HAVE_WAIT4)
check_symbol_exists(strerror string.h HAVE_STRERROR)
check_symbol_exists(mmap sys/mman.h HAVE_MMAP)

### posix spawn is per default disabled, as fork is faster
#check_symbol_exists(posix_spawn spawn.h HAVE_SPAWN)

find_library(LIBM m)
if (LIBM)
	set(LIBS ${LIBS} ${LIBM})
endif()

find_library(LIBNCURSES ncurses)
if (LIBNCURSES)
	set(LIBS ${LIBS} ${LIBNCURSES})
else()
	find_library(LIBCURSES curses)
	if (LIBCURSES)
		set(LIBS ${LIBS} ${LIBCURSES})
	endif()
endif()

find_library(LIBTINFO tinfo)
if (LIBTINFO)
	set(LIBS ${LIBS} ${LIBTINFO})
endif()

FLEX_TARGET(tokenizer_l
	tokenizer.l
	${CMAKE_CURRENT_BINARY_DIR}/tokenizer.c
	COMPILE_FLAGS "-F"
)

configure_file(config.h.cm config.h)

add_custom_target(version_h COMMAND sh mkversion.sh)

add_executable(xjobs
	xjobs.c
	colortty.c
	jobctrl.c
	lexextra.c
	log.c
	settings.c
	support.c
	${FLEX_tokenizer_l_OUTPUTS}
)

add_dependencies(xjobs version_h)

target_link_libraries(xjobs ${LIBS})
set_property(TARGET xjobs PROPERTY C_STANDARD 11)

install(TARGETS xjobs
	PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
	DESTINATION bin
)

install(FILES xjobs.1
	DESTINATION man/man.1
	PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
)

install(CODE "execute_process(COMMAND bash -c \"
	mkdir -p ${CMAKE_INSTALL_PREFIX}/etc;
	if [ ! -f ${CMAKE_INSTALL_PREFIX}/etc/xjobs.rc ]; then
		cp -n xjobs.rc ${CMAKE_INSTALL_PREFIX}/etc &&
		chmod 0644 ${CMAKE_INSTALL_PREFIX}/etc/xjobs.rc &&
		echo installed ${CMAKE_INSTALL_PREFIX}/etc/xjobs.rc ||
		echo failed to install ${CMAKE_INSTALL_PREFIX}/etc/xjobs.rc;
	else
		echo please update existing ${CMAKE_INSTALL_PREFIX}/etc/xjobs.rc manually;
	fi\"
	)"
)
