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

# NOTE: before reporting this (old) version of flex should be
# updated to one of the newer unofficial versions, please explain
# why this version doesn't work.  I've read that newer versions
# of flex are not ready for prime time, and I'm going to be
# resistant to upgrading it for no reason.  This one has worked
# fine for a long time.  It's stable and reliable.

VERSION=2.5.4a
CDINTO=2.5.4
ARCH=${ARCH:-i486}
BUILD=3

if [ "$ARCH" = "i386" ]; then
  SLKCFLAGS="-O2 -march=i386 -mcpu=i686"
elif [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mcpu=i686"
elif [ "$ARCH" = "s390" ]; then
  SLKCFLAGS="-O2"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2"
fi

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

# Explode the package framework:
cd $PKG
explodepkg $CWD/_flex.tar.gz

echo "+=============+"
echo "| flex-$VERSION |"
echo "+=============+"
cd $TMP
rm -rf flex-$CDINTO
tar xzvf $CWD/flex-$VERSION.tar.gz
cd flex-$CDINTO
chown -R root:root .
# Modify flex to work with newer, standards-complient gcc:
zcat $CWD/flex-2.5.4a-skel.patch.gz | patch -p1 --verbose
zcat $CWD/flex-2.5.4-glibc22.patch.gz | patch -p1 --verbose
zcat $CWD/flex-2.5.4a-gcc3.patch.gz | patch -p1 --verbose
zcat $CWD/flex-2.5.4a-gcc31.patch.gz | patch -p1 --verbose
zcat $CWD/flex-2.5.4a2.patch.gz | patch -p1 --verbose
mkdir -p $PKG/usr/doc/flex-$VERSION
cp -a INSTALL NEWS README $PKG/usr/doc/flex-$VERSION
mkdir -p $PKG/usr/doc/flex-$VERSION/MISC
cd MISC
cp -a EBCDIC README alloca.c debflex.awk parse.c parse.h \
  testxxLexer.l $PKG/usr/doc/flex-$VERSION/MISC
cp -a fastwc $PKG/usr/doc/flex-$VERSION/MISC
chown -R root:root $PKG/usr/doc/flex-$VERSION
cd ..
CFLAGS="$SLKCFLAGS" \
./configure --prefix=/usr
make CFLAGS=-O2 LDFLAGS=-s
cat flex > $PKG/usr/bin/flex
cat FlexLexer.h > $PKG/usr/include/FlexLexer.h
cat libfl.a > $PKG/usr/lib/libfl.a
cat flex.1 | gzip -9c > $PKG/usr/man/man1/flex.1.gz
cd MISC/texinfo
makeinfo flex.texi
mkdir -p $PKG/usr/info
cat flex.info | gzip -9c > $PKG/usr/info/flex.info.gz
( 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
)
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

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

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