#! /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}

rebuild () {
    rm -rf glibc-2.2.5 glibc-build
    tar xzf glibc-2.2.5.tar.gz
    cd glibc-2.2.5
    tar xzf ../glibc-linuxthreads-2.2.5.tar.gz
    gunzip -c ../glibc_2.2.5-11.8.diff.gz | patch -p1
    cd debian/patches
    # glibc-cvs.dpatch will fails several globs, but these failures are all
    # benign (they have already been applied, with trivial cosmetic
    # differences that cause context matching to fail).
    sed -e '/^#/d' 0list | while read PATCH; do
	sh $PATCH.dpatch -patch ../..
    done
    cd  ../..
    ed -s Makeconfig >/dev/null <<EOF
/^all-subdirs =/
s/\<db\>//
w
q
EOF
#    ed -s io/Makefile 2>/dev/null <<EOF
#/^static-only-routines =/+1
#s/\Wfstatat64\W/ /
#w
#q
#EOF
    mkdir ../glibc-build
    cd ../glibc-build
    BUILD=`cpp -dumpmachine`
    LINKER_NAME='ld-linux.so.2'
#    case "$BUILD" in
#    arm-linux-gnu|sparc-linux-gnu)
#	BUILD="$BUILD --without-fp"
#	;;
#    ppc-linux-gnu|powerpc-linux-gnu|mips*-linux-gnu)
#	LINKER_NAME='ld.so.1'
#	;;
#    x86_64-linux-gnu)
#	PORTS=
#	LINKER_NAME='ld-linux-x86-64.so.2'
#	ln -sf lib ../libc6-minimal/lib64
#	;;
#    esac
    ../glibc-2.2.5/configure --prefix=/usr --sysconfdir=/etc \
	    --localstatedir=/var --enable-add-ons=linuxthreads \
	    --disable-profile --enable-kernel=2.2.0 \
	    --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 linuxthreads/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 \
	    linuxthreads/libpthread.so.0 rt/librt.so.1 login/libutil.so.1 \
	    ../libc6-minimal/lib/
    chmod u+w elf/ldd
    sed -i -e 's/set -o pipefail/true/' elf/ldd
    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 glibc-2.2.5 glibc-build
}

ln -sf /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
