#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild
# http://www.gnu.org/software/units
# http://www.itweb.it/linux/units.php?lng=it
# Packager baldelario ~at~ gmail ~dot~ com
# http://www.slacky.eu

CWD=`pwd`
TMP=${TMP:-/tmp/txz}
NAME=units
PKG=$TMP/package/$NAME
VERSION=1.88
ARCH=${ARCH:-i486}
BUILD=3bj

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

SOURCE=ftp://ftp.gnu.org/gnu/units/$NAME-$VERSION.tar.gz

if [ ! -e $NAME-$VERSION.tar.gz ]; then
wget -c $SOURCE
fi

cd $TMP
rm -rf $NAME-$VERSION
tar xzvf $CWD/$NAME-$VERSION.tar.gz || exit 1
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 .

LDFLAGS="$SLKLDFLAGS" \
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure 	--prefix=/usr \
		--sysconfdir=/etc \
		--localstatedir=/var \
		--libdir=/usr/lib${LIBDIRSUFFIX} \
		--datadir=/usr/share/units \
		--mandir=/usr/man \
		--infodir=/usr/info \
		--docdir=/usr/doc/$NAME-$VERSION \
		--program-prefix= \
		--program-suffix= \
		--build=$ARCH-slackware-linux
make || exit 1
make install DESTDIR=$PKG || exit 1
strip $PKG/usr/bin/*
find $PKG/usr/{man,info} -type f -exec gzip -9 {} \;

(cd $PKG/usr/share/units ; tar xzvf $CWD/it_units.dat.tar.gz 
chown root:root *
)

cat << EOF >> $PKG/usr/share/units/units.dat
!include /usr/share/units/it_units.dat
!include /usr/share/units/old_it_units.dat
EOF

mkdir -p $PKG/usr/doc/$NAME-$VERSION/SlackBuild
cp -a INSTALL COPYING ChangeLog NEWS README* \
  $PKG/usr/doc/$NAME-$VERSION

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

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

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