#!/bin/sh
if [ "$1" == "" ]
then
	echo "Please pass the path to the 'Products' directory as the command line argument"
	exit
fi


# 10.9/10.10
PKG_COMPONENT_ROOT=QemuUSBTabletUSBDriver
PKG_FILENAME=QemuUSBTabletUSBDriver.pkg
PKG_IDENTIFIER=eu.philjordan.driver.QemuUSBTablet

KEXT_PATH=`find "$1/$PKG_COMPONENT_ROOT/" -iname *.kext`
KEXT_VERSION=`/usr/libexec/PlistBuddy -c 'Print CFBundleVersion' "$KEXT_PATH/Contents/Info.plist"`
echo building $PKG_FILENAME version $KEXT_VERSION with $KEXT_PATH
pkgbuild --analyze --root "$1/$PKG_COMPONENT_ROOT" "$PKG_FILENAME.component.plist"
pkgbuild --root "$1/$PKG_COMPONENT_ROOT"  --component-plist "$PKG_FILENAME.component.plist"  --identifier "$PKG_IDENTIFIER" --version $KEXT_VERSION --scripts ./scripts/ --ownership recommended "$PKG_FILENAME"
echo

# 10.8 and older
PKG_COMPONENT_ROOT=QemuUSBTablet
PKG_FILENAME=QemuUSBTablet.pkg
PKG_IDENTIFIER=eu.philjordan.driver.QemuUSBTabletHIDEventDriver

KEXT_PATH=`find "$1/$PKG_COMPONENT_ROOT/" -iname *.kext`
KEXT_VERSION=`/usr/libexec/PlistBuddy -c 'Print CFBundleVersion' "$KEXT_PATH/Contents/Info.plist"`
echo building $PKG_FILENAME version $KEXT_VERSION with $KEXT_PATH
pkgbuild --analyze --root "$1/$PKG_COMPONENT_ROOT" "$PKG_FILENAME.component.plist"
pkgbuild --root "$1/$PKG_COMPONENT_ROOT"  --component-plist "$PKG_FILENAME.component.plist"  --identifier "$PKG_IDENTIFIER" --version $KEXT_VERSION --scripts ./scripts/ --ownership recommended "$PKG_FILENAME"
echo

# 10.11 and newer
PKG_COMPONENT_ROOT=QemuUSBTablet1011
PKG_FILENAME=QemuUSBTablet1011.pkg
PKG_IDENTIFIER=eu.dennis-jordan.driver.QemuUSBTablet-10.11

KEXT_PATH=`find "$1/$PKG_COMPONENT_ROOT/" -iname *.kext`
KEXT_VERSION=`/usr/libexec/PlistBuddy -c 'Print CFBundleVersion' "$KEXT_PATH/Contents/Info.plist"`
echo building $PKG_FILENAME version $KEXT_VERSION with $KEXT_PATH
pkgbuild --analyze --root "$1/$PKG_COMPONENT_ROOT" "$PKG_FILENAME.component.plist"
pkgbuild --root "$1/$PKG_COMPONENT_ROOT"  --component-plist "$PKG_FILENAME.component.plist"  --identifier "$PKG_IDENTIFIER" --version $KEXT_VERSION --scripts ./scripts/ --ownership recommended "$PKG_FILENAME"
echo


echo auto-generating Distribution.xml
productbuild --synthesize \
  --package QemuUSBTablet.pkg \
  --package QemuUSBTabletUSBDriver.pkg \
  --package QemuUSBTablet1011.pkg \
  Distribution.xml

cp Distribution.xml Distribution-autogenerated.xml

echo patching Distribution.xml with manual changes
patch -p0 < distribution-xml.patch

