##################################################################
# Standard target filesystem paths.
##################################################################
#
# If changing these values, beware that native/cross/nativesdk bbclass
# files may also need changes to keep in sync.
#

# Used by multilib code to change the library paths
baselib = "${BASELIB}"
baselib[vardepvalue] = "${baselib}"
BASELIB = "lib"
BASELIB_powerpc64 = "lib64"
BASELIB_powerpc64le = "lib64"

# Path prefixes
export base_prefix = ""
export prefix = "/usr"
export exec_prefix = "${prefix}"

root_prefix = "${@bb.utils.contains('DISTRO_FEATURES', 'usrmerge', '${exec_prefix}', '${base_prefix}', d)}"

# Base paths
export base_bindir = "${root_prefix}/bin"
export base_sbindir = "${root_prefix}/sbin"
export base_libdir = "${root_prefix}/${baselib}"
export nonarch_base_libdir = "${root_prefix}/lib"

# Architecture independent paths
export sysconfdir = "${base_prefix}/etc"
export servicedir = "${base_prefix}/srv"
export sharedstatedir = "${base_prefix}/com"
export localstatedir = "${base_prefix}/var"
export datadir = "${prefix}/share"
export infodir = "${datadir}/info"
export mandir = "${datadir}/man"
export docdir = "${datadir}/doc"
export systemd_unitdir = "${nonarch_base_libdir}/systemd"
export systemd_system_unitdir = "${nonarch_base_libdir}/systemd/system"
export nonarch_libdir = "${exec_prefix}/lib"
export systemd_user_unitdir = "${nonarch_libdir}/systemd/user"

# Architecture dependent paths
export bindir = "${exec_prefix}/bin"
export sbindir = "${exec_prefix}/sbin"
export libdir = "${exec_prefix}/${baselib}"
export libexecdir = "${exec_prefix}/libexec"
export includedir = "${exec_prefix}/include"
export oldincludedir = "${exec_prefix}/include"
localedir = "${libdir}/locale"

# Linkage between native/cross/nativesdk layouts
base_bindir_native = "/bin"
base_sbindir_native = "/sbin"
sysconfdir_native = "/etc"
prefix_native = "/usr"
bindir_native = "${prefix_native}/bin"
sbindir_native = "${prefix_native}/sbin"
includedir_native = "${prefix_native}/include"
libdir_native = "${prefix_native}/lib"
libexecdir_native = "${prefix_native}/libexec"
base_libdir_native = "/lib"
datadir_native = "${prefix_native}/share"
bindir_cross = "/bin"
bindir_crossscripts = "${bindir}/crossscripts"
prefix_nativesdk = "/usr"
bindir_nativesdk = "${prefix_nativesdk}/bin"
sbindir_nativesdk = "${prefix_nativesdk}/sbin"
base_bindir_nativesdk = "/bin"
base_sbindir_nativesdk = "/sbin"
includedir_nativesdk = "${prefix_nativesdk}/include"
libdir_nativesdk = "${prefix_nativesdk}/lib"
base_libdir_nativesdk = "/lib"
localstatedir_nativesdk = "/var"

#
# Cross recipes need to know about the target layout
# := is used carefully here
#
target_datadir := "${datadir}"
# Used to find env/perl/python
USRBINPATH = "${bindir}"
USRBINPATH_class-native = "/usr/bin"
USRBINPATH_class-nativesdk = "/usr/bin"

# Root home directory
ROOT_HOME ??= "/home/root"

# If set to boolean true ('yes', 'y', 'true', 't', '1'), /var/log links to /var/volatile/log.
# If set to boolean false ('no', 'n', 'false', 'f', '0'), /var/log is on persistent storage.
VOLATILE_LOG_DIR ?= "yes"

##################################################################
# Architecture-dependent build variables.
##################################################################

# Immediate expansion since there is no point in repeatedly calling
# os.uname() throughout parsing
BUILD_ARCH := "${@os.uname()[4]}"
BUILD_OS := "${@os.uname()[0].lower()}"
BUILD_VENDOR = ""
BUILD_SYS = "${BUILD_ARCH}${BUILD_VENDOR}-${BUILD_OS}"
BUILD_PREFIX = ""
BUILD_CC_ARCH = ""
BUILD_LD_ARCH = ""
BUILD_AS_ARCH = ""
BUILD_EXEEXT = ""

HOST_ARCH = "${TARGET_ARCH}"
HOST_OS = "${TARGET_OS}"
HOST_VENDOR = "${TARGET_VENDOR}"
HOST_SYS = "${HOST_ARCH}${HOST_VENDOR}-${HOST_OS}"
HOST_PREFIX = "${TARGET_PREFIX}"
HOST_CC_ARCH = "${TARGET_CC_ARCH}"
HOST_LD_ARCH = "${TARGET_LD_ARCH}"
HOST_AS_ARCH = "${TARGET_AS_ARCH}"
HOST_EXEEXT = ""

TUNE_ARCH ??= "INVALID"
TUNE_CCARGS ??= ""
TUNE_CCARGS[vardepvalue] = "${TUNE_CCARGS}"
TUNE_LDARGS ??= ""
TUNE_ASARGS ??= ""
TUNE_FEATURES ??= "${TUNE_FEATURES_tune-${DEFAULTTUNE}}"
LIBCEXTENSION ??= ""
ABIEXTENSION ??= ""
USE_NLS ??= "yes"
SDKUSE_NLS ??= "yes"

TARGET_ARCH = "${TUNE_ARCH}"
TARGET_OS = "linux${LIBCEXTENSION}${ABIEXTENSION}"
TARGET_VENDOR = "-oe"
TARGET_SYS = "${TARGET_ARCH}${TARGET_VENDOR}-${TARGET_OS}"
TARGET_PREFIX = "${TARGET_SYS}-"
TARGET_CC_ARCH = "${TUNE_CCARGS}"
TARGET_LD_ARCH = "${TUNE_LDARGS}"
TARGET_AS_ARCH = "${TUNE_ASARGS}"

SDKMACHINE ??= "x86_64"
SDK_OS = "${BUILD_OS}"
SDK_VENDOR = "-oesdk"
SDK_SYS = "${SDK_ARCH}${SDK_VENDOR}-${SDK_OS}"
SDK_PREFIX = "${SDK_SYS}-"
SDK_CC_ARCH = "${BUILD_CC_ARCH}"
SDKPKGSUFFIX = "nativesdk"
SDK_PACKAGE_ARCHS = "all any noarch ${SDK_ARCH}-${SDKPKGSUFFIX}"
SDK_LD_ARCH = "${BUILD_LD_ARCH}"
SDK_AS_ARCH = "${BUILD_AS_ARCH}"

TUNE_PKGARCH ??= ""
PACKAGE_ARCH ??= "${TUNE_PKGARCH}"
MACHINE_ARCH = "${@[d.getVar('TUNE_PKGARCH'), d.getVar('MACHINE')][bool(d.getVar('MACHINE'))].replace('-', '_')}"
PACKAGE_EXTRA_ARCHS ??= "${PACKAGE_EXTRA_ARCHS_tune-${DEFAULTTUNE}}"
PACKAGE_ARCHS = "all any noarch ${PACKAGE_EXTRA_ARCHS} ${MACHINE_ARCH}"
# MACHINE_ARCH shouldn't be included here as a variable dependency
# since machine specific packages are handled using multimachine
PACKAGE_ARCHS[vardepsexclude] = "MACHINE_ARCH"

MULTIMACH_TARGET_SYS = "${PACKAGE_ARCH}${TARGET_VENDOR}-${TARGET_OS}"

##################################################################
# Date/time variables.
##################################################################

DATE := "${@time.strftime('%Y%m%d',time.gmtime())}"
TIME := "${@time.strftime('%H%M%S',time.gmtime())}"
DATETIME = "${DATE}${TIME}"

##################################################################
# Openembedded Software Prerequisites.
##################################################################

# python-native should be here but python relies on building
# its own in staging
ASSUME_PROVIDED = "\
    bzip2-native \
    chrpath-native \
    file-native \
    findutils-native \
    gawk-native \
    git-native \
    grep-native \
    diffstat-native \
    patch-native \
    libgcc-native \
    hostperl-runtime-native \
    hostpython-runtime-native \
    tar-native \
    virtual/libintl-native \
    virtual/libiconv-native \
    virtual/crypt-native \
    texinfo-native \
    bash-native \
    sed-native \
    wget-native \
    "
# gzip-native should be listed above?

##################################################################
# Package default variables.
##################################################################

PN = "${@bb.parse.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'}"
PV = "${@bb.parse.vars_from_file(d.getVar('FILE', False),d)[1] or '1.0'}"
PR = "${@bb.parse.vars_from_file(d.getVar('FILE', False),d)[2] or 'r0'}"
PE = ""
PF = "${PN}-${EXTENDPE}${PV}-${PR}"
EXTENDPE = "${@['','${PE}_'][int(d.getVar('PE') or 0) > 0]}"
P = "${PN}-${PV}"

PRAUTO = ""
EXTENDPRAUTO = "${@['.${PRAUTO}', ''][not d.getVar('PRAUTO')]}"
PRAUTOINX = "${PF}"

PKGV ?= "${PV}"
PKGR ?= "${PR}${EXTENDPRAUTO}"
PKGE ?= "${@['','${PE}'][int(d.getVar('PE') or 0) > 0]}"
EXTENDPKGEVER = "${@['','${PKGE}:'][d.getVar('PKGE').strip() != '']}"
EXTENDPKGV ?= "${EXTENDPKGEVER}${PKGV}-${PKGR}"

# Base package name
# Automatically derives "foo" from "foo-native", "foo-cross" or "foo-initial"
# otherwise it is the same as PN and P
SPECIAL_PKGSUFFIX = "-native -cross -initial -intermediate -crosssdk -cross-canadian"
BPN = "${@oe.utils.prune_suffix(d.getVar('PN'), d.getVar('SPECIAL_PKGSUFFIX').split(), d)}"
BP = "${BPN}-${PV}"

# Package info.

SECTION = "base"
PRIORITY = "optional"
SUMMARY ?= "${PN} version ${PV}-${PR}"
DESCRIPTION ?= "${SUMMARY}."

# The following two are commented out because they result in a recursive
# definition of the variable in some corner cases.  These are left in
# to illustrate the intended behavior.
#SUMMARY_${PN} ?= "${SUMMARY}"
#DESCRIPTION_${PN} ?= "${DESCRIPTION}"

SUMMARY_${PN}-src ?= "${SUMMARY} - Source files"
DESCRIPTION_${PN}-src ?= "${DESCRIPTION}  \
This package contains sources for debugging purposes."

SUMMARY_${PN}-dbg ?= "${SUMMARY} - Debugging files"
DESCRIPTION_${PN}-dbg ?= "${DESCRIPTION}  \
This package contains ELF symbols and related sources for debugging purposes."

SUMMARY_${PN}-dev ?= "${SUMMARY} - Development files"
DESCRIPTION_${PN}-dev ?= "${DESCRIPTION}  \
This package contains symbolic links, header files, and \
related items necessary for software development."

SUMMARY_${PN}-staticdev ?= "${SUMMARY} - Development files (Static Libraries)"
DESCRIPTION_${PN}-staticdev?= "${DESCRIPTION}  \
This package contains static libraries for software development."

SUMMARY_${PN}-doc ?= "${SUMMARY} - Documentation files"
DESCRIPTION_${PN}-doc ?= "${DESCRIPTION}  \
This package contains documentation."

LICENSE ??= "INVALID"
MAINTAINER = "OE-Core Developers <openembedded-core@lists.openembedded.org>"
HOMEPAGE = ""

# Package dependencies and provides.

# Ensure that -dev packages recommend the corresponding -dev packages of their
# deps, and the same for -dbg.
DEPCHAIN_PRE  = ""
DEPCHAIN_POST = "-dev -dbg"

DEPENDS = ""
RDEPENDS = ""
PROVIDES = ""
PROVIDES_prepend = "${PN} "
RPROVIDES = ""

MULTI_PROVIDER_WHITELIST = "virtual/libintl virtual/libintl-native virtual/nativesdk-libintl virtual/xserver virtual/update-alternatives-native virtual/update-alternatives"

SOLIBS = ".so.*"
SOLIBS_darwin = ".dylib"

SOLIBSDEV = ".so"
# Due to the ordering of PACKAGES and the naming of the dev symlinks on darwin,
# we can't make the symlinks end up in the -dev packages easily at this point. This hack
# at least means builds aren't completely broken and symlinks don't take up much space.
SOLIBSDEV_darwin = ".dylibbroken"

PACKAGE_DEBUG_SPLIT_STYLE ?= "debug-with-srcpkg"

PACKAGE_BEFORE_PN ?= ""
PACKAGES = "${PN}-src ${PN}-dbg ${PN}-staticdev ${PN}-dev ${PN}-doc ${PN}-locale ${PACKAGE_BEFORE_PN} ${PN}"
PACKAGES_DYNAMIC = "^${PN}-locale-.*"
FILES = ""

FILES_${PN} = "${bindir}/* ${sbindir}/* ${libexecdir}/* ${libdir}/lib*${SOLIBS} \
            ${sysconfdir} ${sharedstatedir} ${localstatedir} \
            ${base_bindir}/* ${base_sbindir}/* \
            ${base_libdir}/*${SOLIBS} \
            ${base_prefix}/lib/udev ${prefix}/lib/udev \
            ${base_libdir}/udev ${libdir}/udev \
            ${datadir}/${BPN} ${libdir}/${BPN}/* \
            ${datadir}/pixmaps ${datadir}/applications \
            ${datadir}/idl ${datadir}/omf ${datadir}/sounds \
            ${libdir}/bonobo/servers"

FILES_${PN}-bin = "${bindir}/* ${sbindir}/*"

FILES_${PN}-doc = "${docdir} ${mandir} ${infodir} ${datadir}/gtk-doc \
            ${datadir}/gnome/help"
SECTION_${PN}-doc = "doc"

FILES_SOLIBSDEV ?= "${base_libdir}/lib*${SOLIBSDEV} ${libdir}/lib*${SOLIBSDEV}"
FILES_${PN}-dev = "${includedir} ${FILES_SOLIBSDEV} ${libdir}/*.la \
                ${libdir}/*.o ${libdir}/pkgconfig ${datadir}/pkgconfig \
                ${datadir}/aclocal ${base_libdir}/*.o \
                ${libdir}/${BPN}/*.la ${base_libdir}/*.la \
                ${libdir}/cmake ${datadir}/cmake"
SECTION_${PN}-dev = "devel"
ALLOW_EMPTY_${PN}-dev = "1"
RDEPENDS_${PN}-dev = "${PN} (= ${EXTENDPKGV})"

FILES_${PN}-staticdev = "${libdir}/*.a ${base_libdir}/*.a ${libdir}/${BPN}/*.a"
SECTION_${PN}-staticdev = "devel"
RDEPENDS_${PN}-staticdev = "${PN}-dev (= ${EXTENDPKGV})"

FILES_${PN}-dbg = "/usr/lib/debug /usr/lib/debug-static /usr/src/debug"
SECTION_${PN}-dbg = "devel"
ALLOW_EMPTY_${PN}-dbg = "1"

# The files list for source packages are dynamically set based on
# PACKAGE_DEBUG_SPLIT_STYLE
FILES_${PN}-src = ""
SECTION_${PN}-src = "devel"

FILES_${PN}-locale = "${datadir}/locale"

# File manifest

FILE_DIRNAME = "${@os.path.dirname(d.getVar('FILE', False))}"
# FILESPATH is set in base.bbclass
#FILESPATH = "${FILE_DIRNAME}/${PF}:${FILE_DIRNAME}/${P}:${FILE_DIRNAME}/${PN}:${FILE_DIRNAME}/${BP}:${FILE_DIRNAME}/${BPN}:${FILE_DIRNAME}/files:${FILE_DIRNAME}"
# This default was only used for checking
FILESEXTRAPATHS ?= "__default:"

# The default list of fs-perms files to process.  If the list is empty only
# the builtin definitions will be used.  Builtin definitions included:
#  base_prefix, prefix, exec_prefix, base_bindir, base_sbindir, base_libdir,
#  datadir, sysconfdir, servicedir, sharedstatedir, localstatedir, infodir,
#  mandir, docdir, bindir, sbindir, libexecdir, libdir, includedir and
#  oldincludedir
FILESYSTEM_PERMS_TABLES ?= "${@'files/fs-perms.txt' if oe.types.boolean(d.getVar('VOLATILE_LOG_DIR')) else 'files/fs-perms-persistent-log.txt'}"

##################################################################
# General work and output directories for the build system.
##################################################################

TMPDIR ?= "${TOPDIR}/tmp"
CACHE = "${TMPDIR}/cache${@['', '/' + str(d.getVar('MACHINE'))][bool(d.getVar('MACHINE'))]}${@['', '/' + str(d.getVar('SDKMACHINE'))][bool(d.getVar('SDKMACHINE'))]}"
# The persistent cache should be shared by all builds
PERSISTENT_DIR = "${TOPDIR}/cache"
LOG_DIR = "${TMPDIR}/log"

STAMPS_DIR ?= "${TMPDIR}/stamps"
STAMP = "${STAMPS_DIR}/${MULTIMACH_TARGET_SYS}/${PN}/${EXTENDPE}${PV}-${PR}"
STAMPCLEAN = "${STAMPS_DIR}/${MULTIMACH_TARGET_SYS}/${PN}/*-*"
BASE_WORKDIR ?= "${TMPDIR}/work"
WORKDIR = "${BASE_WORKDIR}/${MULTIMACH_TARGET_SYS}/${PN}/${EXTENDPE}${PV}-${PR}"
T = "${WORKDIR}/temp"
D = "${WORKDIR}/image"
S = "${WORKDIR}/${BP}"
B = "${S}"

STAGING_DIR = "${TMPDIR}/sysroots"
COMPONENTS_DIR = "${STAGING_DIR}-components"
RECIPE_SYSROOT = "${WORKDIR}/recipe-sysroot"
RECIPE_SYSROOT_NATIVE = "${WORKDIR}/recipe-sysroot-native"

STAGING_DIR_NATIVE = "${RECIPE_SYSROOT_NATIVE}"
STAGING_BINDIR_NATIVE = "${STAGING_DIR_NATIVE}${bindir_native}"
STAGING_BINDIR_CROSS = "${STAGING_BINDIR}/crossscripts"
STAGING_BINDIR_TOOLCHAIN = "${STAGING_DIR_NATIVE}${bindir_native}/${TARGET_ARCH}${TARGET_VENDOR}-${TARGET_OS}"
STAGING_LIBDIR_NATIVE = "${STAGING_DIR_NATIVE}${libdir_native}"
STAGING_LIBEXECDIR_NATIVE = "${STAGING_DIR_NATIVE}${libexecdir_native}"
STAGING_BASE_LIBDIR_NATIVE = "${STAGING_DIR_NATIVE}${base_libdir_native}"
STAGING_SBINDIR_NATIVE = "${STAGING_DIR_NATIVE}${sbindir_native}"
STAGING_INCDIR_NATIVE = "${STAGING_DIR_NATIVE}${includedir_native}"
STAGING_ETCDIR_NATIVE = "${STAGING_DIR_NATIVE}${sysconfdir_native}"
STAGING_DATADIR_NATIVE = "${STAGING_DIR_NATIVE}${datadir_native}"

STAGING_DIR_HOST = "${RECIPE_SYSROOT}"
STAGING_BINDIR = "${STAGING_DIR_HOST}${bindir}"
STAGING_LIBDIR = "${STAGING_DIR_HOST}${libdir}"
STAGING_LIBEXECDIR = "${STAGING_DIR_HOST}${libexecdir}"
STAGING_BASELIBDIR = "${STAGING_DIR_HOST}${base_libdir}"
STAGING_INCDIR = "${STAGING_DIR_HOST}${includedir}"
STAGING_DATADIR = "${STAGING_DIR_HOST}${datadir}"
STAGING_EXECPREFIXDIR = "${STAGING_DIR_HOST}${exec_prefix}"
STAGING_LOADER_DIR = "${STAGING_DIR_HOST}/loader"
STAGING_FIRMWARE_DIR = "${STAGING_DIR_HOST}/firmware"

STAGING_DIR_TARGET = "${RECIPE_SYSROOT}"

# Setting DEPLOY_DIR outside of TMPDIR is helpful, when you are using
# packaged staging and/or multimachine.
DEPLOY_DIR ?= "${TMPDIR}/deploy"
DEPLOY_DIR_TAR = "${DEPLOY_DIR}/tar"
DEPLOY_DIR_IPK = "${DEPLOY_DIR}/ipk"
DEPLOY_DIR_RPM = "${DEPLOY_DIR}/rpm"
DEPLOY_DIR_DEB = "${DEPLOY_DIR}/deb"
DEPLOY_DIR_IMAGE ?= "${DEPLOY_DIR}/images/${MACHINE}"
DEPLOY_DIR_TOOLS = "${DEPLOY_DIR}/tools"

PKGDATA_DIR = "${TMPDIR}/pkgdata/${MACHINE}"

##################################################################
# SDK variables.
##################################################################

SDK_NAME_PREFIX ?= "oecore"
SDK_NAME = "${SDK_NAME_PREFIX}-${SDK_ARCH}-${TUNE_PKGARCH}"
SDKPATH = "/usr/local/${SDK_NAME_PREFIX}-${SDK_ARCH}"
SDKPATHNATIVE = "${SDKPATH}/sysroots/${SDK_SYS}"

##################################################################
# Kernel info.
##################################################################

OLDEST_KERNEL = "3.2.0"
OLDEST_KERNEL_aarch64 = "3.14"
OLDEST_KERNEL_nios2 = "3.19"
OLDEST_KERNEL_powerpc64le = "3.10.0"
OLDEST_KERNEL_riscv32 = "5.4"
OLDEST_KERNEL_riscv64 = "4.15"

# SDK_OLDEST_KERNEL can't be set using overrides since there are
# none for the SDK architecture. Best to set it from a machine-sdk
# include file if you need an SDK arch-specific value
SDK_OLDEST_KERNEL = "3.2.0"

# Define where the kernel headers are installed on the target as well as where
# they are staged.
KERNEL_SRC_PATH = "/usr/src/kernel"

STAGING_KERNEL_DIR = "${TMPDIR}/work-shared/${MACHINE}/kernel-source"
STAGING_KERNEL_BUILDDIR = "${TMPDIR}/work-shared/${MACHINE}/kernel-build-artifacts"

##################################################################
# Specific image creation and rootfs population info.
##################################################################

IMAGE_ROOTFS = "${WORKDIR}/rootfs"
IMAGE_BASENAME = "${PN}"
IMAGE_VERSION_SUFFIX = "-${DATETIME}"
IMAGE_VERSION_SUFFIX[vardepsexclude] += "DATETIME"
IMAGE_NAME = "${IMAGE_BASENAME}-${MACHINE}${IMAGE_VERSION_SUFFIX}"
IMAGE_LINK_NAME = "${IMAGE_BASENAME}-${MACHINE}"

# This option allows for a percentage overage of the actual image size rather than a
# fixed extra space, this is space needed for initial startup and basic operations.
IMAGE_OVERHEAD_FACTOR ?= "1.3"
# This option allows for adding additional space in K above and beyond what the
# IMAGE_OVERHEAD_FACTOR might add. This space is for additional packages, user data, ...
# To set a fixed size then overriding IMAGE_ROOTFS_SIZE with the max size one wants
# should do the trick
IMAGE_ROOTFS_EXTRA_SPACE ?= "0"

EXTRA_IMAGEDEPENDS = ""

##################################################################
# Toolchain info.
##################################################################

PATH_prepend = "${COREBASE}/scripts:${STAGING_BINDIR_TOOLCHAIN}:${STAGING_BINDIR_CROSS}:${STAGING_DIR_NATIVE}${sbindir_native}:${STAGING_BINDIR_NATIVE}:${STAGING_DIR_NATIVE}${base_sbindir_native}:${STAGING_DIR_NATIVE}${base_bindir_native}:"
export PATH

##################################################################
# Build utility info.
##################################################################

# Directory where host tools are copied
HOSTTOOLS_DIR = "${TMPDIR}/hosttools"

# Tools needed to run builds with OE-Core
HOSTTOOLS += " \
    [ ar as awk basename bash bzip2 cat chgrp chmod chown chrpath cmp comm cp cpio \
    cpp cut date dd diff diffstat dirname du echo egrep env expand expr false \
    fgrep file find flock g++ gawk gcc getconf getopt git grep gunzip gzip \
    head hostname iconv id install ld ldd ln ls make md5sum mkdir mknod \
    mktemp mv nm objcopy objdump od patch perl pr printf pwd \
    python3 ranlib readelf readlink realpath rm rmdir rpcgen sed seq sh \
    sha1sum sha224sum sha256sum sha384sum sha512sum \
    sleep sort split stat strings strip tail tar tee test touch tr true uname \
    uniq wc wget which xargs \
"

# Tools needed to run testimage runtime image testing
HOSTTOOLS += "${@'ip ping ps scp ssh stty' if (bb.utils.contains_any('IMAGE_CLASSES', 'testimage testsdk', True, False, d) or any(x in (d.getVar("BBINCLUDED") or "") for x in ["testimage.bbclass", "testsdk.bbclass"])) else ''}"

# Link to these if present
HOSTTOOLS_NONFATAL += "aws gcc-ar gpg ld.bfd ld.gold nc pigz sftp socat ssh sudo"

# Temporary add few more detected in bitbake world
HOSTTOOLS_NONFATAL += "join nl size yes zcat"

# Used by bzr fetcher
HOSTTOOLS_NONFATAL += "bzr"

# Used by ssh fetcher
HOSTTOOLS_NONFATAL += "scp"

# Link to git-lfs if present
HOSTTOOLS_NONFATAL += "git-lfs"

CCACHE ??= ""

TOOLCHAIN_OPTIONS = " --sysroot=${STAGING_DIR_TARGET}"

export CC = "${CCACHE}${HOST_PREFIX}gcc ${HOST_CC_ARCH}${TOOLCHAIN_OPTIONS}"
export CXX = "${CCACHE}${HOST_PREFIX}g++ ${HOST_CC_ARCH}${TOOLCHAIN_OPTIONS}"
export FC = "${CCACHE}${HOST_PREFIX}gfortran ${HOST_CC_ARCH}${TOOLCHAIN_OPTIONS}"
export CPP = "${HOST_PREFIX}gcc -E${TOOLCHAIN_OPTIONS} ${HOST_CC_ARCH}"
export LD = "${HOST_PREFIX}ld${TOOLCHAIN_OPTIONS} ${HOST_LD_ARCH}"
export CCLD = "${CC}"
export AR = "${HOST_PREFIX}gcc-ar"
export AS = "${HOST_PREFIX}as ${HOST_AS_ARCH}"
export RANLIB = "${HOST_PREFIX}gcc-ranlib"
export STRIP = "${HOST_PREFIX}strip"
export OBJCOPY = "${HOST_PREFIX}objcopy"
export OBJDUMP = "${HOST_PREFIX}objdump"
export STRINGS = "${HOST_PREFIX}strings"
export NM = "${HOST_PREFIX}nm"
export READELF = "${HOST_PREFIX}readelf"
PYTHON = "${@sys.executable}"

export BUILD_CC = "${CCACHE}${BUILD_PREFIX}gcc ${BUILD_CC_ARCH}"
export BUILD_CXX = "${CCACHE}${BUILD_PREFIX}g++ ${BUILD_CC_ARCH}"
export BUILD_FC = "${CCACHE}${BUILD_PREFIX}gfortran ${BUILD_CC_ARCH}"
export BUILD_CPP = "${BUILD_PREFIX}gcc ${BUILD_CC_ARCH} -E"
export BUILD_LD = "${BUILD_PREFIX}ld ${BUILD_LD_ARCH}"
export BUILD_CCLD = "${BUILD_PREFIX}gcc ${BUILD_CC_ARCH}"
export BUILD_AR = "${BUILD_PREFIX}ar"
export BUILD_AS = "${BUILD_PREFIX}as ${BUILD_AS_ARCH}"
export BUILD_RANLIB = "${BUILD_PREFIX}ranlib"
export BUILD_STRIP = "${BUILD_PREFIX}strip"
export BUILD_NM = "${BUILD_PREFIX}nm"

export MAKE = "make"
EXTRA_OEMAKE = ""
EXTRA_OECONF = ""
export LC_ALL = "en_US.UTF-8"
export TZ = 'UTC'

##################################################################
# Patch handling.
##################################################################
PATCHTOOL = "quilt"
PATCHRESOLVE = "noop"

##################################################################
# Build flags and options.
##################################################################

export BUILD_CPPFLAGS = "-isystem${STAGING_INCDIR_NATIVE}"
BUILDSDK_CPPFLAGS = ""
export CPPFLAGS = "${TARGET_CPPFLAGS}"
TARGET_CPPFLAGS = ""

export BUILD_CFLAGS = "${BUILD_CPPFLAGS} ${BUILD_OPTIMIZATION}"
BUILDSDK_CFLAGS = "${BUILDSDK_CPPFLAGS} ${BUILD_OPTIMIZATION} ${DEBUG_PREFIX_MAP}"
export CFLAGS = "${TARGET_CFLAGS}"
TARGET_CFLAGS = "${TARGET_CPPFLAGS} ${SELECTED_OPTIMIZATION}"

export BUILD_CXXFLAGS = "${BUILD_CFLAGS}"
BUILDSDK_CXXFLAGS = "${BUILDSDK_CFLAGS}"
export CXXFLAGS = "${TARGET_CXXFLAGS}"
TARGET_CXXFLAGS = "${TARGET_CFLAGS}"

export BUILD_LDFLAGS = "-L${STAGING_LIBDIR_NATIVE} \
                        -L${STAGING_BASE_LIBDIR_NATIVE} \
                        -Wl,--enable-new-dtags \
                        -Wl,-rpath-link,${STAGING_LIBDIR_NATIVE} \
                        -Wl,-rpath-link,${STAGING_BASE_LIBDIR_NATIVE} \
                        -Wl,-rpath,${STAGING_LIBDIR_NATIVE} \
                        -Wl,-rpath,${STAGING_BASE_LIBDIR_NATIVE} \
                        -Wl,-O1"

BUILDSDK_LDFLAGS = "-Wl,-O1"

LINKER_HASH_STYLE ??= "gnu"

TARGET_LINK_HASH_STYLE ?= "${@['-Wl,--hash-style=gnu',''][d.getVar('LINKER_HASH_STYLE') != 'gnu']}"

ASNEEDED ?= "-Wl,--as-needed"

export LDFLAGS = "${TARGET_LDFLAGS}"
TARGET_LDFLAGS = "-Wl,-O1 ${TARGET_LINK_HASH_STYLE} ${ASNEEDED}"
# mips does not support GNU hash style therefore we override
LINKER_HASH_STYLE_mipsarch_libc-musl = "sysv"

# Pass parallel make options to the compile task
EXTRA_OEMAKE_prepend_task-compile = "${PARALLEL_MAKE} "
PARALLEL_MAKEINST ??= "${PARALLEL_MAKE}"
# Pass parallel make options to the install task
EXTRA_OEMAKE_prepend_task-install = "${PARALLEL_MAKEINST} "

##################################################################
# Optimization flags.
##################################################################
# Beware: applied last to first
DEBUG_PREFIX_MAP ?= "-fmacro-prefix-map=${WORKDIR}=/usr/src/debug/${PN}/${EXTENDPE}${PV}-${PR} \
                     -fdebug-prefix-map=${WORKDIR}=/usr/src/debug/${PN}/${EXTENDPE}${PV}-${PR} \
                     -fdebug-prefix-map=${STAGING_DIR_HOST}= \
                     -fdebug-prefix-map=${STAGING_DIR_NATIVE}= \
"
DEBUG_FLAGS ?= "-g -feliminate-unused-debug-types ${DEBUG_PREFIX_MAP}"

# Disabled until the option works properly -feliminate-dwarf2-dups
FULL_OPTIMIZATION = "-O2 -pipe ${DEBUG_FLAGS}"
DEBUG_OPTIMIZATION = "-Og ${DEBUG_FLAGS} -pipe"
SELECTED_OPTIMIZATION = "${@d.getVar(oe.utils.vartrue('DEBUG_BUILD', 'DEBUG_OPTIMIZATION', 'FULL_OPTIMIZATION', d))}"
SELECTED_OPTIMIZATION[vardeps] += "FULL_OPTIMIZATION DEBUG_OPTIMIZATION DEBUG_BUILD"
BUILD_OPTIMIZATION = "${@oe.utils.vartrue('DEBUG_BUILD', '-Og -g -feliminate-unused-debug-types', '-O2', d)} -pipe"
BUILD_OPTIMIZATION[vardeps] += "DEBUG_BUILD"

##################################################################
# Settings used by bitbake-layers.
##################################################################
BBLAYERS_LAYERINDEX_URL ??= "https://layers.openembedded.org/layerindex/"
BBLAYERS_FETCH_DIR ??= "${COREBASE}"

##################################################################
# Download locations and utilities.
##################################################################

APACHE_MIRROR = "https://archive.apache.org/dist"
DEBIAN_MIRROR = "http://ftp.debian.org/debian/pool"
GENTOO_MIRROR = "http://distfiles.gentoo.org/distfiles"
GNOME_GIT = "git://gitlab.gnome.org/GNOME"
GNOME_MIRROR = "https://ftp.gnome.org/pub/GNOME/sources"
GNU_MIRROR = "https://ftp.gnu.org/gnu"
GNUPG_MIRROR = "https://www.gnupg.org/ftp/gcrypt"
GPE_MIRROR = "http://gpe.linuxtogo.org/download/source"
KERNELORG_MIRROR = "https://cdn.kernel.org/pub"
SOURCEFORGE_MIRROR = "https://downloads.sourceforge.net"
XLIBS_MIRROR = "https://xlibs.freedesktop.org/release"
XORG_MIRROR = "https://www.x.org/releases/"
SAVANNAH_GNU_MIRROR = "https://download.savannah.gnu.org/releases"
SAVANNAH_NONGNU_MIRROR = "https://download.savannah.nongnu.org/releases"
CPAN_MIRROR = "https://search.cpan.org/CPAN"

SRC_URI[vardepsexclude] += "\
    APACHE_MIRROR \
    CPAN_MIRROR \
    DEBIAN_MIRROR \
    GENTOO_MIRROR \
    GNOME_GIT \
    GNOME_MIRROR \
    GNU_MIRROR \
    GNUPG_MIRROR \
    GPE_MIRROR \
    KERNELORG_MIRROR \
    SAVANNAH_GNU_MIRROR \
    SAVANNAH_NONGNU_MIRROR \
    SOURCEFORGE_MIRROR \
    XLIBS_MIRROR \
    XORG_MIRROR \
"

# You can use the mirror of your country to get faster downloads by putting
#  export DEBIAN_MIRROR = "http://ftp.de.debian.org/debian/pool"
#     into your local.conf

SRCDATE = "${DATE}"
SRCREV ??= "INVALID"
AUTOREV = "${@bb.fetch2.get_autorev(d)}"
AUTOREV[vardepvalue] = "${SRCPV}"
# Set Dynamically in base.bbclass
# SRCPV = "${@bb.fetch2.get_srcrev(d)}"
SRCPV[vardepvalue] = "${SRCPV}"

SRC_URI = ""

# Use pseudo as the fakeroot implementation
PSEUDO_LOCALSTATEDIR ?= "${WORKDIR}/pseudo/"
PSEUDO_PASSWD ?= "${STAGING_DIR_TARGET}:${PSEUDO_SYSROOT}"
PSEUDO_SYSROOT = "${COMPONENTS_DIR}/${BUILD_ARCH}/pseudo-native"
export PSEUDO_DISABLED = "1"
#export PSEUDO_PREFIX = "${STAGING_DIR_NATIVE}${prefix_native}"
#export PSEUDO_BINDIR = "${STAGING_DIR_NATIVE}${bindir_native}"
#export PSEUDO_LIBDIR = "${STAGING_DIR_NATIVE}$PSEUDOBINDIR/../lib/pseudo/lib
FAKEROOTBASEENV = "PSEUDO_BINDIR=${PSEUDO_SYSROOT}${bindir_native} PSEUDO_LIBDIR=${PSEUDO_SYSROOT}${prefix_native}/lib/pseudo/lib PSEUDO_PREFIX=${PSEUDO_SYSROOT}${prefix_native} PSEUDO_DISABLED=1"
FAKEROOTCMD = "${PSEUDO_SYSROOT}${bindir_native}/pseudo"
FAKEROOTENV = "PSEUDO_PREFIX=${PSEUDO_SYSROOT}${prefix_native} PSEUDO_LOCALSTATEDIR=${PSEUDO_LOCALSTATEDIR} PSEUDO_PASSWD=${PSEUDO_PASSWD} PSEUDO_NOSYMLINKEXP=1 PSEUDO_DISABLED=0"
FAKEROOTNOENV = "PSEUDO_UNLOAD=1"
FAKEROOTDIRS = "${PSEUDO_LOCALSTATEDIR}"
PREFERRED_PROVIDER_virtual/fakeroot-native ?= "pseudo-native"

##################################################################
# Not sure about the rest of this yet.
##################################################################

# Pre-build configuration output
BUILDCFG_HEADER = "Build Configuration:"
BUILDCFG_VARS = "BB_VERSION BUILD_SYS NATIVELSBSTRING TARGET_SYS MACHINE DISTRO DISTRO_VERSION TUNE_FEATURES TARGET_FPU"
BUILDCFG_VARS[type] = "list"
BUILDCFG_NEEDEDVARS = "TARGET_ARCH TARGET_OS"
BUILDCFG_NEEDEDVARS[type] = "list"

# Other

export PKG_CONFIG_DIR = "${STAGING_DIR_HOST}${libdir}/pkgconfig"
export PKG_CONFIG_PATH = "${PKG_CONFIG_DIR}:${STAGING_DATADIR}/pkgconfig"
export PKG_CONFIG_LIBDIR = "${PKG_CONFIG_DIR}"
export PKG_CONFIG_SYSROOT_DIR = "${STAGING_DIR_HOST}"
export PKG_CONFIG_DISABLE_UNINSTALLED = "yes"
export PKG_CONFIG_SYSTEM_LIBRARY_PATH = "${base_libdir}:${libdir}"
export PKG_CONFIG_SYSTEM_INCLUDE_PATH = "${includedir}"

# Don't allow git to chdir up past WORKDIR so that it doesn't detect the OE
# repository when building a recipe
export GIT_CEILING_DIRECTORIES = "${WORKDIR}"

###
### Config file processing
###

# An empty distro leads to :: entries in OVERRIDES and FILEOVERRIDES which
# is a bad idea. Setting a dummy value is better than a ton of anonymous python.
DISTRO ??= "nodistro"
DISTRO_NAME ??= "OpenEmbedded"

# Overrides are processed left to right, so the ones that are named later take precedence.
# You generally want them to go from least to most specific. This means that:
# A variable '<foo>_arm' overrides a variable '<foo>' when ${TARGET_ARCH} is arm.
# A variable '<foo>_qemuarm' overrides '<foo>' and overrides '<foo>_arm' when ${MACHINE} is 'qemuarm'.
# If you use combination ie '<foo>_qemuarm_arm', then '<foo>_qemuarm_arm' will override
# '<foo>_qemuarm' and then '<foo>' will be overriden with that value from '<foo>_qemuarm'.
# And finally '<foo>_forcevariable' overrides any standard variable, with the highest priority.
# This works for functions as well, they are really just variables.
#
OVERRIDES = "${TARGET_OS}:${TRANSLATED_TARGET_ARCH}:pn-${PN}:${MACHINEOVERRIDES}:${DISTROOVERRIDES}:${CLASSOVERRIDE}${LIBCOVERRIDE}:forcevariable"
LIBCOVERRIDE ?= ""
CLASSOVERRIDE ?= "class-target"
DISTROOVERRIDES ?= "${@d.getVar('DISTRO') or ''}"
MACHINEOVERRIDES ?= "${MACHINE}"

FILESOVERRIDES = "${TRANSLATED_TARGET_ARCH}:${MACHINEOVERRIDES}:${DISTROOVERRIDES}"

##################################################################
# Include the rest of the config files.
##################################################################

require conf/abi_version.conf
include conf/site.conf
include conf/auto.conf
include conf/local.conf
require conf/multiconfig/${BB_CURRENT_MC}.conf
include conf/machine/${MACHINE}.conf
include conf/machine-sdk/${SDKMACHINE}.conf
include conf/distro/${DISTRO}.conf
include conf/distro/defaultsetup.conf
include conf/documentation.conf
include conf/licenses.conf
require conf/sanity.conf

##################################################################
# Weak variables (usually to retain backwards compatibility)
##################################################################

DL_DIR ?= "${TOPDIR}/downloads"
SSTATE_DIR ?= "${TOPDIR}/sstate-cache"
IMAGE_FSTYPES ?= "tar.gz"
IMAGE_FSTYPES_DEBUGFS ?= "tar.gz"

INITRAMFS_FSTYPES ?= "cpio.gz"
# The maximum size in Kbytes for the generated initramfs image size.
# Usually, it should be less than 1/2 of ram size, or you may fail to
# boot it.
INITRAMFS_MAXSIZE ??= "131072"

DEFAULT_TASK_PROVIDER ?= "packagegroup-base"
MACHINE_TASK_PROVIDER ?= "${DEFAULT_TASK_PROVIDER}"

# The size in Kbytes for the generated image if it is larger than
# the required size (du -ks IMAGE_ROOTFS * IMAGE_OVERHEAD_FACTOR),
# and no effect if less than it.
IMAGE_ROOTFS_SIZE ??= "65536"

# Forcefully set CACHE now so future changes to things like
# MACHINE don't change the path to the cache
CACHE := "${CACHE}"

# Default to setting automatically based on cpu count
BB_NUMBER_THREADS ?= "${@oe.utils.cpu_count()}"

# Default to setting automatically based on cpu count
PARALLEL_MAKE ?= "-j ${@oe.utils.cpu_count()}"

# Default parallelism and resource usage for xz
XZ_MEMLIMIT ?= "50%"
XZ_THREADS ?= "${@oe.utils.cpu_count(at_least=2)}"
XZ_DEFAULTS ?= "--memlimit=${XZ_MEMLIMIT} --threads=${XZ_THREADS}"
XZ_DEFAULTS[vardepsexclude] += "XZ_MEMLIMIT XZ_THREADS"

##################################################################
# Magic Cookie for SANITY CHECK
##################################################################
OES_BITBAKE_CONF = "1"

##################################################################
# Machine properties and packagegroup-base stuff
##################################################################

MACHINE_FEATURES ?= ""
DISTRO_FEATURES ?= ""

DISTRO_EXTRA_RDEPENDS ?= ""
DISTRO_EXTRA_RRECOMMENDS ?= ""
MACHINE_EXTRA_RDEPENDS ?= ""
MACHINE_EXTRA_RRECOMMENDS ?= ""
MACHINE_ESSENTIAL_EXTRA_RDEPENDS ?= ""
MACHINE_ESSENTIAL_EXTRA_RRECOMMENDS ?= ""

EXTRA_IMAGE_FEATURES ??= ""
IMAGE_FEATURES += "${EXTRA_IMAGE_FEATURES}"

# Native distro features (will always be used for -native, even if they
# are not enabled for target)
DISTRO_FEATURES_NATIVE ?= "x11 ipv6 xattr"
DISTRO_FEATURES_NATIVESDK ?= "x11"

# Normally target distro features will not be applied to native builds:
# Native distro features on this list will use the target feature value
DISTRO_FEATURES_FILTER_NATIVE ?= "api-documentation"
DISTRO_FEATURES_FILTER_NATIVESDK ?= "api-documentation"

DISTRO_FEATURES_BACKFILL = "pulseaudio sysvinit gobject-introspection-data ldconfig"
MACHINE_FEATURES_BACKFILL = "rtc qemu-usermode"

COMBINED_FEATURES = "${@oe.utils.set_intersect('DISTRO_FEATURES', 'MACHINE_FEATURES', d)}"
COMBINED_FEATURES[vardeps] += "DISTRO_FEATURES MACHINE_FEATURES"

SERIAL_CONSOLE ??= ""
SERIAL_CONSOLES ??= "${@d.getVar('SERIAL_CONSOLE').replace(' ', ';')}"

NO_RECOMMENDATIONS ??= ""
BAD_RECOMMENDATIONS ?= ""

# Make sure MACHINE isn't exported
# (breaks binutils at least)
MACHINE[unexport] = "1"

# Make sure TARGET_ARCH isn't exported
# (breaks Makefiles using implicit rules, e.g. quilt, as GNU make has this
# in them, undocumented)
TARGET_ARCH[unexport] = "1"

# Make sure DISTRO isn't exported
# (breaks sysvinit at least)
DISTRO[unexport] = "1"

# Make sure SHELL isn't exported
# (can break any number of things if the user's shell isn't POSIX-compliant,
# including the flock command). The user's shell shouldn't affect our builds.
SHELL[unexport] = "1"

# Used by canadian-cross to handle string conversions on TARGET_ARCH where needed
TRANSLATED_TARGET_ARCH ??= "${@d.getVar('TARGET_ARCH').replace("_", "-")}"

# Complete output from bitbake
BB_CONSOLELOG ?= "${LOG_DIR}/cooker/${MACHINE}/${DATETIME}.log"

# Setup our default hash policy
BB_SIGNATURE_HANDLER ?= "OEBasicHash"
BB_HASHBASE_WHITELIST ?= "TMPDIR FILE PATH PWD BB_TASKHASH BBPATH BBSERVER DL_DIR \
    SSTATE_DIR THISDIR FILESEXTRAPATHS FILE_DIRNAME HOME LOGNAME SHELL TERM \
    USER FILESPATH STAGING_DIR_HOST STAGING_DIR_TARGET COREBASE PRSERV_HOST \
    STAMPS_DIR PRSERV_DUMPDIR PRSERV_DUMPFILE PRSERV_LOCKDOWN PARALLEL_MAKE \
    CCACHE_DIR EXTERNAL_TOOLCHAIN CCACHE CCACHE_NOHASHDIR LICENSE_PATH SDKPKGSUFFIX \
    WARN_QA ERROR_QA WORKDIR STAMPCLEAN PKGDATA_DIR BUILD_ARCH SSTATE_PKGARCH \
    BB_WORKERCONTEXT BB_LIMITEDDEPS BB_UNIHASH extend_recipe_sysroot DEPLOY_DIR \
    SSTATE_HASHEQUIV_METHOD SSTATE_HASHEQUIV_REPORT_TASKDATA \
    SSTATE_HASHEQUIV_OWNER CCACHE_TOP_DIR BB_HASHSERVE GIT_CEILING_DIRECTORIES"
BB_HASHCONFIG_WHITELIST ?= "${BB_HASHBASE_WHITELIST} DATE TIME SSH_AGENT_PID \
    SSH_AUTH_SOCK PSEUDO_BUILD BB_ENV_EXTRAWHITE DISABLE_SANITY_CHECKS \
    PARALLEL_MAKE BB_NUMBER_THREADS BB_ORIGENV BB_INVALIDCONF BBINCLUDED \
    GIT_PROXY_COMMAND ALL_PROXY all_proxy NO_PROXY no_proxy FTP_PROXY ftp_proxy \
    HTTP_PROXY http_proxy HTTPS_PROXY https_proxy SOCKS5_USER SOCKS5_PASSWD \
    BB_SETSCENE_ENFORCE BB_CMDLINE BB_SERVER_TIMEOUT"
BB_SIGNATURE_EXCLUDE_FLAGS ?= "doc deps depends \
    lockfiles type vardepsexclude vardeps vardepvalue vardepvalueexclude \
    file-checksums python func task export unexport noexec nostamp dirs cleandirs \
    sstate-lockfile-shared prefuncs postfuncs export_func deptask rdeptask \
    recrdeptask nodeprrecs stamp-extra-info sstate-outputdirs filename lineno \
    progress mcdepends number_threads"

MLPREFIX ??= ""
MULTILIB_VARIANTS ??= ""

# Older versions of bitbake (< 1.42) don't set BB_UNIHASH. For compatibility with these
# versions, set BB_UNIHASH equivalent to BB_TASKHASH if unspecified, which is
# what it would be anyway if the signature generator (e.g. OEEquivHash) doesn't
# support unihashes.
BB_UNIHASH ?= "${BB_TASKHASH}"
