# Copyright (C) 2010, 2012, 2016 D. R. Commander
# Copyright (C) 2009 Sun Microsystems, Inc.
#
# 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@
JAVADIR=@CMAKE_INSTALL_FULL_JAVADIR@
MANDIR=@CMAKE_INSTALL_FULL_MANDIR@
SYSCONFDIR=@CMAKE_INSTALL_FULL_SYSCONFDIR@

if [ -d $BINDIR ]; then
	rmdir $BINDIR 2>&1 || EXITSTATUS=-1
fi
if [ -d $SYSCONFDIR ]; then
	rmdir $SYSCONFDIR 2>&1 || EXITSTATUS=-1
fi
if [ -d $MANDIR/man1 ]; then
	rmdir $MANDIR/man1 2>&1 || EXITSTATUS=-1
fi
if [ -d $MANDIR ]; then
	rmdir $MANDIR 2>&1 || EXITSTATUS=-1
fi
if [ -d $JAVADIR ]; then
	rmdir $JAVADIR 2>&1 || EXITSTATUS=-1
fi
rmdir $PREFIX 2>&1 || EXITSTATUS=-1
if [ -d /Library/Documentation/$PKGNAME ]; then
	rm -rf /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/$PROJECT Viewer.app" ]; then
	rm -rf "/Applications/$PROJECT/$PROJECT Viewer.app" 2>&1 || EXITSTATUS=-1
fi
if [ -d "/Applications/$PROJECT/$PROJECT Viewer (Listen Mode).app" ]; then
	rm -rf "/Applications/$PROJECT/$PROJECT Viewer (Listen Mode).app" 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
