#! /usr/bin/env bash

# f24353d02d90f97c72b6977f3a8a05006ad06120

ourScript="$(which "$0")"
if ! head -3 "${ourScript}" 2>/dev/null | grep f24353d02d90f97c72b6977f3a8a05006ad06120 >/dev/null; then
	echo "error: Unable to find ourselves" >&2

	exit 1
fi

cd "$(dirname "${ourScript}")" || exit 1

patchDir="$(pwd)/patches"

if [ -z "${NACL_SDK_ROOT}" ]; then
	echo "error: Please set NACL_SDK_ROOT to the path of the current NaCl SDK target" >&2

	exit 1
fi

if [ ! -d "${NACL_SDK_ROOT}/toolchain" ]; then
	echo "error: Invalid NACL_SDK_ROOT, not found: ${NACL_SDK_ROOT}/toolchain" >&2

	exit 1
fi

# Setup cross-compiler toolchain
## Set path to include the tools
PATH="${PATH}:${NACL_SDK_ROOT}/toolchain/linux_pnacl/bin"
export PATH

## Set variables needed by projects
HOST_CC="$(which "${CC:-cc}")"
BUILD_CC="${HOST_CC}"
CC_FOR_BUILD="${HOST_CC}"
AR=pnacl-ar
AS=pnacl-as
LD=pnacl-ld
CC=pnacl-clang
CXX=pnacl-clang++
RANLIB=pnacl-ranlib
STRIP=pnacl-strip
OBJCOPY=pnacl-objcopy
export HOST_CC BUILD_CC CC_FOR_BUILD AR AS LD CC CXX RANLIB STRIP OBJCOPY

## Set some CFLAGS that the compiler fails to internally set
CFLAGS="-I${NACL_SDK_ROOT}/include"
CXXFLAGS="${CFLAGS}"
CPPFLAGS="${CFLAGS}"
export CFLAGS CXXFLAGS CPPFLAGS

# Function to download files from the interwebs and verify them
function download() {
	local url file hash
	local hashMethod
	local chkHash

	url="$1"
	file="$2"
	hash="$3"

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

	mkdir -p "$(dirname "${file}")"

	hashMethod='sha256'

	rm -f "${file}.new"
	wget --header "X-Cache-URL: ${url}" -O "${file}.new" "http://hashcache.rkeene.org/${hashMethod}/${hash}" || \
		wget -O "${file}.new" "${url}" || \
		return 1

	chkHash="$(openssl "${hashMethod}" "${file}.new" | sed 's@.*= *@@')"

	if [ "${chkHash}" != "${hash}" -a "${hash}" != '-' ]; then
		echo "error: Checksum mismatch: Got: ${chkHash}; Expected: ${hash}" >&2

		return 1
	fi

	mv "${file}.new" "${file}"

	return 0
}

# Extract an archive into a directory, stripping the top-level directory
# if that is all that it contains
function extract() {
	local file directory

	file="$1"
	directory="$2"

	if [ ! -f "${file}" ]; then
		echo "error: Unable to extract \"${file}\"" >&2

		return 1
	fi

	rm -rf "${directory}"

	mkdir -p "${directory}" || return 1
	(
		cd "${directory}" || exit 1

		case "${file}" in
			*.tar.bz2|*.bz2)
				bzip2 -dc | tar -xf - || exit 1
				;;
			*.tar.gz|*.tgz)
				gzip -dc | tar -xf - || exit 1
				;;
			*.tar.xz|*.txz)
				xz -dc | tar -xf - || exit 1
				;;
			*.zip)
				cat > x.zip || exit 1
				unzip x.zip || exit 1
				rm -f x.zip
				;;
			*)
				echo "error: Don't know what to do with \"${file}\"" >&2

				exit 1
				;;
		esac

		if [ -d "$(echo *)" ]; then
			mv */* . >/dev/null 2>/dev/null
		fi
	) < "${file}" || return 1

	return 0
}

# User-overridable "make"
function make() {
	"${MAKE:-$(which make)}" "$@"
}

# Build "zlib"
function buildZlib() {
	local version url pkg sha256 configure_extra
	local archive workdir

	pkg='zlib'
	version='1.2.8'
	url="http://zlib.net/zlib-${version}.tar.gz"
	sha256='36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d'

	archive="archive/${pkg}-${version}.tar.gz"
	workdir="workdir-${RANDOM}${RANDOM}${RANDOM}${RANDOM}.build"

	download "${url}" "${archive}" "${sha256}" || return 1
	extract "${archive}" "${workdir}" || return 1

	(
		cd "${workdir}" || exit 1

		./configure --prefix=/ --libdir=/lib --static || exit 1
		make || exit 1
		make DESTDIR="${instdir}" install || exit 1
	) || return 1

	rm -rf "${workdir}"

	return 0
}

# Build the libpcsc we need
function buildPCSC() {
	local version url pkg sha256 configure_extra
	local archive workdir

	pkg='nacl-libpcsc'
	version='a72d1992e9e7d70c885d3b34f9b75317fa8671ef'
	url="https://chiselapp.com/user/rkeene/repository/nacl-libpcsc/tarball/nacl-libpcsc-${version}.tar.gz?uuid=${version}"
	sha256='-'

	archive="archive/${pkg}-${version}.tar.gz"
	workdir="workdir-${RANDOM}${RANDOM}${RANDOM}${RANDOM}.build"

	download "${url}" "${archive}" "${sha256}" || return 1
	extract "${archive}" "${workdir}" || return 1

	(
		cd "${workdir}" || exit 1

		if [ ! -d pcsc/src ]; then
			./build/assemble-source-from-google.sh || exit 1
		fi
	) || return 1

	make -C "${workdir}" prefix="${instdir}" install || return 1

	rm -rf "${workdir}"

	return 0
}

# Build our CACKey
function buildCACKey() {
	local platform
	local file copied
	local targets

	buildZlib || return 1
	buildPCSC || return 1

	(
		cd ../.. || exit 1

		make distclean

		./configure --host=nacl --with-pcsc-headers="${instdir}/include/PCSC" --with-pcsc-libs="-lpcsc" cackey_cv_pcsc_works=okay --disable-dod-certs CFLAGS='-g3 -ggdb3 -Wall' || exit 1
		make || exit 1
	) || return 1

	mkdir -p "${instdir}/lib"
	cp ../../libcackey.a ../../libcackey_g.a "${instdir}/lib" || return 1

	return 0
}

instdir="workdir-${RANDOM}${RANDOM}${RANDOM}${RANDOM}.inst"
rm -rf "${instdir}"
mkdir "${instdir}" || exit 1
instdir="$(cd "${instdir}" && pwd)" || exit 1

CFLAGS="${CFLAGS} -I${instdir}/include"
CPPFLAGS="${CPPFLAGS} -I${instdir}/include"
CXXFLAGS="${CXXFLAGS} -I${instdir}/include"
LDFLAGS="${LDFLAGS} -L${instdir}/lib"
export CFLAGS CPPFLAGS CXXFLAGS LDFLAGS

buildCACKey || exit 1

exit 0
