#! /usr/bin/env bash

# URLs and versions
if [ -z "${LIBFFI_VERS}" ]; then
	LIBFFI_VERS='3.2.1'
	LIBFFI_TARBALL_SHA256='d06ebb8e1d9a22d19e38d63fdb83954253f39bedc5d46232a05645685722ca37'
fi
if [ -z "${LIBFFI_URL}" ]; then
	LIBFFI_URL="http://sourceware.org/pub/libffi/libffi-3.2.1.tar.gz"
fi
LIBFFI_TARBALL="src/libffi-${LIBFFI_VERS}.tar.gz"
LIBFFI_DIR="libffi-${LIBFFI_VERS}"

# Main script
CCNAME="$1"
CCDIR="$2"
PREFIX="$3"
STAGE="$4"

# Clean
if [ "$1" = "distclean" ]; then
        rm -f "${LIBFFI_TARBALL}"

        set -- clean
fi

if [ "$1" = "clean" ]; then
        rm -rf "${LIBFFI_DIR}"
        rm -rf libffi-*-*-*

        exit 0
fi

if [ "${BUILD_CC_INSTALL_LIBFFI}" != '1' ]; then
	exit 0
fi

# Only build in the final stage
if [ "${STAGE}" != "stage2" ]; then
        exit 0
fi

# Load common functions
. 'scripts/common'

# Download source
if [ ! -d "${LIBFFI_DIR}" ]; then
	download "${LIBFFI_URL}" "${LIBFFI_TARBALL}" "${LIBFFI_TARBALL_SHA256}" || exit 1

	gzip -dc "${LIBFFI_TARBALL}" | tar -xf - || rm -f "${LIBFFI_TARBALL}"
fi

cc_save="${CC}"
cxx_save="${CXX}"
for arch in $(multilib); do
	CC="${cc_save} $(multilib --cflags "${arch}")"
	CXX="${cxx_save} $(multilib --cflags "${arch}")"
	arch_host="$(multilib --host "${arch}")"
	arch_libdir="$(multilib --libdir "${arch}")"

	# Do not compile if we already have built it
	if [ -e "${arch_libdir}/libffi.a" -o -e "${arch_libdir}/libffi.so" ]; then
		continue
	fi

	# Inform the user of what we are doing
	echo " * Building libFFI (version ${LIBFFI_VERS}) for ${arch_host}"

	workdir="libffi-${CCNAME}-${arch_host}"
	rm -rf "${workdir}"
	mkdir "${workdir}"
	cd "${workdir}" || exit 1

	"../${LIBFFI_DIR}/configure" --host="${CCNAME}" --prefix="${PREFIX}" --libdir="${arch_libdir}" --enable-shared --enable-static || exit 1

	${MAKE} ${BUILD_CC_MAKE_FLAGS}

	${MAKE} ${BUILD_CC_MAKE_FLAGS} install || exit 1

	cd ..

	rm -rf "${workdir}"

	fix_pkgconfig_file "${arch_libdir}/pkgconfig/libffi.pc"
done

exit 0
