#! /usr/bin/env bash

bashArrayToJSON() (
	args=("$@")

	jq -M -r -n -c --args '$ARGS.positional' --args -- "${args[@]}"
)

bashStringToJSON() (
	string="$1"

	eval "tmpArray=($string)"
	bashArrayToJSON "${tmpArray[@]}"
)

# Perform common build options
. ./build-common.sh

# Compile using the same options as Tcl
if [ -z "${TCLCONFIGSH}" ]; then
	TCLCONFIGSH="$(find /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64 /lib /lib64 -name tclConfig.sh -print -quit)"
fi

. "${TCLCONFIGSH}"

echo "${TCL_CC} -ggdb3 -fPIC -DPIC -Wall -DUSE_TCL_STUBS=1 ${TCL_DEFS} ${TCL_INCLUDE_SPEC} -shared -rdynamic -o tuapi.so tuapi.c ${TCL_STUB_LIB_SPEC}"

cat << _EOF_ > compile_commands.json.new
[
	{
		"directory": "$(pwd)",
		"file": "tuapi.c",
		"arguments": [
			"$(echo "${TCL_CC}" | sed 's@ @", "@g')",
			"-ggdb3",
			"-fPIC",
			"-DPIC",
			"-Wall",
			"-DUSE_TCL_STUBS=1",
			$(bashStringToJSON "${TCL_DEFS}" | sed 's@^\[@@;s@\]$@@'),
			$(bashStringToJSON "${TCL_INCLUDE_SPEC}" | sed 's@^\[@@;s@\]$@@'),
			"-shared",
			"-rdynamic",
			"-o",
			"tuapi.so",
			"tuapi.c"
		]
	}
]
_EOF_

eval ${TCL_CC} -ggdb3 -fPIC -DPIC -Wall -DUSE_TCL_STUBS=1 ${TCL_DEFS} ${TCL_INCLUDE_SPEC} -shared -rdynamic -o tuapi.so tuapi.c ${TCL_STUB_LIB_SPEC} || exit 1
mv compile_commands.json.new compile_commands.json

echo 'package ifneeded tuapi '"${tuapi_version}"' [list load [file join $dir tuapi.so]]' > pkgIndex.tcl
