#!/bin/bash
#
# Written by Elrod
# http://www.thomaselrod.com
#

CWD=`pwd`
NAME=qc-usb
VERSION=0.6.6
ARCH=${ARCH:-x86_64}
BUILD=elrod

TMP=${TMP:-/tmp/build}
PKG=$TMP/package-$NAME
OUTPUT=${OUTPUT:-/tmp}
SOURCE=http://downloads.sourceforge.net/qce-ga/$NAME-$VERSION.tar.gz

# Download the source if not already
if [ ! -e $NAME-$VERSION.tar.gz ]; then
  wget -c $SOURCE
fi

DOCS="APPLICATIONS COPYING CREDITS FAQ README* TODO"


if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"; SLKLDFLAGS=""; LIBDIRSUFFIX=""; CHOST=i486
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"; SLKLDFLAGS=""; LIBDIRSUFFIX=""; CHOST=i486
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"; SLKLDFLAGS="-L/usr/lib64"; LIBDIRSUFFIX="64"
fi


mkdir -p $TMP/tmp-$NAME     # location to build the source
rm -rf $TMP/tmp-$NAME/*     # remove the remnants of previous build
mkdir -p $PKG               # place for the package to be built
rm -rf $PKG/*               # erase old package's contents
mkdir -p $OUTPUT            # place for the package to be saved


echo "++"
echo "|| $NAME-$VERSION"
echo "++"

cd $TMP/tmp-$NAME

echo "Extracting the source for $NAME..."
tar -xzvf $CWD/$NAME-$VERSION.tar.gz
cd ${NAME}-${VERSION}
chown -R root:root .
chmod -R u+w,go+r-w,a-s .


#if [ ! -e /lib/modules/`uname -r`/build ]; then
#  echo "The symbolic link /lib/modules/`uname -r`/build should point to the source directory for the kernel you are running."
#elif [ -z "$(ls -A /lib/modules/`uname -r`/build)" ]; then
#  echo "The symbolic link /lib/modules/`uname -r`/build should point to the source directory for the kernel you are running."
#fi
#
#( cd /lib/modules/`uname -r`/build
#  make oldconfig && make prepare
#)

if [ ! -e /usr/src/linux-`uname -r`/ ]; then
  echo "Need the source for the kernel you are running, /usr/src/linux-$(uname -r)/"
  exit 1
elif [ -z "$(ls -A /usr/src/linux-`uname -r`/)" ]; then
  echo "Need the source for the kernel you are running, /usr/src/linux-$(uname -r)/"
  exit 1
fi

( cd /usr/src/linux-`uname -r`/
  make oldconfig && make prepare
)

echo Building ...
make all
exit
make install DESTDIR=$PKG

