# Copyright (C)2009 Sun Microsystems, Inc.
# Copyright (C)2009-2012, 2014, 2016 D. R. Commander
#
# This library is free software and may be redistributed and/or modified under
# the terms of the wxWindows Library License, Version 3.1 or (at your option)
# any later version.  The full license is in the LICENSE.txt file included
# with this distribution.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# wxWindows Library License for more details.

#!/bin/sh

if [ ! "`id -u`" = "0" ]; then
	echo "ERROR: This script must be executed as root"
	exit -1
fi

PKGNAME=@PKGNAME@
PROJECT=@CMAKE_PROJECT_NAME@
PKGID=@PKGID@
RECEIPT=/Library/Receipts/$PKGNAME.pkg

LSBOM=
if [ -d $RECEIPT ]; then
	LSBOM='lsbom -s -f -l '$RECEIPT'/Contents/Archive.bom'
else
	LSBOM='pkgutil --files '$PKGID
fi

mylsbom()
{
	$LSBOM || (echo "ERROR: Could not list package contents"; exit -1)
}

echo Removing package files ...
EXITSTATUS=0
pushd /
mylsbom | while read file; do
	if [ ! -d "$file" ]; then rm "$file" 2>&1 || EXITSTATUS=-1; fi
done
popd

echo Removing package directories ...
PREFIX=@CMAKE_INSTALL_PREFIX@
BINDIR=@CMAKE_INSTALL_FULL_BINDIR@

if [ -d $BINDIR ]; then
	rmdir $BINDIR 2>&1 || EXITSTATUS=-1
fi
if [ -h $PREFIX/doc ]; then
	rm $PREFIX/doc 2>&1
fi
rmdir $PREFIX 2>&1 || EXITSTATUS=-1
if [ -d /Library/Documentation/$PKGNAME ]; then
	rmdir /Library/Documentation/$PKGNAME 2>&1 || EXITSTATUS=-1
fi
if [ -h /Applications/$PROJECT/Documentation ]; then
	rm /Applications/$PROJECT/Documentation 2>&1 || EXITSTATUS=-1
fi
if [ -d "/Applications/$PROJECT/Uninstall $PROJECT.app" ]; then
	rm -rf "/Applications/$PROJECT/Uninstall $PROJECT.app" 2>&1 || EXITSTATUS=-1
fi
rmdir /Applications/$PROJECT 2>&1 || EXITSTATUS=-1

if [ -d $RECEIPT ]; then
	echo Removing package receipt ...
	rm -r $RECEIPT 2>&1 || EXITSTATUS=-1
else
	echo Forgetting package $PKGID ...
	pkgutil --forget $PKGID
fi

exit $EXITSTATUS
