#!/bin/bash
# Copyright (c) 2008, Fred Emmott <mail@fredemmott.co.uk>
# 
# Permission to use, copy, modify, and/or 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.
# 
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# Get variables out of the script, such as VERSION, BUILD and so on
. "$1" # %SOURCE% - do not delete that marker - used by 'expand'

. /etc/pkghelpers
pkghelpers_env

if [ "x$PKGNAM" = "x" ]; then
	exit 1
fi

# if $2 = expand, write a slackbuild instead of building
if [ "x$2" = "xexpand" ]; then
	OUT="$(basename $1 .PHBuild).SlackBuild"
	cat > "$OUT" << EOF
#!/bin/bash
# Generated by pkghelpers

PKGNAM=$PKGNAM
VERSION=$VERSION
ARCH=$ARCH
BUILD=$BUILD

# Apologies for the mess below, it's several scripts 'cat'ed together.

EOF
	cat /etc/pkghelpers.d/* "$1" >> "$OUT"
	sed '/%SOURCE%/d' "$0" >> "$OUT"
	chmod 755 "$OUT"
	exit
fi

cd $TMP
rm -rf $PKG
rm -rf $PKGNAM-$VERSION
tar xfv $CWD/$PKGNAM-$VERSION.tar.*
cd $PKGNAM-$VERSION
if [ -e $CWD/apply-patches.sh ]; then
	sh $CWD/applypatches.sh
fi
pkghelpers_permissions

if [ -e CMakeLists.txt ]; then # CMake
	mkdir build
	cd build
	cmake \
		-DCMAKE_C_FLAGS:STRING="$SLKCFLAGS" \
		-DCMAKE_CXX_FLAGS:STRING="$SLKCFLAGS" \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DMAN_INSTALL_DIR=/usr/man \
		-DSYSCONF_INSTALL_DIR=/etc \
		-DLIB_SUFFIX=$LIBSUFFIX \
		..
	make -j$NUMJOBS || exit 1
	make install DESTDIR=$PKG || exit 1
elif [ -e configure ]; then # autotools
	CFLAGS="$SLKCFLAGS" \
	CXXFLAGS="$SLKCFLAGS" \
	LDFLAGS="-L/usr/lib$LIBSUFFIX -L/lib$LIBSUFFIX" \
	./configure \
		--prefix=/usr \
		--libdir=/usr/lib$LIBSUFFIX \
		--mandir=/usr/man \
		--sysconfdir=/etc \
		--disable-static \
		--enable-shared \
		$ARCH-$DISTRO-linux
	make -j$NUMJOBS || exit 1
	make install DESTDIR=$PKG || exit 1
fi

mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION
for file in AUTHORS COPYING README LICENSE CHANGELOG ChangeLog NEWS; do
	if [ -e $file ]; then
		install -m644 $file $PKG/usr/doc/$PKGNAM-$VERSION
	fi
done

cd $PKG
# Standard documentation
# Slack-desc and doinst.sh
mkdir install
if [ -e $CWD/slack-desc ]; then
	cat $CWD/slack-desc > install/slack-desc
fi
if [ -e $CWD/doinst.sh.gz ]; then
	zcat $CWD/doinst.sh.gz > install/doinst.sh
fi

# Cleanup and make the package
pkghelpers_fixup
pkghelpers_makepkg
