#!/usr/bin/env sh
# This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
# Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.


set -e
set -u
set -f


_program_path_find()
{
    if [ "${_program_fattening_program_path+set}" = 'set' ]; then
        printf '%s\n' "$_program_fattening_program_path"

    elif [ "${0%/*}" = "$0" ]; then

        # We've been invoked by the interpreter as, say, bash program
        if [ -r "$0" ]; then
            pwd -P
        # Clutching at straws; probably run via a download, anonymous script, etc, weird execve, etc
        else
            printf '\n'
        fi

    else

        # We've been invoked with a relative or absolute path (also when invoked via PATH in a shell)

        _program_path_find_parentPath()
        {
            parentPath="${scriptPath%/*}"
            if [ -z "$parentPath" ]; then
                parentPath='/'
            fi
            cd "$parentPath" 1>/dev/null
        }

        # pdksh / mksh have problems with unsetting a variable that was never set...
        if [ "${CDPATH+set}" = 'set' ]; then
            unset CDPATH
        fi

        if command -v realpath 1>/dev/null 2>/dev/null; then
            (
                scriptPath="$(realpath "$0")"

                _program_path_find_parentPath
                pwd -P
            )
        elif command -v readlink 1>/dev/null 2>/dev/null; then
            (
                scriptPath="$0"

                while [ -L "$scriptPath" ]
                do
                    _program_path_find_parentPath
                    scriptPath="$(readlink "$scriptPath")"
                done

                _program_path_find_parentPath
                pwd -P
            )
        else
            # This approach will fail in corner cases where the script itself is a symlink in a path not parallel with the concrete script
            (
                scriptPath="$0"

                _program_path_find_parentPath
                pwd -P
            )
        fi

    fi
}

compile_fail()
{
	local message="$1"

	printf 'compile-rdma-core:FAIL:%s\n' "$message" 1>&2
	exit 1
}

compile_ensureRequiredBinariesArePresent()
{
	local reason="$1"
	shift 1

	local binary
	local missing=false
	for binary in "$@"
	do
		if ! command -v "$binary" 1>/dev/null 2>/dev/null; then
			printf 'compile-rdma-core:%s\n' "The binary '$binary' needs to be in the path" 1>&2
			missing=true
		fi
	done

	if $missing; then
		compile_fail "Please make sure that the missing binaries are installed because '$reason'"
	fi
}

_compile_prepareForMacOSX_brewInstall()
{
	compile_ensureRequiredBinariesArePresent brew

	local packageName="$1"
	if ! brew ls --versions "$packageName" 1>/dev/null 2>/dev/null; then
		brew install "$packageName" 1>&2
	fi
}

compile_prepareForMacOSX()
{
	_compile_prepareForMacOSX_brewInstall gnu-sed
	_compile_prepareForMacOSX_brewInstall make
	_compile_prepareForMacOSX_brewInstall libelf
	_compile_prepareForMacOSX_brewInstall coreutils
	_compile_prepareForMacOSX_brewInstall FiloSottile/musl-cross/musl-cross
	
	_compile_prepareForMacOSX_brewInstall autoconf@2.69
	_compile_prepareForMacOSX_brewInstall automake
}

compile_parseCommandLine()
{
	case "$#" in

		0)
			:
		;;

		1)
			case "$1" in

				-h|--help)
					printf './compile-rdma-core\n'
					printf './compile-rdma-core -h|--help\n'
					printf 'Pass the environment variable NUM_JOBS to control the number of make jobs\n'
					exit 0
				;;

				*)
					compile_fail "Does not take any arguments"
				;;

			esac
		;;

		*)
			compile_fail "Does not take any arguments"
		;;

	esac
}

compile_findFolderPaths()
{
	programFolderPath="$(_program_path_find)"

	cd "$programFolderPath"/.. 1>/dev/null 2>/dev/null
		homeFolderPath="$(pwd)"
	cd - 1>/dev/null 2>/dev/null

	if [ -z "${CARGO_MANIFEST_DIR+is_unset}" ]; then
		export CARGO_MANIFEST_DIR="$homeFolderPath"
		printf 'build-under-cargo:%s\n' "Whilst this script (compile) is designed to be run under cargo, it can run independently. We're setting CARGO_MANIFEST_DIR to '$CARGO_MANIFEST_DIR'" 1>&2
	else
		:
	fi

	configurationFolderPath="$CARGO_MANIFEST_DIR"/compile.conf.d
	bindgenWrapperConfDFolderPath="$CARGO_MANIFEST_DIR"/bindgen-wrapper.conf.d

	if [ -z "${OUT_DIR+is_unset}" ]; then
		export OUT_DIR="$bindgenWrapperConfDFolderPath"/temporary
		printf 'build-under-cargo:%s\n' "Whilst this script (compile) is designed to be run under cargo, it can run independently. We're setting OUT_DIR to '$OUT_DIR'" 1>&2
	else
		:
	fi
}

compile_createTemporaryFolder()
{
	temporaryFolderPath="$OUT_DIR"/root
	rm -rf "$temporaryFolderPath"
	mkdir -m 0700 -p "$temporaryFolderPath"/
}

compile_createTemporaryBinariesPath()
{
	rm -rf "$additionalPath"
	mkdir -m 0700 -p "$additionalPath"
	export PATH="$additionalPath":"$PATH"
}

compile_platformSpecificPreparation()
{
	compile_ensureRequiredBinariesArePresent uname
	platform="$(uname)"

	if [ -z "${NUM_JOBS+undefined}" ]; then
		numberOfMakeJobs=0
	else
		numberOfMakeJobs="$NUM_JOBS"
	fi

	case "$platform" in

		Darwin)
			compile_prepareForMacOSX

			compile_ensureRequiredBinariesArePresent brew

			export PATH="$(brew --prefix coreutils)"/libexec/gnubin:"$(brew --prefix gnu-sed)"/libexec/gnubin:"$PATH"

			muslIncludeFolderPath="$(brew --prefix musl-cross)"/libexec/x86_64-linux-musl/include
			targetSysRootFolderPath="$(brew --prefix musl-cross)"/libexec/"$configureHost"

			if [ $numberOfMakeJobs -eq 0 ]; then
				compile_ensureRequiredBinariesArePresent sysctl
				numberOfMakeJobs="$(sysctl -n hw.ncpu)"
			fi
		;;

		Linux)
			compile_ensureRequiredBinariesArePresent make sed x86_64-linux-musl-gcc x86_64-linux-musl-ar rm mkdir rsync cat
			
			muslIncludeFolderPath='/usr/include'
			targetSysRootFolderPath='/usr'

			if [ $numberOfMakeJobs -eq 0 ]; then
				compile_ensureRequiredBinariesArePresent grep
				numberOfMakeJobs="$(grep -c '^processor' /proc/cpuinfo)"
			fi
		;;

		*)
			compile_fail "Only Darwin (Mac OS X) and Linux (specifically, Alpine Linux) are supported at this time"
		;;

	esac
}

compile_makeCopyToAlter()
{
	rsync --archive --quiet --exclude=.git "$CARGO_MANIFEST_DIR"/lib/rdma-core/ "$temporaryFolderPath"/
}

compile_patch()
{
	cd "$temporaryFolderPath" 1>/dev/null 2>/dev/null
		diff -r -U 3 . "$configurationFolderPath"/patches/ | LC_ALL=C grep -v '^Only in' | patch -p1 -d "$temporaryFolderPath"
	cd - 1>/dev/null 2>/dev/null
}

compile_prepareCMakeToolChainFile()
{
	CMAKE_TOOLCHAIN_FILE="$temporaryFolderPath"/toolchain.cmake
	cat >"$CMAKE_TOOLCHAIN_FILE" <<-EOF
		SET(CMAKE_SYSTEM_NAME Linux)
		SET(CMAKE_SYSTEM_VERSION 1)
		SET(CMAKE_C_COMPILER ${compilerPrefix}cc)
		SET(CMAKE_CXX_COMPILER ${compilerPrefix}c++)
		SET(CMAKE_FIND_ROOT_PATH ${targetSysRootFolderPath})
		SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
		SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
		SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

		SET(CMAKE_C_FLAGS_DEBUG "-Werror")
		SET(CMAKE_C_FLAGS_MINSIZEREL "-Werror")
		SET(CMAKE_C_FLAGS_RELWITHDEBINFO "-Werror")
		SET(CMAKE_C_FLAGS_RELEASE "-Werror")
		SET(CMAKE_CXX_FLAGS_DEBUG "-Werror")
		SET(CMAKE_CXX_FLAGS_MINSIZEREL "-Werror")
		SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-Werror")
		SET(CMAKE_CXX_FLAGS_RELEASE "-Werror")
		
		# These, despite their names, are specific to the rdma-core build system.
		SET(CMAKE_C_FLAGS_DEBUG_INIT "-Werror")
		SET(CMAKE_C_FLAGS_MINSIZEREL_INIT "-Werror")
		SET(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-Werror")
		SET(CMAKE_C_FLAGS_RELEASE_INIT "-Werror")
		SET(CMAKE_CXX_FLAGS_DEBUG_INIT "-Werror")
		SET(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Werror")
		SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-Werror")
		SET(CMAKE_CXX_FLAGS_RELEASE_INIT "-Werror")
	EOF
}

compile_build()
{
	local buildFolderPath="$temporaryFolderPath"/build
	mkdir -m 0700 "$buildFolderPath"
	
	local destDirFolderPath="$temporaryFolderPath"/DESTDIR
	mkdir -m 0700 "$destDirFolderPath"
	
	cd "$buildFolderPath" 1>/dev/null 2>/dev/null
		
		# Removes need for libnl
		cmake \
			-DCMAKE_TOOLCHAIN_FILE="$CMAKE_TOOLCHAIN_FILE" \
			-DCMAKE_BUILD_TYPE=Release \
			-DCMAKE_INSTALL_PREFIX='/usr' \
			-DIN_PLACE=0 \
			-DENABLE_STATIC=1 \
			-DENABLE_VALGRIND=0 \
			-DENABLE_RESOLVE_NEIGH=0 \
			-DNO_COMPAT_SYMS=1 \
			..
		make -j "$numberOfMakeJobs" DESTDIR="$destDirFolderPath" install
		
	cd - 1>/dev/null 2>/dev/null
}

compile_now()
{
	local CMAKE_TOOLCHAIN_FILE
	compile_prepareCMakeToolChainFile
	
	compile_build
}

compile_main()
{
	local configureHost='x86_64-linux-musl'
	local compilerPrefix="${configureHost}"-
	
	compile_parseCommandLine "$@"
	
	local programFolderPath
	local homeFolderPath
	local configurationFolderPath
	compile_findFolderPaths

	local temporaryFolderPath
	compile_createTemporaryFolder
	
	local additionalPath="$temporaryFolderPath"/PATH
	compile_createTemporaryBinariesPath

	local platform
	local muslIncludeFolderPath
	local targetSysRootFolderPath
	local numberOfMakeJobs
	compile_platformSpecificPreparation
	
	compile_makeCopyToAlter
	
	compile_patch
	
	compile_now
	
	printf '\n\n\n\nCOMPILE FINISHED\n\n\n' 1>&2
}

compile_main "$@"
