# This file is part of the Owl Positioning System (OwlPS) project.
# It is subject to the copyright notice and license terms in the
# COPYRIGHT.t2t file found in the top-level directory of this
# distribution and at
#   https://code.lm7.fr/mcy/owlps/src/master/COPYRIGHT.t2t
# No part of the OwlPS Project, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the COPYRIGHT.t2t file; the COPYRIGHT.t2t file must be
# distributed along with this file, either separately or by replacing
# this notice by the COPYRIGHT.t2t file's contents.

# Toolchain file for OpenWrt


### OpenWrt options ###
#
# These options should be overriden by the user as needed when calling
# cmake (-D option).

# OpenWrt root: /opt by default
set(OPENWRT_ROOT /opt/openwrt CACHE STRING
  "OpenWrt tools' base path")

# OpenWrt version: trunk (default), 10.03, 12.09, etc.
set(OPENWRT_VERSION trunk CACHE STRING
  "OpenWrt version")

# OpenWrt architecture: mips (default), x86, etc.
set(OPENWRT_ARCH mips CACHE STRING
  "OpenWrt architecture")

# OpenWrt target: atheros (default), ar71xx, etc.
set(OPENWRT_TARGET atheros CACHE STRING
  "OpenWrt target")


### Toolchain options ###

# The target OS is Linux
set(CMAKE_SYSTEM_NAME Linux)

# Toolchain paths
set(TOOLCHAIN_PREFIX "${OPENWRT_ROOT}/${OPENWRT_TARGET}/${OPENWRT_VERSION}")
set(TOOLCHAIN1 "${TOOLCHAIN_PREFIX}/toolchain_gcc_uClibc")
set(TOOLCHAIN2 "${TOOLCHAIN_PREFIX}/target_uClibc")
set(CMAKE_FIND_ROOT_PATH "${TOOLCHAIN1}" "${TOOLCHAIN2}")

if (${OPENWRT_VERSION} VERSION_EQUAL 10.03)
  set(TOOLCHAIN_BIN "${TOOLCHAIN1}/usr/bin")
else()
  set(TOOLCHAIN_BIN "${TOOLCHAIN1}/bin")
endif()

set(STAGING_DIR "${TOOLCHAIN_PREFIX}/staging_dir")

# Cross-compiler
set(COMPILER_PREFIX "${TOOLCHAIN_BIN}/${OPENWRT_ARCH}-openwrt-linux-")
set(CMAKE_C_COMPILER "${COMPILER_PREFIX}gcc")
set(CMAKE_CXX_COMPILER "${COMPILER_PREFIX}g++")

# Search libraries and headers only in the toolchain directories
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)


### Generate the make.sh script ###
#
# It's a pitty, but we have to do that because environment variables are
# not exported to sub-processes within targets, so calling
#   set(ENV{STAGING_DIR} "${STAGING_DIR}")
# alone has no effect. (Note that it does work in execute_process()
# commands.)

set(MAKE_SCRIPT "${CMAKE_BINARY_DIR}/make.sh")
message(STATUS "Generating ${MAKE_SCRIPT}")
file(WRITE "${MAKE_SCRIPT}"
"#!/bin/sh
export STAGING_DIR=\"${STAGING_DIR}\"
exec make \"$@\"
")
execute_process(COMMAND chmod u+x "${MAKE_SCRIPT}")
