#! /bin/bash

function setup_tcl85 () {
	source "${PROJROOTDIR}/platform.magic.env-8.5" 2>/dev/null
}

function setup_tcl84 () {
	source "${PROJROOTDIR}/platform.magic.env-8.4" 2>/dev/null
}

function not_platforms () {
	local platform

	for platform in "$@"; do
		if [ "${PLATFORM}" = "${platform}" ]; then
			rm -rf out

			exit 0
		fi
	done
}

function only_platforms () {
	local platform

	for platform in "$@"; do
		if [ "${PLATFORM}" = "${platform}" ]; then
			return 0
		fi
	done

	rm -rf out

	exit 0
}

function only_platforms_regexp () {
	local platform_re

	for platform_re in "$@"; do
		if echo "${PLATFORM}" | grep -- "${platform_re}" >/dev/null; then
			return 0
		fi
	done

	rm -rf out

	exit 0
}

function download () {
	local url file

	file="$1"
	url="$2"

	if [ -s "${file}" ]; then
		return 0
	fi

	rm -f "${file}.tmp" "${file}"

	if echo "${url}" | grep '^https://' >/dev/null; then
		wget --ca-certificate='../certs.pem' -O "${file}.tmp" "${url}" || return 1
	else
		wget -O "${file}.tmp" "${url}" || return 1
	fi

	mv "${file}.tmp" "${file}"
}

function download_src () {
	if [ ! -f "${SRC}" -a -n "${SRC}" -a -n "${SRCURL}" ]; then
		mkdir -p "$(dirname "${SRC}")" >/dev/null 2>/dev/null

		download "${SRC}" "${SRCURL}" || exit 1
	fi
}

function extract_src () {
	rm -rf build
	mkdir build

	(
		cd build/ || exit 1

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

function apply_patches () {
	local patchroot patchdir patchfiles patchfile idx

	patchroot="$(pwd)/patches"

	for patchdir in "${patchroot}/all" "${patchroot}/${VERS}"; do
		unset patchfiles

		if [ -f "${patchdir}/series" ]; then
			idx=0
			for patchfile in $(cat "${patchdir}/series"); do
				patchfiles[${idx}]="${patchdir}/${patchfile}"
				idx=$[${idx} + 1]
			done
		else
			patchfiles=("${patchdir}"/*.diff)
		fi

		for patchfile in "${patchfiles[@]}"; do
			if [ ! -f "${patchfile}" ]; then
				continue
			fi

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

				echo "* Applying patch \"${patchfile}\""
				"${PATCH:-patch}" -p1 < "${patchfile}"
			)
		done
	done
}

WORKDIR="${TMPDIR:-/tmp}/tcl-buildpkgs-$$${RANDOM}${RANDOM}${RANDOM}"
PLATDIR="$(pwd)/out/${VERS}/${PLATFORM}"
BUILDSYSROOT="$(cd ../; pwd)"
export WORKDIR PLATDIR BUILDSYSROOT

setup_tcl84
