#! /usr/bin/env bash

# URLs and versions
if [ -z "${ZLIB_VERS}" ]; then
	ZLIB_VERS='1.2.11'
	ZLIB_TARBALL_SHA256="c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1"
fi
if [ -z "${ZLIB_URL}" ]; then
	ZLIB_URL="http://zlib.net/zlib-${ZLIB_VERS}.tar.gz"
fi
ZLIB_TARBALL="src/zlib-${ZLIB_VERS}.tar.gz"
ZLIB_DIR="zlib-${ZLIB_VERS}"

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

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

        set -- clean
fi

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

        exit 0
fi

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

# Download source
. 'scripts/common'

if [ ! -d "${ZLIB_DIR}" ]; then
        download "${ZLIB_URL}" "${ZLIB_TARBALL}" "${ZLIB_TARBALL_SHA256}" || exit 1

        gzip -dc "${ZLIB_TARBALL}" | tar -xf -
fi

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

	if [ -e "${arch_libdir}/libz.a" -o -e "${arch_libdir}/libz.so" ]; then
		continue
	fi

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

	rm -rf "zlib-${CCNAME}-${arch_host}"
	cp -rp "${ZLIB_DIR}" "zlib-${CCNAME}-${arch_host}"
	cd "zlib-${CCNAME}-${arch_host}" || exit 1

	./configure --prefix="${PREFIX}" --libdir="${arch_libdir}" || exit 1

	${MAKE} ${BUILD_CC_MAKE_FLAGS}

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

	${MAKE} distclean

	./configure --prefix="${PREFIX}" --libdir="${arch_libdir}" --static || exit 1

	${MAKE} ${BUILD_CC_MAKE_FLAGS}

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

	cd ..

	rm -rf "zlib-${CCNAME}-${arch_host}"
done

find "${PREFIX}" -name 'zlib.pc' | while IFS='' read -r filename; do
	fix_pkgconfig_file "${filename}"
done

exit 0
