#!/bin/sh
# Slackware build script for broadcom-sta proprietary wireless driver
# Written by David Matthew Jerry Koenig <koenigdavidmj@gmail.com>
# Public domain.

NAME="broadcom-sta"
VERSION=${VERSION:-"6.30.223.141"}
BUILDNUM=${BUILDNUM:-"1"}
VER="$(echo ${VERSION} | tr . _)"
VL_VERSION=${VL_VERSION:-"$(ls /var/log/packages/|grep vlconfig2|cut -d "-" -f4|cut -c 2-5)"}
BUILD=${BUILD:-"$BUILDNUM""$VL_VERSION"}
ARCH=${ARCH:-"$(uname -m)"}
KERNEL=${KERNEL:-$(uname -r)}
PKG_VERSION=${VERSION}_$(echo $KERNEL | tr - _)

#LINK32="http://www.broadcom.com/docs/linux_sta/hybrid-portsrc_x86_32-v${VER}.tar.gz"
LINK32="http://www.broadcom.com/docs/linux_sta/hybrid-v35-nodebug-pcoem-${VER}.tar.gz"
#LINK64="http://www.broadcom.com/docs/linux_sta/hybrid-portsrc_x86_64-v${VER}.tar.gz"
LINK64="http://www.broadcom.com/docs/linux_sta/hybrid-v35_64-nodebug-pcoem-${VER}.tar.gz"
LINK="${LINK32} ${LINK64}"

case "$( uname -m )" in
  i?86) ARCH=i586 ;;
  arm*) ARCH=arm ;;
     *) ARCH=$( uname -m ) ;;
esac

CWD=$(pwd)
OUTPUT=${OUTPUT:-$CWD/..}
TMP=${TMP:-"$CWD/../tmp"}
PKG=$TMP/package-$NAME

_WORKDIR=$TMP/build-$NAME

if [ "$NORUN" != 1 ]; then
# Skipped the usual set of variables since they don't apply here
# (libdir isn't needed, and custom CFLAGS aren't wanted).
if [ "$ARCH" = "i586" ]; then
  MY_ARCH=""
  LINK=${LINK32}
  ARCH=x86
elif [ "$ARCH" = "x86_64" ]; then
  MY_ARCH="_64"
  LINK=${LINK64}
else
  printf "\n\n$ARCH is not supported...\n"
  exit 1
fi


for src in $(echo $LINK); do
	(
	cd $CWD
	wget -c --no-check-certificate $src
	)
done
set -e

rm -rf $_WORKDIR $PKG
mkdir -p $TMP $_WORKDIR $PKG $OUTPUT
cd $_WORKDIR
tar xvf $CWD/hybrid-v35${MY_ARCH}-nodebug-pcoem-$(echo $VERSION|tr . _).tar.gz

# Fix API change in newer kernels
patch -p2 < $CWD/patches/broadcom-sta-6.30.223.30-linux-3.10.0.patch
#patch -p1 < $CWD/wl_linux.c-semaphore.patch
#patch -p2 < $CWD/06-3.2.0.patch
#patch -p1 < $CWD/linux-recent.patch
#patch -p1 < $CWD/user-ioctl.patch

# Build the module
make -C /lib/modules/$KERNEL/build M=$_WORKDIR clean
make -C /lib/modules/$KERNEL/build M=$_WORKDIR

# Install the module
mkdir -p $PKG/lib/modules/$KERNEL/kernel/extra
cp wl.ko $PKG/lib/modules/$KERNEL/kernel/extra

mkdir -p $PKG/usr/doc/$NAME-$VERSION
cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/$NAME.SlackBuild
cat $_WORKDIR/lib/LICENSE.txt > $PKG/usr/doc/$NAME-$VERSION/LICENSE.txt

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
chown -R root:root .
/sbin/makepkg -l y -c n $OUTPUT/$NAME-${PKG_VERSION}-$ARCH-$BUILD$TAG.${PKGTYPE:-txz}
rm -r $TMP
fi
