#! /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 () {
    tar xzf e2fsprogs-1.42.4.tar.gz
    cd e2fsprogs-1.42.4
    bunzip2 -c ../e2fsprogs-1.42.4-e2compr-0.4.12.diff.bz2 | patch -p1 -b
    bunzip2 -c ../e2fsprogs-1.41.9-dietpc-patch.bz2 | patch -p1 -b
    # FIXME: also need this for MIPSEL on Etch
    [ "$ARCH" = 'arm' ] && TLS='--disable-tls' || TLS=
    CFLAGS="$CFLAGS -fPIC" ./configure --prefix='' --enable-compression \
	    --enable-fsck --disable-nls --disable-rpath $TLS
    make
    cd lib/uuid
    gcc -shared -Wl,-soname -Wl,libuuid.so.1 -o libuuid.so.1 `ar t libuuid.a`
    strip -R .note -R .comment libuuid.so.1
    mkdir -p ../../../libuuid1/lib
    cp libuuid.so.1 ../../../libuuid1/lib/
    cd ../..
    rm -f misc/uuidgen
    make -C misc uuidgen LIBUUID=../lib/uuid/libuuid.so.1
    strip -R .note -R .comment misc/uuidgen
    mkdir -p ../uuidgen/bin
    cp misc/uuidgen ../uuidgen/bin/
    strip -R .note -R .comment e2fsck/e2fsck resize/resize2fs \
	    misc/{fsck,mke2fs,chattr,lsattr,badblocks,tune2fs}
    cp e2fsck/e2fsck misc/badblocks ../e2fsck/sbin/
    cp misc/fsck ../fsck/sbin/
    cp misc/mke2fs ../mke2fs/sbin/
    mkdir -p ../e2fsprogs-misc/bin ../e2fsprogs-misc/sbin
    cp misc/{lsattr,chattr} ../e2fsprogs-misc/bin/
    sudo cp misc/{lsattr,chattr} /usr/local/bin/
    cp resize/resize2fs misc/tune2fs ../e2fsprogs-misc/sbin/
    cd ..
    rm -rf e2fsprogs-1.42.4
}

mkdir -p fsck/sbin
for FSTYPE in cramfs iso9660 jffs2 nfs nfs4 squashfs; do
    ln -sf ../bin/true fsck/sbin/fsck.$FSTYPE
done

mkdir -p e2fsck/sbin
ln -sf e2fsck e2fsck/sbin/fsck.ext2
ln -sf e2fsck e2fsck/sbin/fsck.ext3
ln -sf e2fsck e2fsck/sbin/fsck.ext4

mkdir -p mke2fs/sbin
ln -sf mke2fs mke2fs/sbin/mkfs.ext2
ln -sf mke2fs mke2fs/sbin/mkfs.ext3
ln -sf mke2fs mke2fs/sbin/mkfs.ext4

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`

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

for CTRLFILE in */CONTROL/control; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
