#! /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 xjf MesaLib-6.5.2.tar.bz2
    cd Mesa-6.5.2
    ed -s configs/linux-dri >/dev/null <<EOF
/^OPT_FLAGS  =/d
i
OPT_FLAGS  = $CFLAGS
.
w
q
EOF
    ed -s configs/default >/dev/null <<EOF
/^DRI_DRIVER_INSTALL_DIR =/d
i
DRI_DRIVER_INSTALL_DIR = /usr/lib/xorg/modules/dri
.
w
q
EOF
    ed -s configs/linux-dri >/dev/null <<EOF
/^DRI_DIRS = /
s/= /= swrast /
w
q
EOF
    case "`uname -m`" in
    *86)
	make linux-dri-x86
	;;
    ppc|powerpc)
	ed -s configs/linux-dri-ppc >/dev/null <<EOF
/^OPT_FLAGS =/d
i
OPT_FLAGS = $CFLAGS -mcpu=603
.
w
q
EOF
	make linux-dri-ppc
	;;
    x86_64)
	ed -s configs/linux-dri-x86-64 >/dev/null <<EOF
/^DRI_DIRS =/d
w
q
EOF
	make linux-dri-x86-64
	;;
    *)
	ed -s configs/linux-dri >/dev/null <<EOF
/^DRI_DIRS =/
/\Wsis\W/
s/sis\W//
w
q
EOF
	make linux-dri
	;;
    esac
    cd src/mesa/drivers/dri
    strip -R .note -R .comment */*_dri.so
    for SHLIB in */*_dri.so; do
	DRIVER=`dirname $SHLIB`
	mkdir -p ../../../../../xserver-xorg-dri-$DRIVER/lib/xorg/modules/dri
	cp $SHLIB ../../../../../xserver-xorg-dri-$DRIVER/lib/xorg/modules/dri/
    done
    cd ../../../../..
    rm -rf Mesa-6.5.2

    case "`uname -m`" in
    *86|x86_64)
	;;
    *)
	mkdir -p xserver-xorg-dri-sis/lib/xorg/modules/dri
	touch xserver-xorg-dri-sis/lib/xorg/modules/dri/sis_dri.so
	;;
    esac
}

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
    [ "$CTRLFILE" = 'xserver-xorg-dri-sis/CONTROL/control' -a "$ARCH" != \
	'i386' -a "$ARCH" != 'amd64' ] && continue
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
