#!/bin/sh

# Wrapper to build a compat32 package
# Arguments:
# $1: SlackBuild file
#
# Copyright (c) 2011 Alan Alberghini
# 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.
# -----------------------------------------------------------------------------

# Arguments check
if [ $# -ne 1 ]
then
	cat << EOF
Usage: $0 SlackBuild-script
EOF
	exit 1
fi

# Become root and relaunch script if launched as unprivileged user

if [ $USER != root ]
then
	su -c "$0 "`pwd`/$1""
	exit 0
fi

echo -n "Setting 32-bit compiling environment..."
. /etc/profile.d/32dev.sh || exit 1
echo "Done!"

# Copy the SlackBuild to modify it

TEMPFILE=`mktemp`
cp "$1" "$TEMPFILE"
chmod +x "$TEMPFILE"

# Remove 64 suffix from libdir
sed -i 's/LIBDIRSUFFIX=.*64.*/LIBDIRSUFFIX=""/g' "$TEMPFILE"

# Remove eventual /usr/lib64 files (already present in 64 bit package)
echo "rm -rf \$PKG/usr/lib64" >> "$TEMPFILE"

# Concat convertpkg to the modified SlackBuild and then delete non-compat32 archive:
OUTFILEINFO=`grep -n makepkg "$1"`
OUTFILELINE=`echo "$OUTFILEINFO" | cut -d: -f1`
OUTFILE="`echo "$OUTFILEINFO" | awk '{print $6}'`"

# First, let's change package tag to a non standard one, in order to prevent an overwrite of
# a same-named 64 bit package already in $OUTDIR, which would get lost;
sed -i "${OUTFILELINE}i\TAG=C32" "$TEMPFILE"
# Second: remove eventual /usr/lib64 files (which should be already there in the 64 bit package)
sed -i "${OUTFILELINE}i\rm -rf \$PKG/usr/lib64" "$TEMPFILE"
# Last: Let's append the compat32 package creation to the SlackBuild...
echo "convertpkg-compat32 -i \""$OUTFILE"\"" >> "$TEMPFILE"
# ... and let's remove the temporary non-stripped down package
echo "rm \""$OUTFILE"\"" >> "$TEMPFILE"

# Finally, launch the modified SlackBuild...
exec "$TEMPFILE"
# and remove the temporary SlackBuild created
rm "$TEMPFILE"
