#! /bin/bash

# Define parameters
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}"
PATCHDIR="$(pwd)/patches"
export VERS SRC SRCURL BUILDDIR PATCHDIR

# Load common functions
source ../common.sh

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

# Download source
download_src

# Extract source
extract_src

# Apply appropriate patches
apply_patches

(
	cd "build/${BUILDDIR}" || exit 1

	if [ -z "${SSLDIR}" ]; then
		(
			case "${PLATFORM}" in
				solaris*-ix86)
					opensslplatform='solaris-x86-gcc'
					;;
				solaris*-x86_64)
					opensslplatform='solaris64-x86_64-gcc'
					;;
				solaris*-sparc)
					opensslplatform='solaris-sparcv9-gcc'
					;;
				solaris*-sparc64)
					opensslplatform='solaris64-sparcv9-gcc'
					;;
			esac

			if [ -z "${opensslplatform}" ]; then
				exit 0
			fi

			wget 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz'
			gzip -dc openssl-1.0.1g.tar.gz | tar -xf -
			cd openssl-1.0.1g

			./Configure no-shared --prefix=$(pwd)/INST "${opensslplatform}"

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

		for chkssldir in "$(pwd)/openssl-1.0.1g/INST"; do
			if [ -d "${chkssldir}/lib" ]; then
				SSLDIR="${chkssldir}"
			fi
		done
	fi

	if [ -z "${SSLDIR}" ]; then
		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
	fi

	if [ -z "${SSLDIR}" ]; then
		SSLDIR="/usr"
	fi

	bash ./configure --enable-shared --with-tcl="${TCLCONFIGDIR}" --with-ssl-dir="${SSLDIR}" ${CONFIGUREEXTRA}
	${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
