#!/usr/bin/env sh
# This file is part of judy. 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/judy/master/COPYRIGHT. No part of judy-sys, 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 judy. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/judy/master/COPYRIGHT.


# This script exists because doing complex builds of non-Rust code under Cargo is tedious and error-prone
# Not least because Cargo does not display stdout and stderr 'as it goes'
# This script exists to allow testing of the build without running Cargo


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
}

build_under_cargo_fail()
{
	local message="$1"
	
	printf 'build-under-cargo:FAIL:%s\n' "$message" 1>&2
	exit 1
}

build_under_cargo_determineJudyRootFolderPath()
{
	if [ -z "${OUT_DIR+undefined}" ]; then
		judyRootFolderPath="$homeFolder"/bindgen-wrapper.conf.d/temporary/root/usr
	else
		judyRootFolderPath="$OUT_DIR"/root/usr
	fi
		
	if [ ! -d "$judyRootFolderPath" ]; then
		needsCompilation='true'
	fi
}

build_under_cargo_compileIfRequired()
{
	if $needsCompilation; then
		"$homeFolder"/tools/compile-judy 1>&2
	fi
}

# This is extremely brittle, mostly because of bindgen being brittle
build_under_cargo_generatingRustBindingsToJudyIfRquired()
{
	local rebuildBindings='false'
	
	if [ ! -d "$rustBindingsFolderPath" ]; then
		rebuildBindings='true'
	elif ! diff "$copyHeadersToKnownLocationForEmbeddedCCodeInRustIncludeFolderPath" "$judyIncludeFolderPath" 1>/dev/null 2>/dev/null; then
		rebuildBindings='true'
	fi
	
	if $rebuildBindings; then
		rm -rf "$rustBindingsFolderPath" 1>&2
		"$homeFolder"/tools/bindgen-wrapper/bindgen-wrapper 1>&2
	fi
}

build_under_cargo_copyHeadersToKnownLocationForEmbeddedCCodeInRust()
{
	rm -rf "$copyHeadersToKnownLocationForEmbeddedCCodeInRustIncludeFolderPath" 1>&2
	mkdir -m 0700 -p "$copyHeadersToKnownLocationForEmbeddedCCodeInRustIncludeFolderPath" 1>&2
	rsync --quiet --archive "$judyIncludeFolderPath"/ "$copyHeadersToKnownLocationForEmbeddedCCodeInRustIncludeFolderPath"/ 1>&2
}

build_under_cargo_outputCargoKeyValuePairs()
{
	printf 'cargo:rustc-link-lib=static=Judy\n'
	
	printf 'cargo:rustc-link-search=native=%s\n' "$judyLibFolderPath"
	
	# Not used by us, but useful for downstream potentially
	printf 'cargo:root=%s\n' "$judyRootFolderPath"
	printf 'cargo:include=%s\n' "$judyIncludeFolderPath"
	printf 'cargo:libdir=%s\n' "$judyLibFolderPath"
	
	printf 'cargo:rerun-if-changed=src/build.rs\n'

	printf 'cargo:rerun-if-changed=compile-judy.conf.d/config\n'

	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/header-overrides\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/configuration.sh\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/constant.mapping\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/constant.types\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/function.mapping\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/preamble.rs\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/static.mapping\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/whitelist-function.regex\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/whitelist-type.regex\n'
	printf 'cargo:rerun-if-changed=bindgen-wrapper.conf.d/whitelist-var.regex\n'
	
	printf 'cargo:rerun-if-changed=tools/bindgen-wrapper/bindgen-wrapper\n'
	printf 'cargo:rerun-if-changed=tools/build-under-cargo\n'
	printf 'cargo:rerun-if-changed=tools/compile-judy\n'
	printf 'cargo:rerun-if-changed=tools/recreate-bindings\n'
}

build_under_cargo_steps()
{	
	local judyRootFolderPath
	local needsCompilation='false'
	build_under_cargo_determineJudyRootFolderPath
	
	local judyLibFolderPath="$judyRootFolderPath"/lib
	local judyIncludeFolderPath="$judyRootFolderPath"/include
	local srcFolderPath="$homeFolder"/src
	local rustBindingsFolderPath="$srcFolderPath"/bindgen
	local copyHeadersToKnownLocationForEmbeddedCCodeInRustIncludeFolderPath="$srcFolderPath"/include
	
	build_under_cargo_compileIfRequired
	
	build_under_cargo_copyHeadersToKnownLocationForEmbeddedCCodeInRust
	
	build_under_cargo_generatingRustBindingsToJudyIfRquired

	build_under_cargo_outputCargoKeyValuePairs
}

build_under_cargo_main()
{
	case "$#" in
		
		0)
			:
		;;
		
		1)
			case "$1" in
				
				-h|--help)
					printf './build\n'
					printf './build -h|--help\n'
					exit 0
				;;
				
				*)
					build_under_cargo_fail "Does not take any arguments"
				;;
				
			esac
		;;
		
		*)
			build_under_cargo_fail "Does not take any arguments"
		;;
		
	esac
	
	local programPath="$(_program_path_find)"
	cd "$programPath"/.. 1>/dev/null 2>/dev/null
		local homeFolder="$(pwd)"
	cd - 1>/dev/null 2>/dev/null
		
	build_under_cargo_steps
}

build_under_cargo_main "$@"
