#!/bin/sh

export ABUILD_CONF=$PWD/abuild-cross-armel.conf
export APORTS=$HOME/aports

SUDO_APK=abuild-apk
CARCH="$(source $ABUILD_CONF ; echo $CARCH)"
CBUILDROOT="$(source $ABUILD_CONF ; echo $CBUILDROOT)"
REPODEST="$(source $ABUILD_CONF ; echo $REPODEST)"
PACKAGER_PRIVKEY="$(source $ABUILD_CONF ; echo $PACKAGER_PRIVKEY)"
TOOLCHAIN_SYSROOT="$(source $ABUILD_CONF ; ${CC} -print-sysroot)"

if [ -z "$CBUILDROOT" -o -z "$CARCH" ]; then
	echo "CARCH and CBUILDROOT needs to be set in $ABUILD_CONF."
	exit 1
fi

# instialize build root (copy packager's key)
mkdir -p "${CBUILDROOT}" "${CBUILDROOT}/etc/apk/keys" "${CBUILDROOT}/lib"
cp -f ${PACKAGER_PRIVKEY}.pub ${CBUILDROOT}/etc/apk/keys
${SUDO_APK} --quiet --arch "$CARCH" --root "$CBUILDROOT" --initdb add

# copy over libgcc_so.so.1 and fake it in apk
if [ ! -f "${CBUILDROOT}/lib/libgcc_s.so" ]; then
	cp -a ${TOOLCHAIN_SYSROOT}/lib/libgcc_s.so* "${CBUILDROOT}"/lib || exit 1
	${SUDO_APK} --quiet --root "$CBUILDROOT" add -t "so:libgcc_s.so.1"
fi

# copy over libstdc++, mangle it, and fake it in apk
if [ ! -f "${CBUILDROOT}/lib/libstdc++.la" ]; then
	cp -a ${TOOLCHAIN_SYSROOT}/lib/libstdc++.* "${CBUILDROOT}"/lib || exit 1
	sed -e "s|libdir=.*|libdir='${CBUILDROOT}/lib/'|" -i "${CBUILDROOT}"/lib/libstdc++.la || exit 1
	${SUDO_APK} --quiet --root "$CBUILDROOT" add -t "so:libstdc++.so.6"
fi

# certain packages need to be installed to build root after each source build
install_linux_headers="linux-headers"
install_libc="libc-dev"
install_zlib="zlib-dev"
install_gmp5="gmp-dev"
install_mpfr3="mpfr-dev"
install_mpc1="mpc1-dev"
install_isl="isl-dev"
install_cloog="cloog-dev"
install_openssl="openssl-dev"
abuildflags_abuild="-r"
install_ncurses="ncurses-dev"

# ordered build and install to build root
for PKG in linux-headers musl libc \
	   busybox busybox-initscripts binutils make pkgconf pkgconfig \
	   zlib gmp5 mpfr3 mpc1 isl cloog gcc \
	   openssl apk-tools \
	   openrc alpine-conf alpine-baselayout alpine-keys alpine-base build-base \
	   pax-utils abuildhelper fakeroot patch sudo abuild; do

	cd $APORTS/main/$PKG

	eval tmp="\${abuildflags_${PKG/-/_}}"
	abuild $tmp || exit 1

	eval tmp="\${install_${PKG/-/_}}"
	if [ -n "${tmp}" ]; then
		${SUDO_APK} --quiet --root "$CBUILDROOT" \
			--repository "${REPODEST}/main" \
			add $tmp || exit 1
	fi
done

