#!/bin/sh
#
# @(#)wzuninstall	3.3.1.5 98/09/21
# Wingz 3 uninstall script
#
# Usage: wzuninstall [-p platform]"
#

fatal()
{
    echo fatal: $*
    exit 1
}

usage()
{
    echo "usage: wzuninstall [-p platform]"
    exit 2
}

rmfile()
{
    rm -f $1 2>/dev/null || fatal cannot remove file $1
}

rmtree()
{
    rm -rf $1 2>/dev/null || fatal cannot remove directory $1
}

chkfile()
{
    if [ `echo $1 | wc -w` != 1 ]
    then
	return 0
    fi
    if [ -f $1 ]
    then
	return 0
    fi
    return 1
}

test -n "$WINGZ3" || fatal "Environment variable 'WINGZ3' not set"
test -d "$WINGZ3" || fatal "Environment variable 'WINGZ3' not a directory"

. $WINGZ3/bin/wzenv

PLATFORM=
if [ "$1" = "-p" ]
then
    test $# = 2 || usage
    PLATFORM=$2
    shift 2
    test -d $WINGZ3/pkginfo/$PLATFORM || fatal "no packages to uninstall for the $PLATFORM platform"
fi

test $# = 0 || usage

test -z "$PLATFORM" && PLATFORM=$WZPLATFORM

ROOT=`echo $WINGZ3 | sed 's?/Wingz3??'`

chkfile $WINGZ3/pkginfo/$PLATFORM/*.list
if [ $? = 1 ]
then
    fatal no packages installed for $PLATFORM
fi

echo
echo "About to remove all installed packages for $PLATFORM ..."
echo
if [ ! -w $WINGZ3 ]
then
    echo Warning: you do not have write permission in $WINGZ3
    echo
fi
echon "Please enter 'y' to continue: "
read ans
echo
test "$ans" != "y" && exit 0

for p in $WINGZ3/pkginfo/$PLATFORM/*.list
do
    name=`awk -F= '/^i NAME/ { print $2 }' $p`
    version=`awk -F= '/^i VERSION/ { print $2 }' $p`
    echo removing $name $version ...
    cat $p | while read line
    do
	set $line

	case $1 in
	    i|d|F)
		;;
	    f)
		count=`grep "^f $2 " $WINGZ3/pkginfo/*/*.list | wc -l`
		if [ $count = 1 ]
		then
		    rmfile $ROOT/$2
		fi
		;;
	    t)
		count=`grep "^t $2 " $WINGZ3/pkginfo/*/*.list | wc -l`
		if [ $count = 1 ]
		then
		    rmtree $ROOT/$2
		fi
		;;
	    *)
		warning bad entry in package file
		;;
	esac
    done
    rm $p
done

chkfile $WINGZ3/pkginfo/*/*.list
if [ $? = 1 ]
then
    rmfile $WINGZ3/etc/wzinfo
    rmfile $WINGZ3/etc/wzuninstall
fi

find $WINGZ3 -depth -type d -exec rmdir {} \; 2>/dev/null
exit 0
