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

tce-load -i compiletc openssl-dev squashfs-tools automake autoconf sysfsutils-dev

# Only needed if enabling NIST-Beacon support.  We should only need hwrng on arm:  
# jansson-dev curl-dev libxml2-dev

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

SRCNAM=rng-tools-6.10.tar.gz
PATCHDIR=patches
WRKDIR=rng-tools-6.10
EXTNAM=rng-tools
TMPDIR=/tmp/$EXTNAM

######################################################
# 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
	armv*)
		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

#Patch Source with Security patches from http://w1.filibgcrypt-dev

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

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

cd $WRKDIR

[ ! -f ./configure ] && ./autogen.sh

./configure --prefix=/usr/local --without-pkcs11 --without-rtlsdr --without-nistbeacon

# Compile

make -j4

# 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

####Remove man pages
rm -rf $TMPDIR/usr/local/share/man

###################################################
# 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

