#! /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 samba-2.2.12.tar.gz
    cd samba-2.2.12/source
    cp /usr/share/automake-*/config.guess .
    bunzip2 -c ../../samba-2.2.12-dietpc-patch.bz2 | patch -p2 -b
    CFLAGS="$CFLAGS -D_GNU_SOURCE" ./configure --prefix=/usr \
	    --with-configdir=/etc/samba --with-privatedir=/etc/samba \
	    --with-lockdir=/var/lock --with-piddir=/var/run \
	    --with-logfilebase=/var/log --with-syslog --without-readline \
	    --disable-cups --with-included-popt --with-acl-support \
	    --with-codepagedir=/usr/lib/samba/codepages --with-smbmount \
	    --with-sendfile-support
    # Oplocks need libcap for proper operation!
    #grep -v 'HAVE_SYS_CAPABILITY_H 1' include/config.h >include/config.h.new
    #mv include/config.h.new include/config.h
    # FIXME: smbfs is gone in recent kernels, so smbmnt and smbmount fail due
    # to missing headers.
    make
    rm -f bin/smbmnt
    make bin/smbmnt LIBS=
    rm -f bin/smbmount
    make bin/smbmount LIBS='-ldl -lnsl -lresolv'
    rm -f bin/smbd
    make bin/smbd LIBS="-Wl,-Bstatic -lacl -lattr -lcap -Wl,-Bdynamic -ldl \
	    -lnsl -lcrypt"
    strip -R .note -R .comment bin/smb{mnt,mount} bin/smbd
    mkdir -p ../../cifsd/sbin ../../smbmount/bin \
	    ../../smb-codepages/lib/samba/codepages
    cp bin/smb{mnt,mount} ../../smbmount/bin/
    cp bin/smbd ../../cifsd/sbin/
    for PAGE in 437 737 775 850 852 857 861 862 866 932 936 949 950 1125 \
	    1251; do
	bin/make_smbcodepage c $PAGE codepages/codepage_def.$PAGE \
		../../smb-codepages/lib/samba/codepages/codepage.$PAGE
    done
#   for MAP in 437 737 775 850 852 857 861 862 866 932 936 949 950 1125 1251 \
#	    ISO8859-1 ISO8859-2 ISO8859-5 ISO8859-7 ISO8859-8 ISO8859-9 \
#	    ISO8859-13 ISO8859-15 KOI8-R KOI8-U; do
#	bin/make_unicodemap $MAP codepages/CP${MAP}.TXT \
#		../../smb-codepages/lib/samba/codepages/unicode_map.$MAP
#   done
    cd ../..
    rm -rf samba-2.2.12
}

chmod 0600 cifsd/etc/samba/smbpasswd

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
