#!/bin/bash

# Slackware build script for heirloom-sh
# Written by slakmagik <slakmagik@gmail.com>
# Released under the WTFPL
# Modified and now maintained by B. Watson <urchlay@slackware.uk>.

# 20260706 bkw, BUILD=2:
# - take over maintenance.
# - add doinst.sh and douninst.sh to add/remove from /etc/shells.

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

PRGNAM=heirloom-sh
VERSION=${VERSION:-050706}
BUILD=${BUILD:-2}
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.bz2
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 {} + \)

# configure is the worst way to build a package except for all the others
# 1. make static changes to the makefile with a patch
patch -p1 < $CWD/makefile.patch
# 2. make dynamic changes to the makefile with sed
sed -i~ "/^CFLAGS=/s:-O:$SLKCFLAGS:;/^ROOT=/s:$:$PKG:" makefile
# 3. make static changes to the manpage with sed (easier maintenance)
sed -i~ 's/\<sh\>/h&/g;s/\<Sh\>/Hsh/g;s/\\fBsh\\fR/\\fBhsh\\fR/' sh.1

# the makefile autostrips
make install

find $PKG/usr/man -type f -exec gzip -9 {} \;
for i in $(find $PKG/usr/man -type l); do
  ln -s $(readlink $i).gz $i.gz; rm $i
done

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a [COR]* $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
