#!/bin/sh

if [ "${2}" != "POST-INSTALL" ]; then
	exit 0
fi

if [ ! -f /usr/local/share/%%PRODUCT_NAME%%/base.txz ]; then
	echo "===> ERROR: base tarball not found!"
	exit 1
fi

# Save a copy of /etc/version to trigger copynotice.inc show when it's needed
if [ ! -f /cf/conf/copynotice_version ]; then
	# Create empty file to force it to differ and show notice once
	echo "" > /cf/conf/copynotice_version
else
	/bin/cp -f /etc/version /cf/conf/copynotice_version
fi

echo %%PRODUCT_NAME%% > /etc/platform

echo "===> Removing schg flag from base files"

# Cleanup schg flags
chflags -R noschg \
	/boot \
	/bin \
	/sbin \
	/usr/bin \
	/usr/sbin \
	/libexec \
	/lib \
	/usr/lib >/dev/null 2>&1

echo "===> Extracting new base tarball"

# Install new base files
tar -C / --exclude ./var/empty -xJPUf \
	/usr/local/share/%%PRODUCT_NAME%%/base.txz

# Create/remove trigger to show copynotice when version changes
if /usr/bin/cmp -s /etc/version /cf/conf/copynotice_version; then
	/bin/rm -f /cf/conf/copynotice_display >/dev/null 2>&1
else
	/usr/bin/touch /cf/conf/copynotice_display
fi

echo "===> Removing static obsoleted files"

# Set IFS to \n to deal with filenames containing spaces
oIFS=${IFS}
IFS="
"

# Process obsolete files
if [ -f /etc/%%PRODUCT_NAME%%.obsoletedfiles ]; then
	for f in $(cat /etc/%%PRODUCT_NAME%%.obsoletedfiles); do
		if [ -n "${f}" -a -d "${f}" ]; then
			chflags -R noschg "${f}"
			rm -rf "${f}"
		elif [ -n "${f}" -a -f "${f}" ]; then
			chflags noschg "${f}"
			rm -f "${f}"
		elif [ -n "${f}" -a -L "${f}" ]; then
			rm -f "${f}"
		fi
	done
fi

# Restore IFS
IFS=${oIFS}

exit 0
