#! /bin/bash

# Define parameters
VERS=2.1.0
SRC="src/tclreadline-${VERS}.tar.gz"
SRCURL="http://downloads.sourceforge.net/project/tclreadline/tclreadline/tclreadline-${VERS}/tclreadline-${VERS}.tar.gz"
BUILDDIR="tclreadline-${VERS}"
export VERS SRC SRCURL BUILDDIR

# Load common functions
source ../common.sh

# Do not build if the "tcl" platform has been requested
not_platforms 'tcl'

# Download source
download_src

# Build package
(
	rm -rf build
	mkdir -p "${PLATDIR}" >/dev/null 2>/dev/null
	mkdir build

	cd build/ || exit 1

	gzip -dc "../${SRC}" | tar -xf -
	cd "${BUILDDIR}" || exit 1

	# The configure script that comes with TclReadLine is out-of-date
	autoreconf -fvi

	# TclReadLine doesn't know it should use stubs, force it.
	CFLAGS="${CFLAGS} -DUSE_TCL_STUBS=1"
	CPPFLAGS="${CPPFLAGS} -DUSE_TCL_STUBS=1"
	LDFLAGS="${LDFLAGS} $(source "${TCLCONFIGDIR}/tclConfig.sh" 2>/dev/null; eval echo "${TCL_STUB_LIB_SPEC}")" 
	export CFLAGS CPPFLAGS LDFLAGS

	bash ./configure --enable-shared --with-tcl="${TCLCONFIGDIR}" --prefix="${PLATDIR}" --libdir="${PLATDIR}" --bindir="${PLATDIR}" ${CONFIGUREEXTRA}

	${MAKE:-make} || exit 1

	${MAKE:-make} install || exit 1

) || exit 1

# Re-write installation to match expectations
(
	cd "${PLATDIR}" || exit 1

	mv lib/tclreadline*/* .
	rm *.a *.la

	rm -rf lib/
	rm -rf include/
	rm -rf share/

	# Delete symlink
	rm -f libtclreadline.so

	# Rename actual file to symlink
	mv libtclreadline-*.so libtclreadline.so

	# Correct Tcl script
	sed 's@ /.*/tclreadline/out/[^/]*/lib@ [file dirname [info script]]@' tclreadlineInit.tcl > tclreadlineInit.tcl.new
	mv tclreadlineInit.tcl.new tclreadlineInit.tcl

	exit 0
) || exit 1


# Create metadata
../create_teapot "${PLATDIR}/teapot.txt" "tclreadline" "${VERS}" "${SRCURL}" "${PLATFORM}" "Tcl 8.4" "Readline package for Tcl"

exit 0
