#!/bin/sh

if [ ! -f /mach_kernel ]; then
	echo "MacOS X required."
	exit
fi

# Checking for tools required for building a MacOS X package
#
echo "-- Checking for required tools"
tools="/usr/bin/gcc /usr/bin/pkgbuild /usr/bin/productbuild /usr/bin/hdiutil"
missing=""
for tool in ${tools}; do
	if [ ! -f ${tool} ]; then
		missing="${missing} ${tool}"
	fi
done
if [ "${missing}" != "" ]; then
	echo "The following tools are missing:${missing}"
	exit
fi

# Setup build directory
#
cd `dirname $0`/..
if [ -d build ]; then
	rm -rf build
fi
mkdir build
cd build

# Compile Hiawatha
#
cmake .. -DWEBROOT_DIR=/Library/Webserver/hiawatha
make

# Make MacOS X package
#
strip cgi-wrapper hiawatha php-fcgi ssi-cgi wigwam
make install DESTDIR=`pwd`/root
mkdir -p root/Library/PreferencePanes
cp -r ../extra/macosx/HiawathaWebserver.prefPane root/Library/PreferencePanes
mkdir -p root/Library/LaunchDaemons
cp ../extra/macosx/org.hiawatha-webserver.httpd.plist root/Library/LaunchDaemons

echo "-- Building package"
cp -r ../extra/macosx/diskimage .
version=`grep VERSION config.h | cut -f2 -d'"'`
pkgbuild --root root --version ${version} --identifier org.hiawatha-webserver.httpd hiawatha.pkg
productbuild --distribution ../extra/macosx/Distribution.xml --resources ../extra/macosx diskimage/hiawatha-${version}.pkg 
echo "-- Buiding disk image"
hdiutil create ../"Hiawatha ${version}".dmg -srcfolder diskimage -volname "Hiawatha ${version}" -ov

# Done
#
cd ..
if [ "$1" != "-b" ]; then
	rm -rf build
fi
