#!/bin/ash

make clean
sudo rm -rf _install

if [ "$1" == "x86" ]; then
	export CFLAGS="-march=i486 -mtune=i686 -Os -pipe"
	export CXXFLAGS="-march=i486 -mtune=i686 -Os -pipe"
	export LDFLAGS="-Wl,-O1"
elif [ "$1" == "x86_64"; then
	export CFLAGS="-mtune=generic -Os -pipe"
	export CXXFLAGS="-mtune=generic -Os -pipe"
	export LDFLAGS="-Wl,-O1"
elif [ "$1" == "RPi" ]; then
	export CFLAGS="-Os -pipe"
	export CXXFLAGS="-Os -pipe"
	export LDFLAGS="-Wl,-O1
else
	echo
	echo "USAGE: $(basename $0) x86 | x_86_64 | RPi
	echo
	exit 1
fi

if ! which file >/dev/null; then
	echo
	echo "ERROR: this script need 'file' as command, abort"
	echo
	exit 1
fi

make
make DESTDIR=./_install install
rm -rf _install/usr/local/share
find _install -type f | xargs file | grep "ELF .* executable, .* not stripped" | cut -f 1 -d : | xargs strip --strip-unneeded 2>/dev/null
find _install -type f | xargs file | grep "ELF .* shared object, .* not stripped" | cut -f 1 -d : | xargs strip -g 2>/dev/null
find _install -type d | xargs chmod 755
find _install -type f | xargs chmod 644
find _install -type f | xargs file | grep "executable" | cut -d: -f1 | xargs chmod 755

echo
echo "Check this for dependencies"
find _install -type f | xargs file | grep "ELF .* executable," | cut -f 1 -d : | xargs ldd 2>/dev/null
find _install -type f | xargs file | grep "ELF .* shared object," | cut -f 1 -d : | xargs ldd 2>/dev/null
echo
echo "Press ENTER to continue or CTR-C to stop"
read

sudo rm -rf unionfs-fuse.tcz
sudo chown -R root.root _install
sudo mksquashfs _install unionfs-fuse.tcz >/dev/null
sudo chown tc.staff unionfs-fuse.tcz
du -ks unionfs-fuse.tcz

ls -1 /usr/local/tce.installed/ | grep -ve "-meta$" | sed -e "s,\(.*\),\1.tcz," >unionfs-fuse.tcz.buid_dep

cd _install 
find usr -not -type d > ../unionfs-fuse.tcz.list
cd ..

submitqc --libs --tcz=unionfs-fuse.tcz

echo
