#!/bin/sh
#$Id: kertex.SlackBuild,v 1.17 2018/08/22 16:56:30 tlaronde Exp $
# Template generated by Alien's SlackBuild Toolkit: http://slackware.com/~alien/AST
# Copyright 2009, 2010, 2011, 2012  Eric Hameleers, Eindhoven, Netherlands
# Copyright 2012-2013  olivares14031@gmail.com
# Copyright 2012-2013, 2016-2018  tlaronde AT polynum.com
# All rights reserved.
#
#   Permission to use, copy, modify, and distribute this software for
#   any purpose with or without fee is hereby granted, provided that
#   the above copyright notice and this permission notice appear in all
#   copies.
#
#   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
#   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#   IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# -----------------------------------------------------------------------------
#
# Slackware SlackBuild script
# ===========================
# By:          tlaronde@polynum.com suggested by olivares14031@gmail.com
# For:         kerTeX
# Descr:       kerTeX Tex Distribution
# URL:         http://www.kergis.com/en/kertex.html
# Needs:
# Changelog:
# 0.999999.1.1: 28/02/2017 by tlaronde@polynum.com
#	* KXPATH handling for kerTeX packages now allows cross-reference
#	  "if other package exists".
# 0.999999.0.2: 01/Feb/2016 by tlaronde@polynum.com
#	* Fix tar '-z' problem.
# 0.9999.7.8: 20/Apr/2013 by tlaronde@polynum.com
#    * Modifications to fit with new R.I.S.K. release.
# 0.9999.3.0-1: 08/Mar/2012 by tlaronde@polynum.com
#              * Sketching how R.I.S.K. has to be used by the package
#                framework.
# 0.9995-1:     06/Mar/2012 by olivares14031@gmail.com
#              * Initial build.
#
# Run 'sh kerTeX.SlackBuild' to build a Slackware package.
# The package (.tgz) and .txt file as well as build logs are created in /tmp .
# Install it using 'installpkg'.
#
# -----------------------------------------------------------------------------
# [TL] Note that the official name is: kerTeX with a small leading 'k'
# to emphasize that TeX is the important part. There is no LaTeX is there
# is no TeX...
# 
# [TL] A supplementary tip: if KERTEX_PKG_DIR is set in the environment
# at packaging time, the _kerTeX_ packages put in this dir will be
# added to the package. These are _kerTeX_ packages built from a running
# kerTeX. There are (if bin fmt, base etc.) binary dependent but hier
# independent. This is the crux.

# [TL] Actually, packaging kerTeX for whatever packaging framework is a
# simple 4 steps process:
# 
# 1) Create a R.I.S.K. configuration file to take into account custom
# values given by the packager when calling this script, and 
# configuring the kerTeX installed hierarchy conforming to the host 
# filesystem hierarchy.
# 
# 2) Let R.I.S.K. build everything (removing all that is 
# automake/autoconf specific, since R.I.S.K. is a framework on is own).
# 
# 3) Let R.I.S.K. install everything according to the filesystem 
# hierarchy configured in a subdirectory.
# 
# 4) Let the host packaging system gather this result. But since
# R.I.S.K. refuses to process if root, we will indeed install in a 
# subdir and package while R.I.S.K. has switched to root for its own
# installation! So 4) is embedded in 3).
#
# As long as the version is concerned, this script could be always
# cutting edge: if there is saved in SRCDIR a tarball with the
# SlackBuild expected name, we use it. If not we download the latest
# version and set the version accordingly. This means that updating
# should be removing the saved tarball...
#
# For R.I.S.K. it refuses to process if being root, and switches only
# when needed. Period.
#
if test $(id -u) -eq 0; then
  echo "Don't run me as root _now_!" >&2
  echo "I will switch to root only when needed." >&2
  exit 1
fi

#========== STEP 1
#
# [TL] We respect the packaging framework protocol: the names, and will
# be configuring R.I.S.K. after these.

# Set initial variables:

PRGNAM=kertex
VERSION=0.999999.1.1	# to be set with the version of a _saved_ tarball
BUILD=${BUILD:-1}

# The TAG is a unique identifier for all your Slackware packages.
# Use your initials as the value for TAG for instance.
TAG=${TAG:-_ast}

# Where do we look for sources?
# [TL] The bundle can be already here (for packaging various flavors)
# renamed with the Slackbuild convention. If not, we will download
# from kergis.com, using the name of the bundle there.
#
SRCDIR=$(cd $(dirname $0); pwd)
SOURCE="$SRCDIR/${PRGNAM}-${VERSION}.tar.gz"
SRCURL=http://downloads.kergis.com/kertex/kertex_bundle.tar

# Place to build (TMP) package (PKG) and output (OUTPUT) the program:
# We will remove this TMP. So create an unlikely name (if someone 
# defines TMP as '/'...), for concurrent builds, and don't fiddle with 
# it once set! The risk suffix will be verified.
#
TMP=${TMP:-/tmp/}/_$$-$PRGNAM-risk
readonly TMP

# PKG will be installed "chrooted" here for packaging. Root created,
# root deleted.
#
PKG=$TMP/package-$PRGNAM

# The result. So not deleted... and not created either: must exist!
#
OUTPUT=${OUTPUT:-/tmp}

# [TL] R.I.S.K. has its own way (does cross-compilation). And needs
# explicit configuration. This script is a generic one. So we will
# only build package for this matrix arch, except that for Intel based
# we build for i486.
#
ARCH=$(uname -m)
case $ARCH in
  i?86) ARCH=i486
	;;
  arm*) ARCH=arm;
	;;
esac

# Exit the script on errors:
set -e
trap 'echo "$0 FAILED at line ${LINENO}" | tee $OUTPUT/error-${PRGNAM}.log' ERR

# Catch unitialized variables:
set -u
P1=${1:-1}

# Save old umask and set to 0022:
_UMASK_=$(umask)
umask 0022

# Create working directories:
OBJDIRPREFIX=$TMP/build # R.I.S.K.
rm -fr $TMP
mkdir -p $OBJDIRPREFIX
TMPDIR=$OBJDIRPREFIX
export OBJDIRPREFIX TMPDIR

#========== STEP 2
#
# [TL] R.I.S.K. processing. This is simply the get_mk_install.sh
# customized.
#

# We need a writable directory and not SRCDIR.
#
cd $TMP

if ! [ -f ${SOURCE} ]; then
  wget -nv -T 20 -O "kertex_bundle.tar" "${SRCURL}" || true
  if [ $? -ne 0 -o ! -s kertex_bundle.tar ]; then
    echo "Downloading 'kertex_bundle.tar' failed... aborting the build."
    exit 1
  fi
  tar xf kertex_bundle.tar
else
  gunzip -c $SOURCE | tar xf -
fi

for src in knuth etex bibtex ams adobe kertex_M kertex_T risk_comp; do
	gunzip -c ${src}_*.tar.gz | tar xf -
	rm ${src}_*.tar.gz
done

# And then updating the version. If this is the saved bundle: it should
# be unchanged. Downloaded: at least equal or newer.
#
VERSION=$(sed -n 's/^VERSION: *\([^ 	][^ 	]*\) *$/\1/p' kertex_T/CID)

# This is a fake configuration for kertex_M, just in order that the
# name is the default one for the dir with the tools.
# This is for illustration purpose. Since kertex_M is on matrix
# (not installed) we do not set anything.
#
cat >$OBJDIRPREFIX/slackbuild <<EOT
EOT

# Start compiling kertex_M.
#
( 
	cd kertex_M;
	cd `../risk_comp/sys/posix/sh1/rkconfig $OBJDIRPREFIX/slackbuild`;
	make SAVE_SPACE=YES;
)

# Then compile kertex_T.

# Real configuration, with chrooting for the installation (the map).
# And customization for url retrievers (kerTeX packaging system for
# Slackware.
#
cat >$OBJDIRPREFIX/slackbuild <<EOT
SYS_FTPC=lftp
SYS_HTTPC=lftp
TARGETCHROOT=$PKG
TARGETOPTDIR=/usr
RK_COMPILE_SUB_ENV=distrib
HUGETEX=YES
EOT

cd kertex_T
cd `../risk_comp/sys/posix/sh1/rkconfig $OBJDIRPREFIX/slackbuild`
make SAVE_SPACE=YES

# Create the TARGETCHROOT hier for rkinstall or rkinstall will fail.
#
mkdir -p "$PKG"
mkdir -p "$PKG/usr/share"
mkdir -p "$PKG/usr/bin"

#===== embedding 4) in 3)...
#
# [TL] R.I.S.K. switches to root only when strictly needed. We are hence
# going to build the package during R.I.S.K. install procedure. So
# we add the custom Slackbuild stuff.
#
# This is the real chunk of commands to build the package.
# Replace the variables.
#
cat >.rkcomp/$$.slackbuild <<EOT
PRGNAM=$PRGNAM
VERSION=$VERSION
BUILD=$BUILD
TAG=$TAG
PKG=$PKG
SRCDIR=$SRCDIR
TMP=$TMP
OUTPUT=$OUTPUT
THIS=$(basename $0)
ARCH=$ARCH
MANDIR=/usr/share/kertex/man
KERTEX_PKG_DIR=${KERTEX_PKG_DIR:-}
EOT

# Then add chunk verbatim.
#
cat >>.rkcomp/$$.slackbuild <<"EOT"
set -u # we are root, don't write randomly...

# If there are kerTeX packages to apply do it now.
if test "x$KERTEX_PKG_DIR" != x; then
  (
  cd $TMP
  mkdir _kxpkg
  cd _kxpkg
  for pkg in $KERTEX_PKG_DIR/*.tar.gz; do
      gunzip -c $pkg | tar xf -
  done
  # Apply bin
  cd $PKG/usr/bin/kertex
  for pkg in $TMP/_kxpkg/*-bin.tar; do
    tar xf $pkg
  done
  # Apply lib
  cd $PKG/usr/share/kertex
  for pkg in $TMP/_kxpkg/*-lib.tar; do
    tar xf $pkg
  done
  # Set KXPATHS
  cd $PKG/usr/share/kertex
  for kxpath in $TMP/_kxpkg/*.kxpath; do
   while read rootdir addpath; do
	test -d $rootdir/ || continue
 	if test -s $rootdir/KXPATH; then
 	  ed $rootdir/KXPATH <<ENDEDSCRIPT
1s|\$|;$addpath;|
w
q
ENDEDSCRIPT
     else
 	  echo ";$addpath;" >$rootdir/KXPATH
 	fi
   done <$kxpath
  done
  )
  rm -fr $TMP/_kxpkg
fi

# Put stuff where SlackBuilt expect them to be (and to be cleaned).
#
rm -rf $OUTPUT/{configure,make,install,error,makepkg}-$PRGNAM.log
                         # remove old log files
# Add documentation:
mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cat $SRCDIR/$THIS > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild
chown -R root:root $PKG/usr/doc/$PRGNAM-$VERSION
find $PKG/usr/doc -type f -exec chmod 644 {} \;

# Compress the man page(s):
if [ -d $PKG$MANDIR ]; then
 find $PKG$MANDIR -type f -exec gzip -9f {} \;
fi

# Add a package description:
mkdir -p $PKG/install
cat $SRCDIR/slack-desc > $PKG/install/slack-desc

# Add a SlackBuild post-install if there is:
if [ -f $SRCDIR/doinst.sh ]; then
  cat $SRCDIR/doinst.sh >> $PKG/install/doinst.sh
fi

# Build the package:
cd $PKG
makepkg --linkadd y --chown n\
  $OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz}  2>&1\
  | tee $OUTPUT/makepkg-${PRGNAM}.log
cd $OUTPUT
md5sum ${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz}\
  > ${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz}.md5
cd -
cat $PKG/install/slack-desc | grep "^${PRGNAM}"\
  > $OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.txt

# Done with the temporary install. Root created, root deleted.
# Just for catching blunders, test name.
#
test "${PKG%$PRGNAM}" != "$PKG" && rm -fr $PKG
EOT

# We simply add this to our own post-install.
#
ed -s .rkcomp/install_bin/post-install <<EOT
?exit 0?-r .rkcomp/$$.slackbuild
w
q
EOT

# Creating a whole install in the $PKG subdir, and creating the package
# by the way.
#
make local_install SAVE_SPACE=YES

# Cleaning our own risk stuff. Check name
#
test "${TMP%risk}" != "$TMP" && rm -fr $TMP

