#!/bin/sh
#
# uninstallTreeps - uninstall the treeps application
#
# SYNOPSIS: 
#      uninstallTreeps 

INSTALL_ROOT=
PREFIX=


. ./scripts/generic/setPath
. ./Install.defaults
. ./Install.params

if [ -f "./Install.prefixes" ]
then
	. ./Install.prefixes
fi

if [ -z "$LIBDIR" ]
then
    LIBDIR="`getInstallLib`"
    export LIBDIR
fi

USER_NAME=`getUserId`

if [ "$1" = "-f" ]
then
	USER_NAME="root"
fi

# Should really store installed user name and verify it.

LOG=`getInstallLog`
SAVE_LOG="/tmp/treepsInstallLog"

OWNER=`cat $LOG | awk -F: '/^[O]/ {print $2}' | sort | uniq`

if [ $USER_NAME != "root" ] 
then 
	echo

    if [ -z "$OWNER" ]
    then
	echo
        echo "Don't know who installed this package, but will try to delete it."
	echo
    else
	if [ "$USER_NAME" != "$OWNER" ] 
	then 
	    echo
            echo "Your user ID is different that the original installer."
            echo "Run with -f option to force uninstall - may fail."
	    echo "Or, su to root and uninstall - should always work."
	    echo
	    exit
	fi
    fi
fi


    if [ -f $LOG ]
    then
	
        cp $LOG $SAVE_LOG

	if [ ! -z "$INSTALL_ROOT" ]
	then
		P="$INSTALL_ROOT"
	fi

	if [ ! -z "$PREFIX" ]
	then
	    if echo "$PREFIX" | grep "^/" > /dev/null
	    then
		P="$P$PREFIX"
	    else    
		P="$P/$PREFIX"
	    fi
	fi

	if [ -z "$P" ]
	then
        	out "Doing uninstall with prefixes - $P" 
	else
        	out "Doing uninstall" 
	fi

	
	# Call other uninstallers

	for i in `cat $SAVE_LOG | awk -F: '/^[C]/ {print $2}' | sort | uniq`
	do
	    echo "Uninstalling from CDE: $i"

	    cd desktop

	    if [ "$i" != "/etc/dt/appconfig" ]
	    then
	    	/usr/dt/bin/dtappintegrate -s CDE -u -t $i
	    else
	    	/usr/dt/bin/dtappintegrate -s CDE -u
	    fi

	    cd ..

	done

	# Remove files and links

	for i in `cat $SAVE_LOG | awk -F: '/^[FS]/ {print $2}' | sort | uniq`
	do
	    echo "Remove File: $P$i"
	    rm -f $P$i
	done

	rm -f $LOG

	# Remove trees whole shot!

	for i in `cat $SAVE_LOG | awk -F: '/^[T]/ {print $2}' | sort | uniq`
	do
	    echo "Remove Tree: $P$i"

	    # A safety check

	    if [ "$P$i" != "/" ]
	    then
	          rm -rf $P$i
	    fi
	done

	# Now remove the empty directories

	cd /tmp

	for i in `cat $SAVE_LOG | awk -F: '/^[D]/ {print $2}' | sort | uniq`
	do
	    #echo "Attempt to remove directory we created: $P$i"

	    NUM_FILES=`find $P$i -type f -print | wc -l`

	    if [ $NUM_FILES -gt 0 ]
	    then
	        echo "Dir Not Empty!! Not Removing -> $P$i"
	    else
	        echo "Remove Empty Dir: $P$i"
	        rm -rf $P$i
	    fi
	done

	rm -f $SAVE_LOG

        echo "Treeps has been uninstalled"

    else
        out "No install log file - can't uninstall"
    fi



