#!/bin/bash

BUILD_LIBS_PATH=`pwd`/build-libs/

# uclibc
export CC=i386-uclibc-linux-gcc
#export CPP=i386-uclibc-linux-cpp
#export LD=i386-uclibc-linux-ld
#export CC="diet gcc -nostdinc"

# extract all necessary packages
dpkg-source -x ../../source-packages/curl_*.dsc
dpkg-source -x ../../source-packages/expat_*.dsc
dpkg-source -x ../../source-packages/discover_*.dsc

# first compile a minimal CURL library (only static)
curl_dir=`ls -d curl-*`
( cd $curl_dir; \
CFLAGS="-Os" ./configure --disable-largefile --enable-static --disable-shared \
	--enable-http --disable-ftp --disable-gopher --enable-file \
        --disable-ldap --disable-dict --disable-telnet --disable-manual \
        --disable-ipv6 --disable-ares --disable-debug --without-ssl \
        --without-ca-bundle --without-zlib --without-libidn \
        --prefix=$BUILD_LIBS_PATH; \
# uclibc hack to make it compile
sed 's/extern int fputc(int, FILE \*);/\/\/extern int fputc(int, FILE \*);/' \
	lib/mprintf.c > lib/mprintf.c.new; \
mv lib/mprintf.c.new lib/mprintf.c; \
make install )

expat_dir=`ls -d expat-*`
( cd $expat_dir; \
# dietlibc hack
#echo 'typedef char* caddr_t;' >> xmlwf/filemap.h
CFLAGS="-Os" ./configure --prefix=$BUILD_LIBS_PATH --disable-shared --enable-static; \
make install )

# when this is set, it won't work...
#export CURL_CONFIG=false
# instead, use a minimal libcurl
export CURL_CONFIG=$BUILD_LIBS_PATH/bin/curl-config
discover_dir=`ls -d discover-*`
( cd $discover_dir; \
CFLAGS="-I$BUILD_LIBS_PATH/include/ -DNDEBUG -Os" LDFLAGS=-L$BUILD_LIBS_PATH/lib/ \
	./configure --disable-shared --prefix=$BUILD_LIBS_PATH \
        --with-default-url=file:///lib/discover/list.xml \
        --sysconfdir=/etc --localstatedir=/var; \
make; \
make; \
strip discover/discover; \
mkdir -p $INSTALL_PATH; \
install -m 0755 discover/discover $INSTALL_PATH )
# I have absolutely no idea why the first make call above fails and the second
# is ok - seems like a broken Makefile.

rm -rf $curl_dir $expat_dir $discover_dir $BUILD_LIBS_PATH

# this is how discover can then be used
#sudo discover/discover --disable-bus all --enable-bus pci --data-path=linux/module/name --data-path=linux/module/options --format="%s %s" --data-version=`uname -r` --normalize-whitespace network
#sudo discover/discover --disable-bus all --enable-bus pci --data-path=linux/module/name | egrep -v '^ $' | uniq --data-path=linux/module/options --format="%s %s" --data-version=`uname -r` --normalize-whitespace bridge | egrep -v '^ $' | grep hcd | uniq

