#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin:~/diet-pc/tools'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

# FIXME: Wheezy needs symlink as follows:
# ln -s /usr/include/`cpp -dumpmachine`/asm /usr/include/asm

rebuild () {
    rm -rf eglibc-2.11 eglibc-build
    tar xjf eglibc-2.11-svn20111211.tar.bz2
    mkdir eglibc-build
    cd eglibc-build
    BUILD=`cpp -dumpmachine`
    PORTS='../ports,'
    LINKER_NAME='ld-linux.so.2'
    case "$BUILD" in
    arm-linux-gnu)
	BUILD="$BUILD --without-fp"
	;;
    arm-linux-gnueabi)
	LINKER_NAME='ld-linux.so.3'
	;;
    ppc-linux-gnu|powerpc-linux-gnu|mips*-linux-gnu)
	LINKER_NAME='ld.so.1'
	;;
    *86-linux-gnu)
	PORTS=
	;;
    x86_64-linux-gnu)
	PORTS=
	LINKER_NAME='ld-linux-x86-64.so.2'
	ln -sfn lib ../libc6-minimal/lib64
	;;
    esac
    ../eglibc-2.11/libc/configure --prefix=/usr --sysconfdir=/etc \
	    --localstatedir=/var --enable-add-ons=${PORTS}nptl \
	    --disable-profile --enable-kernel=2.6.16 --with-tls \
	    --with-headers=/usr/include --build=$BUILD
    make
    strip -R .note -R .comment libc.so.6 elf/{ldconfig,$LINKER_NAME} \
	    crypt/libcrypt.so.1 dlfcn/libdl.so.2 math/libm.so.6 \
	    nis/libnsl.so.1 resolv/{libnss_dns.so.2,libresolv.so.2} \
	    nss/libnss_files.so.2 nptl/libpthread.so.0 rt/librt.so.1 \
	    login/libutil.so.1 iconvdata/*.so
    mkdir -p ../libc6-minimal/lib ../libc6-minimal/bin ../ldconfig/sbin
    cp libc.so.6 elf/$LINKER_NAME crypt/libcrypt.so.1 dlfcn/libdl.so.2 \
	    math/libm.so.6 nis/libnsl.so.1 \
	    resolv/{libnss_dns.so.2,libresolv.so.2} nss/libnss_files.so.2 \
	    nptl/libpthread.so.0 rt/librt.so.1 login/libutil.so.1 \
	    ../libc6-minimal/lib/
    cp /lib/libgcc_s.so.1 ../libc6-minimal/lib/
    chmod 755 ../libc6-minimal/lib/libgcc_s.so.1
    strip -R .note -R .comment ../libc6-minimal/lib/libgcc_s.so.1
    chmod u+w elf/ldd
    ed -s elf/ldd >/dev/null <<EOF
1s/bash/sh/
/set -o pipefail/
s/set -o pipefail/true/
w
q
EOF
    cp elf/ldd ../libc6-minimal/bin/
    cp elf/ldconfig ../ldconfig/sbin/
    cp iconvdata/{CP1252,ISO8859-1,UNICODE}.so ../iconv-data-minimal/lib/gconv/
    cd ..
    rm -rf eglibc-2.11 eglibc-build
}

ln -sfn /proc/mounts libc6-minimal/etc/mtab
chmod 0600 libc6-minimal/etc/shadow

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`
for CTRLFILE in */CONTROL/control; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
