#!/bin/sh
#
######################################################
# Build script                                       #
#                                                    #
# See .info for details                              #
######################################################

tce-load -i compiletc libnl-dev openssl-dev readline-dev squashfs-tools libnl-dev

######################################################
# Configure extension creation parameters            #
######################################################

SRCNAM=wpa_supplicant-2.9.tar.gz
PATCHDIR=patches
WRKDIR=wpa_supplicant-2.9
EXTNAM=wpa_supplicant
TMPDIR=/tmp/wpa_supplicant

######################################################
# Prepare extension creation                         #
######################################################

# Remove dirs and files left from previous creation

rm -r -f $WRKDIR

rm -r -f $TMPDIR

# Crete temporary directory

mkdir -p $TMPDIR

######################################################
# Compile extension                                  #
######################################################

# Export variables needed for compilation

case $(uname -m) in
	arm*)
		export CFLAGS="-Os -pipe -march=armv6zk -mtune=arm1176jzf-s -mfpu=vfp"
		export CXXFLAGS="-Os -pipe -fno-exceptions -fno-rtti -march=armv6zk -mtune=arm1176jzf-s -mfpu=vfp"
	;;
	aarch64)
		export CFLAGS="-Os -pipe -march=armv8-a+crc -mtune=cortex-a72"
		export CXXFLAGS="-Os -pipe -fno-exceptions -fno-rtti -march=armv8-a+crc -mtune=cortex-a72"
	;;
esac

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:/usr/lib/pkgconfig

# Unpack source in current directory

tar -xf $SRCNAM

cp wpa_supplicant.config $WRKDIR/wpa_supplicant/.config

#Patch Source with Security patches from http://w1.fi

if [ -d $PATCHDIR ]; then
	cd $WRKDIR

	for i in ../$PATCHDIR/*;do
		echo "Patch: $i"
		patch -p1 < $i
	done
	cd ..
fi

cd $WRKDIR/wpa_supplicant

##Fix ncurses lib
sed -i 's/-lncurses/-lncursesw/' Makefile

# Compile

make -j4

[ $? -ne 0 ] && exit 1

# Install in base temp dir

make install DESTDIR=$TMPDIR

# Copy License
cd ../..

mkdir -p $TMPDIR/usr/local/share/licenses/$EXTNAM
cp $WRKDIR/COPYING $TMPDIR/usr/local/share/licenses/$EXTNAM/COPYING

# Delete compilation work directory

rm -r -f $WRKDIR

# Adjust directory access rigths

find $TMPDIR/ -type d | xargs chmod -v 755;

# Strip executables

find $TMPDIR | xargs file | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded

###################################################
# Create base extension in temp dir               #
###################################################

cd $TMPDIR
cd ..
mksquashfs $TMPDIR $EXTNAM.tcz
cd $TMPDIR
find usr -not -type d > $EXTNAM.tcz.list
mv ../$EXTNAM.tcz .

# Create md5 file

md5sum $EXTNAM.tcz > $EXTNAM.tcz.md5.txt

# Cleanup temp directory

rm -r -f usr

