#!/bin/sh
# Set initial variables:
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-which

VERSION=2.16
ARCH=${ARCH:-x86_64}
BUILD=1
DISTRO=${DISTRO:-slamd64}

if [ $DISTRO = slackware ]; then
	PKGARCH=$ARCH
else
	PKGARCH=${ARCH}_${DISTRO}
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
rm -rf $PKG
mkdir -p $PKG

cd $TMP
rm -rf which-$VERSION
tar xzvf $CWD/which-$VERSION.tar.gz || exit 1
cd which-$VERSION

chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

CFLAGS=-O2 \
./configure \
  --prefix=/usr \
  --infodir=/usr/info \
  --build=$ARCH-$DISTRO-linux
make || exit 1
make install DESTDIR=$PKG || exit 1
mkdir $PKG/bin
mv $PKG/usr/bin/which $PKG/bin
( cd $PKG/usr/bin ; ln -sf ../../bin/which which )
gzip -9 $PKG/usr/info/*
gzip -9 $PKG/usr/man/man1/*
mkdir -p $PKG/usr/doc/which-$VERSION
cp -a \
  AUTHORS COPYING EXAMPLES NEWS README README.alias \
  $PKG/usr/doc/which-$VERSION

# Strip everything for good measure:
( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

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

# Build the package:
cd $PKG
makepkg -l y -c n $TMP/which-$VERSION-$PKGARCH-$BUILD.tgz