#! /bin/bash

if [ ! -x "../platform" ]; then
	echo "No platform script found, aborting." >&2

	exit 1
fi

VERS=1.6
SRC="src/tls${VERS}-src.tar.gz"
SRCURL="http://sourceforge.net/projects/tls/files/tls/${VERS}/tls${VERS}-src.tar.gz/download"
BUILDDIR="tls${VERS}"
WORKDIR="${TMPDIR:-/tmp}/tls-$$${RANDOM}${RANDOM}${RANDOM}"
PLATFORM="$(../platform)"
PLATDIR="out/${PLATFORM}"

export VERS SRC SRCURL BUILDDIR WORKDIR PLATFORM PLATDIR

if [ ! -f "${SRC}" ]; then
	mkdir src >/dev/null 2>/dev/null

	wget -O "${SRC}" "${SRCURL}" || exit 1
fi

(
	rm -rf build
	mkdir build
	cd build/ || exit 1

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

	for chkssldir in $(pkg-config openssl --cflags | sed 's@ *-I *@|@g' | tr '|' "\n" | grep '^/'); do
		if [ -f "${chkssldir}/openssl/opensslv.h" -o -f "${chkssldir}/opensslv.h" ]; then
			SSLDIR=$(echo "${chkssldir}" | sed 's@/[^/]*/*$@@')
		fi
	done
	if [ -z "${SSLDIR}" ]; then
		SSLDIR="/usr"
	fi

	./configure --enable-shared --with-tcl="${TCLCONFIGDIR}" --with-ssl-dir="${SSLDIR}"
	${MAKE:-make} || exit 1
) || exit 1

(
	mkdir -p "${PLATDIR}" >/dev/null 2>/dev/null

	cp "build/${BUILDDIR}/libtls1.6.so" "${PLATDIR}/"
	cp "build/${BUILDDIR}/pkgIndex.tcl" "${PLATDIR}/"
	cp "build/${BUILDDIR}/tls.tcl" "${PLATDIR}/"

	../create_teapot "${PLATDIR}/teapot.txt" "tls" "${VERS}" "${SRCURL}" "${PLATFORM}" "Tcl 8.4" "SSL TLS Secure Sockets"
) || exit 1

exit 0
