#!/bin/bash
#
# Prepares the toolchain needed to cross-compile Ariba for
# Openwrt on the Asus WL-500G (brcm-2.4 chipset)
#
# Martin Florian <mflorian@lafka.net>
# Mar-2010
#

ARIBA_BRCM_DIR=$PWD

test ! -e $ARIBA_BRCM_DIR/variables \
    && echo "ARIBA_BRCM_DIR should point to the ariba-brcm-2.4 directory." \
    && exit

source $ARIBA_BRCM_DIR/variables

test ! -d openwrt-buildroot \
    && echo "The openwt-buildroot folder is missing. You can get it with:

svn co svn://svn.openwrt.org/openwrt/trunk/
mv trunk openwrt-buildroot
" \
    && exit

test ! -e openwrt-buildroot/BSDmakefile \
    && echo "The openwt-buildroot is empty" \
    && exit

cd openwrt-buildroot
#make distclean
test ! -e .config && cp $PATCHES_DIR/openwrt-config .config
patch -p0 < $PATCHES_DIR/openwrt-config-gcc-4.4.3.patch
make $MAKEOPTS tools/install
make $MAKEOPTS toolchain/install

TOOLCHAIN_DIR=$PWD/staging_dir/toolchain-mipsel_gcc-4.4.3_uClibc-0.9.30.1/

cd ..

# make a nice symlink
test -L toolchain && rm toolchain
ln -s $TOOLCHAIN_DIR toolchain

# just to be sure that everything is correct
source $ARIBA_BRCM_DIR/variables

# prepare to install some libs for the cross compiler
test ! -d libs && mkdir libs
cd libs

PREFIX=$TOOLCHAIN_DIR

# install the iconv lib (needed by log4cxx)
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.9.1.tar.gz
tar xzvf libiconv-1.9.1.tar.gz
cd libiconv-1.9.1/
./configure --prefix=$PREFIX $CONFIG_ARGS
make $MAKEOPTS
make install

cd ..

# install the openssl libs (needed by ariba)
wget http://www.openssl.org/source/openssl-0.9.8i.tar.gz
tar xzvf openssl-0.9.8i.tar.gz 
cd openssl-0.9.8i/
./Configure --prefix=$PREFIX shared linux-generic32
sed -i s/linux-generic32/mipsel-openwrt-linux/ Makefile
make $MAKEOPTS \
    CC="${CROSS}gcc $CFLAGS" AR="${CROSS}ar r" RANLIB="${CROSS}ranlib"
make $MAKEOPTS \
    CC="${CROSS}gcc $CFLAGS" AR="${CROSS}ar r" RANLIB="${CROSS}ranlib" install

cd ..

cd ..
