#!/bin/sh -x
#
# Build script for Realtek Modules x86 & x86_64
. /etc/init.d/tc-functions
useBusybox

##############################################
## place this script in /tmp 
#
# realtek_compile.sh (this script)
#
# 
# then run this build script 
##############################################

name=realtek
address="https://github.com/lwfinger/rtlwifi_new.git"
BuildDir=/tmp/RTL
pkgdir=rtlwifi_new
arch=$(uname -r)


tceinstalled="/usr/local/tce.installed"
optional_path="/etc/sysconfig/tcedir/optional"
cd $optional_path
tce_path=$(realpath ${PWD%/*})

## load build deps
echo -e "\n\nFetching build dependencies... "

deps="compiletc.tcz \
linux-kernel-sources-env.tcz \
squashfs-tools.tcz \
bash.tcz \
git.tcz"

for i in $deps ; do 

pkgname=${i%.tcz}
if [ ! -f ${tce_path}/optional/"$i" ]; then
	tce-load -w "$pkgname"
	[ x$? != x0 ] && tce-load -w "$pkgname"
	[ -f ${tceinstalled}/"$pkgname" ] || exit
elif [ ! -f ${tceinstalled}/"$pkgname" ]; then
	tce-load -i "$pkgname"
fi
done


[ -e /lib/modules/${arch}/build ] || cliorx linux-kernel-sources-env.sh


###########################################################################
## fetch source 
sleep 1

#cleanup
[ $PWD ==  /tmp ] || cd /tmp
echo -e "\n$PWD\n"

[ -d "$BuildDir" ] && rm -rf "$BuildDir"
sleep .5
[ -d "$BuildDir" ] || mkdir -p $BuildDir
cd $BuildDir
git clone $address || exit


###########################################################################
##configure, make, make install

set +x; echo -e "\n\n ${BLUE}Export compiler flags... ${NORMAL}"; set -x
case $arch in
'$arch') 
echo "compile flags for x86"
export CFLAGS="-march=i486 -mtune=i686 -Os -pipe"
export CXXFLAGS="-march=i486 -mtune=i686 -Os -pipe"
;;
'${arch}64') 
echo "compile flags for x86_64"
export CFLAGS="-mtune=generic -Os -pipe"
export CXXFLAGS="-mtune=generic -Os -pipe -fno-exceptions -fno-rtti"
;;
esac


while [ ! -e Make* ]; do 
  f=$(find . -maxdepth 1 -type d)
  cd ${f#*./}
  echo "$PWD"
done
set +x; echo "${MAGENTA}run make${NORMAL}"; sleep 0.5; set -x
make

cd ..
find . -iname "*.ko" -exec gzip {} +

exit

