#!/bin/bash

PACKAGE=cronosagent

PROJECT=$(readlink -f $0 | xargs dirname)/..
OPENWRT=$HOME/openwrt

if [ -d $OPENWRT/package/$PACKAGE ]
then
  # Remove existing package in buildroot
  rm -rf $OPENWRT/package/$PACKAGE
fi

# Create package directory and copy all stuff
mkdir -p $OPENWRT/package/$PACKAGE/source
cp -R $PROJECT $OPENWRT/package/$PACKAGE/source
rm -rf $OPENWRT/package/$PACKAGE/source/.git

pushd . > /dev/null

cd $OPENWRT

# Make Makefile visible to Buildroot
mv package/$PACKAGE/source/OpenWRT/Makefile package/$PACKAGE

grep "CONFIG_PACKAGE_${PACKAGE}=m" .config > /dev/null
if [ "$?" -ne "0" ]
then
  # Simulate user selection of package $PACKAGE
  echo "CONFIG_PACKAGE_${PACKAGE}=m" >> .config
  # 
  # make -j 4
fi

# Build package
make package/$PACKAGE/compile V=ws 2>&1 | tee $PROJECT/../build.log | grep -i error

# Copy built packages
find bin -name ${PACKAGE}*.ipk | xargs -l -I {} mv {} $PROJECT/.. 

popd > /dev/null