#! /usr/bin/env bash

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

# URLs and versions
LIBFFI_VERS='3.1'
LIBFFI_VERS_SHORT="$(echo "${LIBFFI_VERS}" | cut -f 1-2 -d '.')"
LIBFFI_URL="http://pkgs.fedoraproject.org/repo/pkgs/libffi/libffi-${LIBFFI_VERS}.tar.gz/f5898b29bbfd70502831a212d9249d10/libffi-${LIBFFI_VERS}.tar.gz"
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

# 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}" || 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}

	${MAKE} install || exit 1

	cd ..

	rm -rf "${workdir}"

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

exit 0
