#!/bin/bash

# Slackware build script for zutils

# Written by B. Watson (urchlay@slackware.uk)

# Licensed under the WTFPL. See http://www.wtfpl.net/txt/copying/ for details.

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=zutils
VERSION=${VERSION:-1.16}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
else
  SLKCFLAGS="-O2"
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.lz
cd $PRGNAM-$VERSION
chown -R root:root .
find . ! -type l    -a \
  \(     -perm /111 -a ! -perm 755 -a -exec chmod -f 755 {} + \) -o \
  \(   ! -perm /111 -a ! -perm 644 -a -exec chmod -f 644 {} + \)

# mention zegrep and zfgrep in the man page for zgrep.
patch -p1 < $CWD/zegrep.zfgrep.man.diff

O=/opt/zutils

# nonstandard (non-autotools) configure scrript: ignores CXXFLAGS
# in the env, but allows it as an argument. CFLAGS not used since
# the code is all C++.
./configure \
  CXXFLAGS="-Wall $SLKCFLAGS" \
  --prefix=$O \
  --mandir=$O/man \
  --infodir=/usr/info \
  --sysconfdir=/etc

make
make install-strip DESTDIR=$PKG
rename .conf .conf.new $PKG/etc/zutils.conf
rm -f $PKG/usr/info/dir
gzip $PKG/$O/man/man*/* $PKG/usr/info/*

# neither upstream nor me is gonna write man pages for zefrep or
# zfgrep, but let's be nice and at least symlink them.
ln -s zgrep.1.gz $PKG/$O/man/man1/zegrep.1.gz
ln -s zgrep.1.gz $PKG/$O/man/man1/zfgrep.1.gz

P=$PKG/etc/profile.d
mkdir -p $P
for i in sh csh; do
  cat $CWD/profile.$i > $P/zutils.$i
  chmod 755 $P/zutils.$i
done

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a AUTHORS* COPYING* Change* NEWS* README* $PKGDOC
cat $CWD/$PRGNAM.SlackBuild > $PKGDOC/$PRGNAM.SlackBuild

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

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE
