#!/bin/bash
# Building the installer is only tested and supported on 10.9+ with Xcode 6.0.1
# Built package targets 10.10
# Building should also work on older versions with older revisions or slight changes, YMMV

# You need to have  the following from homebrew or macports or fink:
# autoconf automake libtool pkg-config

set -ex
test -x ./configure || ./bootstrap
BUILDPATH=${PWD}

# Locate the latest OSX SDK
SDKS_PATH="$(xcode-select -p)/Platforms/MacOSX.platform/Developer/SDKs"
SDK_PATH="${SDK_PATH:-$SDKS_PATH/$(ls -1 ${SDKS_PATH} | sort -n -k2 -t. -r | head -1)}"

# Set SDK path
export CFLAGS="$CFLAGS -isysroot $SDK_PATH -arch i386 -arch x86_64 -mmacosx-version-min=10.10"

# OpenSSL is deprecated on OSX since 10.7 and that generates lots of
# "false positive" warnings and there is no alternative option.
# Just ignore these warning for now by silencing them.
CFLAGS="$CFLAGS -Wno-deprecated-declarations"

export SED=/usr/bin/sed
PREFIX=/Library/OpenSC
export PKG_CONFIG_PATH=/usr/lib/pkgconfig

./configure --prefix=$PREFIX \
--sysconfdir=$PREFIX/etc \
--disable-dependency-tracking \
--enable-shared \
--disable-static \
--enable-strict \
--disable-assert \
--enable-sm # TODO: remove this (must be sensible default in master)

# always make clean
make clean

# compile
make -j 2

# copy files
rm -rf target
make install DESTDIR=${BUILDPATH}/target

# remove garbage
rm -f target/$PREFIX/lib/*.la

# generate .bundle (required by Adobe Acrobat)
./MacOSX/libtool-bundle target/$PREFIX/lib/opensc-pkcs11.so target/$PREFIX/lib

# Check out OpenSC.tokend, if not already fetched.
if ! test -e OpenSC.tokend; then
	git clone http://github.com/OpenSC/OpenSC.tokend.git
fi

# Create the symlink to OpenSC sources
test -L OpenSC.tokend/build/opensc-src || ln -sf ${BUILDPATH}/src OpenSC.tokend/build/opensc-src

# Build and copy OpenSC.tokend
xcodebuild -target OpenSC -configuration Deployment -project OpenSC.tokend/Tokend.xcodeproj install DSTROOT=${PWD}/target

# Prepare target root
# The "UnInstaller"
mkdir -p target/usr/local/bin
cp MacOSX/opensc-uninstall target/usr/local/bin

# Build package
pkgbuild --root target --scripts MacOSX/scripts --identifier org.opensc-project.mac --version @PACKAGE_VERSION@ --install-location / OpenSC.pkg
# Build product
productbuild --distribution MacOSX/Distribution.xml --package-path . --resources MacOSX/resources OpenSC-@PACKAGE_VERSION@.pkg

# Build "uninstaller"
pkgbuild --nopayload --identifier org.opensc-project.mac.uninstall --scripts MacOSX/uninstaller-scripts Uninstall_OpenSC.pkg

# Create .dmg
rm -f OpenSC-@PACKAGE_VERSION@.dmg
TIMESTAMP=$(date +%Y.%m.%d)
i=0
while ! hdiutil create -srcfolder Uninstall_OpenSC.pkg -srcfolder OpenSC-@PACKAGE_VERSION@.pkg -volname "OpenSC @PACKAGE_VERSION@ for Mac OS X 10.10+ (${TIMESTAMP})" OpenSC-@PACKAGE_VERSION@.dmg
do
	i=$[$i+1]
	if [ $i -gt 2 ]
	then
		exit 1
	fi
done
