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

VERSION=4.17
ARCH=${ARCH:-i486}
BUILD=1

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

cd $TMP
rm -rf stunnel-$VERSION
tar xzvf $CWD/stunnel-$VERSION.tar.gz
cd stunnel-$VERSION
chown -R root:root .
find . -perm 777 -exec chmod 755 {} \;
CFLAGS="-O2" \
./configure \
  --prefix= \
  --exec-prefix= \
  --sysconfdir=/etc \
  --libdir=/usr/lib \
  --datadir=/usr/share \
  --mandir=/usr/man \
  --sbindir=/usr/sbin \
  --localstatedir=/var
make
mkdir -p $PKG/var/run/stunnel
# This will produce a useless key.
make -i install DESTDIR=$PKG
# Get rid of key, so nobody tries to use it:
rm -r $PKG/etc/stunnel/stunnel.pem
# Add cnf:
cat tools/stunnel.cnf > $PKG/etc/stunnel/stunnel.cnf.new
cat $CWD/generate-stunnel-key.sh > $PKG/etc/stunnel/generate-stunnel-key.sh
chmod 755 $PKG/etc/stunnel/generate-stunnel-key.sh
mkdir -p $PKG/usr/doc/stunnel-$VERSION
mv $PKG/usr/share/doc/stunnel/* $PKG/usr/doc/stunnel-$VERSION
rmdir $PKG/usr/share/doc/stunnel
rmdir $PKG/usr/share/doc
rmdir $PKG/usr/share
mkdir -p $PKG/usr/man/pl/man8
mv $PKG/usr/man/man8/stunnel.pl.8 $PKG/usr/man/pl/man8/stunnel.8
mkdir -p $PKG/usr/man/fr/man8
mv $PKG/usr/man/man8/stunnel.fr.8 $PKG/usr/man/fr/man8/stunnel.8
gzip -9 $PKG/usr/man/*/man?/*.? $PKG/usr/man/man?/*.?
( 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
)

# The 4.15 version of stunnel caused some bizarre perms, so
# we'll protect against that:
chmod 755 $PKG/var/lib
chown root:root $PKG/var/lib

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

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

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