#! /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:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

rebuild () {
    tar xzf screen-4.0.3.tar.gz
    cd screen-4.0.3
    ./configure --prefix=/usr --disable-pam --disable-locale --disable-telnet \
	    --enable-colors256 --enable-rxvt_osc --with-pty-group=0 \
	    --with-pty-mode=0600 --with-sys-screenrc=/etc/screenrc
    ed -s window.c >/dev/null <<EOF
/\<DefaultPath\[/
s@".*"@"/bin:/usr/bin:/usr/local/bin"@
EOF
    make LIBS='-lutil -lcrypt -Wl,-Bstatic -lcurses -Wl,-Bdynamic'
    strip -R .note -R .comment screen
    mkdir -p ../screen/bin ../screen/share/screen/utf8encodings
    cp screen ../screen/bin/
    # screenrc doesn't seem to be necessary, hardcoded defaults are OK.
    #cp etc/etcscreenrc ../screen/etc/screenrc
    cp utf8encodings/?? ../screen/share/screen/utf8encodings/
    mkdir -p ../screen/share/terminfo
    tic -o ../screen/share/terminfo terminfo/screeninfo.src
    cd ..
    rm -rf screen-4.0.3
}

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

chmod 4755 screen/bin/screen

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
