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

VERSION=${VERSION:-0.72}
ARCH=${ARCH:-i486}
BUILD=${BUILD:-2}

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

cd $TMP
rm -rf usbutils-$VERSION
tar xjvf $CWD/usbutils-$VERSION.tar.bz2
cd usbutils-$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 {} \;

# Enable the building of usbmodules, still needed for now on 2.4 systems:
# (obsolete now, but we'll hang onto it until usbutils becomes incompatible
# with the patch...  why not?)
zcat $CWD/usbutils.usbmodules.diff.gz | patch -p1 --verbose || exit 1

# Fetch the latest usb.ids:
rm -f usb.ids
sh ./update-usbids.sh

# Patch update-usbids.sh to update the file in /usr/share:
zcat $CWD/usbutils.ids.dest.gz | patch -p1 --verbose || exit 1

./configure \
  --prefix=/usr \
  --sbindir=/sbin

make -j3 || exit 1
make install DESTDIR=$PKG || exit 1

mkdir -p $PKG/usr/sbin
cat update-usbids.sh > $PKG/usr/sbin/update-usbids
chmod 755 $PKG/usr/sbin/update-usbids

( 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
)

# Compress and if needed symlink the man pages:
if [ -d $PKG/usr/man ]; then
  ( cd $PKG/usr/man
    for manpagedir in $(find . -type d -name "man*") ; do
      ( cd $manpagedir
        for eachpage in $( find . -type l -maxdepth 1) ; do
          ln -s $( readlink $eachpage ).gz $eachpage.gz
          rm $eachpage
        done
        gzip -9 *.?
      )
    done
  )
fi

mkdir -p $PKG/usr/doc/usbutils-$VERSION
cp -a \
  AUTHORS COPYING ChangeLog NEWS README \
  $PKG/usr/doc/usbutils-$VERSION

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

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

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/usbutils-$VERSION
  rm -rf $PKG
fi