#! /bin/bash

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

rebuild () {
    tar xJf yad-0.35.0.tar.xz
    cd yad-0.35.0
    ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var \
	    --with-rgb=/usr/share/X11/rgb.txt
    make
    gcc -o src/yad src/*.o -lgtk-x11-2.0 -lgdk-x11-2.0 -lgdk_pixbuf-2.0 \
	    -lpango-1.0 -lpangocairo-1.0 -lcairo -lglib-2.0 -lgobject-2.0
    strip src/yad
    make install DESTDIR=`readlink -e ../yad`
    mkdir -p ../yad/usr/share/doc/yad
    gzip -9f ../yad/usr/share/man/man1/yad.1
    cp COPYING ../yad/usr/share/doc/yad/copyright
    for DOCFILE in AUTHORS NEWS README THANKS TODO; do
	gzip -9c $DOCFILE > ../yad/usr/share/doc/yad/$DOCFILE.gz
    done
    cd ..
    rm -rf yad-0.35.0
}

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

# Because someone in their infinite wisdom decided to rename libpango1.0-0 to
# libpango-1.0-0 in Jessie, Jessie builds of yad require a slightly different
# control file.
#case "`cat /etc/debian_version`" in
case "8" in
8*|9*)
    sed -i -e 's/libpango[^,]*/libpango-1.0-0/' yad/CONTROL/control
    ;;
*)
    sed -i -e 's/libpango[^,]*/libpango1.0-0/' yad/CONTROL/control
esac

ARCH=`dpkg --print-architecture`
for CTRLFILE in */CONTROL/control; do
    BASEDIR="`dirname $CTRLFILE`/.."
    SIZE=`du -sk $BASEDIR | awk '{print $1}'`
    sed -i -e "s/__SIZE__/$SIZE/g" $CTRLFILE -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    eval "`egrep '^(Package|Version|Architecture):' $CTRLFILE | sed \
	    's/:\s*/=/'`"
    tar -C $BASEDIR/CONTROL -c -z --owner=0 --group=0 -f control.tar.gz .
    tar -C $BASEDIR -c -z --owner=0 --group=0 --exclude=./CONTROL -f \
	    data.tar.gz .
    echo '2.0' > debian-binary
    ar r ${Package}_${Version}_${Architecture}.deb debian-binary \
	    control.tar.gz data.tar.gz
    rm debian-binary control.tar.gz data.tar.gz
done
