#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild
# http://download.opensuse.org/source/factory/repo/oss/suse/src/
# Packager Andrea Sciucca ( gohanz at infinito.it)
# http://www.slacky.it
#
# Required libx86emu
#
# Exit on most errors
set -e

CWD=`pwd`
TMP=${TMP:-/tmp/txz}
NAME=hwinfo
PKG=$TMP/package/$NAME
VERSION=17.0
REVISION=2.7
ARCH=${ARCH:-i486}
BUILD=3as

SOURCE=http://download.opensuse.org/source/factory/repo/oss/suse/src/$NAME-$VERSION-$REVISION.src.rpm

if [ ! -e $NAME-$VERSION-$REVISION.src.rpm ]; then
wget -c $SOURCE
fi

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

if [ ! -d $TMP ]; then
 mkdir -p $TMP
fi
if [ ! -d $PKG ]; then
 mkdir -p $PKG
fi

cd $TMP
rpm2cpio $CWD/$NAME-$VERSION-$REVISION.src.rpm | cpio -i --make-directories
tar xvjf $NAME-$VERSION.tar.bz2

echo -e "\E[0;32m+--------------------------\E[0;0m"
echo -e "\E[0;32m| Start SlackBuild HWinfo |\E[0;0m"
echo -e "\E[0;32m+--------------------------\E[0;0m"

cd $NAME-$VERSION

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 {} \;

chown -R root:root .

# Apply patch for custom ioctl
  patch -p 0 < $CWD/kbd.patch

# use our CFLAGS
sed -i "s/?= -O2/?= $SLKCFLAGS/" Makefile.common


make \
  LIBDIR=/usr/lib$LIBDIRSUFFIX

make \
  LIBDIR=/usr/lib$LIBDIRSUFFIX \
  DESTDIR=$PKG \
  install


install -m 644 -p -D doc/hwinfo.8 $PKG/usr/man/man8/hwinfo.8



mkdir -p $PKG/usr/doc/$NAME-$VERSION/SlackBuild
cp -a  COPYING changelog  README VERSION $PKG/usr/doc/$NAME-$VERSION


( 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
  find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs strip -g 2> /dev/null
)


mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/slack-desc > $PKG/usr/doc/$NAME-$VERSION/SlackBuild/slack-desc
cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/SlackBuild/$NAME.SlackBuild


gzip -9 $PKG/usr/man/*/*


cd $PKG
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION.$REVISION-$ARCH-$BUILD.txz

if [ "$1" = "--cleanup" ]; then
 rm -rf $TMP
fi
