#! /bin/bash
# generates script doing what "make uninstall" would do
# first parameter: the name of the uninstallation script, defaulting to uninstall.sh
# second, optional parameter: the command to execute to uninstall, like "rpm -e armagetronad".

#set -x

UNINSTALL=$1
test "x${UNINSTALL}" = x && UNINSTALL=uninstall

EXTERNAL_CMD=$2

test -z "`echo ${UNINSTALL} | grep '^/'`" && UNINSTALL="`pwd`/${UNINSTALL}"
echo "Generating uninstallation script" ${UNINSTALL}...

if test "$EXTERNAL_CMD" != "" && test "$EXTERNAL_CMD" != "yes"; then
	{
		echo '#! /bin/sh'
		echo "$EXTERNAL_CMD"
	} > "${UNINSTALL}"
else

# start ${UNINSTALL}
cat > "${UNINSTALL}" <<EOF
#! /bin/sh
# uninstalls ${PROGTITLE}

# set default destdir to where the game was installed to
test -z "\${DESTDIR}" && DESTDIR="${ROOTDIR}"
export DESTDIR

# uninstall system files
"\${DESTDIR}${SCRIPTDIR}/sysinstall" uninstall "${PREFIX}" || exit 1

# automaticall generated from "make install"
EOF


# do an installation
echo -n "Performing test installation..."
DEST=$(pwd)/.foruninstall

# test for recursion
if echo ${DESTDIR} | grep "\.foruninstall$"; then
   echo "Recursion detected, aborting."
   exit 0
fi

if ${MAKE} DESTDIR=${DEST} install > /dev/null; then
echo "Success!"
else
echo "Failure :("
rm -rf $DEST
exit -1
fi

find "$DEST" -type d | sed -e "s,^${DEST},rmdir --ignore-fail-on-non-empty \\\$\{DESTDIR\}," > "${UNINSTALL}.dir0"
find "$DEST" -type f | sed -e "s,^${DEST},rm -f \\\$\{DESTDIR\}," > "${UNINSTALL}.files"

# less ${UNINSTALL}.dir0

# add all parent directories of those that are still game-specific
grep "${PROGNAME}" "${UNINSTALL}.dir0" > "${UNINSTALL}.dir"
while test -s "${UNINSTALL}.dir0"; do
  sed -e "s,/[^/]*\$,," < "${UNINSTALL}.dir0" | grep "${PROGNAME}" > "${UNINSTALL}.dir1"
  cat "${UNINSTALL}.dir1" >> "${UNINSTALL}.dir"
  mv "${UNINSTALL}.dir1" "${UNINSTALL}.dir0"
done

# compose uninstall script from file and directory list
cat "${UNINSTALL}.files" >> "${UNINSTALL}"
sort "${UNINSTALL}.dir" -ru >> "${UNINSTALL}"

rm -rf "${DEST}"

fi

# clean up
rm -f "${UNINSTALL}.dir" "${UNINSTALL}.dir0" "${UNINSTALL}.files"

chmod 755 "${UNINSTALL}"

# less "${UNINSTALL}"

echo "done."
