#!/bin/sh
#  $Id: uninstall.sh,v 1.54 2005/09/12 10:08:08 billwe Exp $
#  Copyright (C) 1997-2005 Tarantella, Inc.
#  This software code contains proprietary information 
#  and should be treated as confidential.
#
#  Component: Tarantella Uninstall utility
#  Author: Curtis Cunningham
#
#  Recursively pkgrms installed packages, using dependencies to force order.

# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id: startup.shlib,v 10.165.6.1 2006/04/03 09:51:35 billwe Exp $
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="4.2"
PRODUCT_VERSION_FULL="4.20.983"
PRODUCT_VERSION_MAJOR=4
PRODUCT_VERSION_FEATURE=2
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=983
PRODUCT_VERSION_CAB=4,2,0,983

# Product names
PRODUCT_FULL_NAME="Sun Secure Global Desktop Software"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_SHORT_FILENAME="Tarantella"
TSP_FULL_NAME="Sun Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Sun Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Sun Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Sun Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Sun Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Sun Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Sun Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Sun Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
TCC_FULL_NAME="Sun Secure Global Desktop Client"
TCC_HELPER_NAME="Sun Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Sun Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Sun Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Sun Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Sun Secure Global Desktop Enhancement Module for UNIX/Linux"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Sun Secure Global Desktop Enhancement Module"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"

ARCHIVE_SUFFIX="F"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Sun Microsystems, Inc."
PRODUCT_SHORT_VENDOR="Sun"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"


N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"

u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi

if [ -f $TTAMSG/common -a -f $TTAMSG/tta_uninstall ]; then
  . $TTAMSG/common
  . $TTAMSG/tta_uninstall
else
  echo "Unable to open message file: $TTAMSG/tta_uninstall"
  exit 1
fi

if [ -z "$0" ]; then
  who_i_am=""
else
  who_i_am=`expr "//$0" : '.*/\(.*\)' `
fi

WrapText()
{
    awk 'BEGIN {
	maxwidth = '${1:-74}'
    }
    {
	remtext = $0; remlen = length(remtext)
	while (remlen > 0) {
	    fraglen = remlen
	    if (fraglen > maxwidth) {
		fraglen = maxwidth
		# Move the split point back to a word boundary if necessary.
		# If unable to do that, just split at maxwidth anyway.
		while (fraglen > 0 && substr(remtext,fraglen,2) ~ /[^ 	][^ 	]/) --fraglen
		if (fraglen < 1) fraglen = maxwidth
	    }
	    print substr(remtext,1,fraglen)
	    if ((remlen -= fraglen) > 0) {
		startat = fraglen+1
		# omit whitespace at the beginning of the next line
		while (remlen > 0 && substr(remtext,startat,1) ~ /[ 	]/) { ++startat; --remlen }
		if (remlen > 0) remtext = substr(remtext,startat,remlen)
	    }
	}
    }'
}


if [ -n "$trace" ]; then set -x; fi

OK=0
FAIL=1
NOTANOPTION=2
NOTACOMPONENT=3
DONTDOIT=4
DEPENDFAIL=5

adminfile=$TTAINSTDIR/var/tmp/ttauninst.admin
modefile=$TTAINSTDIR/var/tmp/ttauninst.mode

trap 'rm -f $adminfile $modefile; exit' 1 2 3 15

LOGFILE=$TTAINSTDIR/var/log/ttauninstall.log

# Parse command line arguments

pkgdir="$TTAINSTDIR/etc/pkg"

# Is this an RPM installation ?
RPM_PACKAGE_FILE="${pkgdir}/tta/rpm.pkg"
TTA_RPM=''; [ -f "$RPM_PACKAGE_FILE" ] && TTA_RPM="t"
export TTA_RPM

cwd=`/bin/pwd`
this=$0

# Do a few sanity checks in case we are going to purge the complete install
# tree: don't want to delete too much.
TTAPURGEDIR=""
case "$TTAINSTDIR" in
/?*) if [ -f "$TTAINSTDIR/bin/scripts/uninstall" -a \
          -d "$TTAINSTDIR/etc/pkg" -a \
          -d "$TTAINSTDIR/var/info" ]; then
	TTAPURGEDIR="$TTAINSTDIR"
     fi
esac

cleanandexit() {
    case $1 in
	$OK )
            # if we're still able to run, the server was running when uninstall
            # started, and we're at the top level, try restarting
            if [ -x $TTAINSTDIR/bin/tarantella ]; then
                case $3 in
                    stat=2|stat=3) 
                        case $4 in
                            toplevel=t )
ttadir=$INSTDIR
bindir=$ttadir/bin
script=$bindir/tarantella
if [ ! -x $script ]; then
    echo 1>&2 "$p_nostart"
fi

# Is the server running?
$script status --quiet
if [ $? -eq 2 -o $? -eq 3 ]; then
    runstate=running
else
    runstate=notrunning
	$script start
    res=$?
    if [ $res -ne 0 ]; then
	echo 1>&2 "$p_nostart"
    fi

    # We should wait until the server has fully started, so put in a delay.
    count=10
    while [ $res -eq 0 -a $count -gt 0 ]; do
	sleep 2
	$script status --quiet
	res=$?
	count=`expr $count - 1`
	# If we're half way though, try stopping and restarting the server.
	if [ $count -eq 5 ]; then
	    $script stop --quiet
	    if [ $? -ne 0 ]; then
		$script stop --kill --quiet
	    fi
	    $script start
	fi
    done
fi

                            ;;
                        esac
                    ;;
                esac
            fi
            exit $OK
        ;;
	$FAIL ) echo "$lf_fail" ;;
	$NOTANOPTION ) ;;
	$NOTACOMPONENT ) ;;
	$DONTDOIT ) ;;
	$DEPENDFAIL ) echo "$lf_dependfail" ;;
    esac
    # remove if failed.
    rm -f $adminfile $modefile >/dev/null 2>&1
    exit $FAIL
}

pkg=tta
issubpkg=f
toplevel=t
[ "$1" != "recurse" ] && fulluninstall=t
unconditional="" purge=""
while [ -n "$1" ]; do
    case $1 in
    --help )
	echo "$l_longusage" 1>&2
	exit $OK
	;;
    --force ) 
	unconditional=t
	;;
    --list )  
	pkg=tta 
	cd $pkgdir
	for instance in *instance; do
	    case "$instance" in
	    ${pkg}instance)
		echo $pkg
		sed 's/^/	/' ${pkg}version 2>/dev/null ;;
	    esac
	done
	for instance in *instance; do
	    case "$instance" in
	    ${pkg}instance) ;;
	    *)  subpkg=`expr "$instance" : '\(.*\)instance'`
		echo $subpkg
		sed 's/^/	/' ${subpkg}version 2>/dev/null
	    esac
	done
	exit $OK
	;;
    --purge ) 
	purge=t
	;;
    all )
	pkg=tta 
	fulluninstall=t
	break
	;;
    tta|tta.* ) 
	pkg=$1
	fulluninstall=t
	break
	;;
    recurse ) 
    	pkg=$2
	shift
	toplevel=f
	;;
    * ) installedpkgs=""
	fulluninstall=f
	if [ -d "$pkgdir" ]; then
	    cd "$pkgdir"
	    for i in *
	    do
		if [ -d "$i" ]; then
		    installedpkgs="$installedpkgs $i"
		fi
	    done
	    cd "$cwd"
	fi
	for p in $installedpkgs
	do
	    shortp=`echo $p | sed 's,^\(.*\)\..*$,\1,'`
	    case $1 in 
		    $shortp ) issubpkg=t; break;;
		    $p ) issubpkg=t; break ;;
	    esac
	done
	if [ "$issubpkg" = "f" ]; then
	    echo "${lf_notrecognized1}$1${lf_notrecognized2}"
	    echo "$l_shortusage"
	    cleanandexit $NOTANOPTION
	fi
	pkg=$1
	break
    esac
    shift
done


if [ "$toplevel" = "t" ]; then

    # print out header
echo $_ss_headlines
echo "$h_uninstall"
echo $_ss_headlines

    echo " "

    if [ "$fulluninstall" != "t" ]; then
	# not all packages
	question="$q_uninstall"
	theprompt="$p_uninstall"
	rm -f $modefile
    elif [ -z "$purge" ]; then
	:>$modefile
    	# all packages but not purge
	question="$q_fulluninstall"
	theprompt="$p_fulluninstall
$p_noconfigdelete"
    else
    	# all packages and purge the installation directory
	:>$modefile
	question="$q_fulluninstall"
	theprompt="$p_fulluninstall"
    fi

    $TTAINSTDIR/bin/tarantella status --quiet
    stat=$?
    case $stat in
	0 ) # not running
	;;
	2 ) # running. 0 connections
	    theprompt="$theprompt $p_running"
	;;
	3 ) # running >0 connections
	    theprompt="$theprompt $p_running $p_runningconns"
	;;
    esac
    # warn about other processes being killed
    if [ "$fulluninstall" = "t" ]; then
	theprompt="$theprompt $p_killothers"
    fi

    answer=$a_no
echo "$theprompt"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "$question [$answer] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$answer"   # default
  fi
  case "$_answer" in
    [${a_case_yes}]* )
	    _answer=$s_yes
	    _valid=true
	    ;;
    [${a_case_no}]* )
	    _answer=$s_no
	    _valid=true
	    ;;
  esac
done
answer="$_answer"

	
    if [ "$answer" != "$s_yes" ]; then
	echo "$lf_nochanges"
	cleanandexit $DONTDOIT
    else
	echo " "
    fi

    # stop the web server
    $TTAINSTDIR/bin/tarantella webserver stop >/dev/null 2>&1

    # stop the server if it's running
    INSTDIR=$TTAINSTDIR
cwd=`pwd`
res_ttastop=0
if [ -d "$INSTDIR/bin" -a -x "$INSTDIR/bin/tarantella" ]
then
    cd "$INSTDIR/bin"
    ./tarantella status --quiet
    if [ $? -eq 2 -o $? -eq 3 ]; then
	echo " "
        echo "$p_stopping"
        ./tarantella stop --quiet > /dev/null 2>&1
	res_ttastop=$?
        if [ "$res_ttastop" -ne 0 ]
        then
	    echo " "
	    echo "$p_nostop"
        else
	    echo " "
	    echo "$p_stopok"
        fi
    fi
fi
cd $cwd

    if [ "$res_ttastop" -ne 0 -a "$unconditional" != "t" ]; then
	echo "$lf_nochanges"
	cleanandexit $DONTDOIT
    fi

    # remove all other instances of this package
    pkginfo=""
    thepkg=`echo $pkg | sed 's,^\(.*\)\..*$,\1,'`
    if [ -f $pkgdir/"$thepkg"instance ]; then
	thisinst=`cat $pkgdir/"$thepkg"instance 2>/dev/null`
	[ -z "${TTA_RPM}" ] && pkginfo=`pkginfo $thepkg.\* 2>/dev/null | awk '{printf (" %s ",$2)}'`
    else
	thisinst=$thepkg
	[ -z "${TTA_RPM}" ] && {
	    pkginfo=`pkginfo $thepkg.\* 2>/dev/null | awk '{printf (" %s ",$2)}'`
	    echo "$lf_notknown1$thisinst$lf_notknown2"
	    if [ -n "$pkginfo" ]; then
		echo "$lf_removeothers$thisinst$lf_removeothers2"
	    fi
	}
    fi
    if [ -n "$pkginfo" ]; then
	for pkginst in $pkginfo
	do
	    if [ "$pkginst" != "$thisinst" ]; then
		$this recurse $pkginst 
	    fi
	done
    fi

    # finally remove this instance
    $this recurse $thisinst
    res=$?
    if [ "$res" = "$OK" -a "$toplevel" = "t" -a -n "$purge" -a -n "$TTAPURGEDIR" ]; then
	#
	# Purge the whole tree.
	#
	cd /tmp
	nohup sh -c "sleep 3; rm -rf \"$TTAPURGEDIR\"" >/dev/null 2>&1 &
	exit 0
    fi
    rm -f $modefile
    cleanandexit $res purge=$purge stat=$stat toplevel=$toplevel
else  
    # we have been self-initiated
    # $pkg is a sensible value
    pkginst=$pkg
fi

# double check though - all packages have a name
if [ -z "$TTA_RPM" ]; then
    pkgname=`pkgparam $pkginst NAME 2>/dev/null`
    res=$?
    if [ $res -ne 0 ]; then
       cleanandexit $FAIL 
    fi
else
    pkgname=$PRODUCT_FULL_NAME
fi

# We calculate dependencies using the depends file installed with the package.

# Check the package for dependencies
# and recursively remove those first.
if [ -z "$TTA_RPM" ]; then
    cd $pkgdir
    for p in *; do
	if [ ! -f "$p/depend" ]; then continue; fi
	
	dependencies=`cat $p/depend`
	
	for dep in $dependencies; do
	# If p depends on this package, remove p first
	    if [ "$dep" = "$pkginst" ]; then
		cd $cwd
		$this recurse $p
		res=$?
		if [ $res -gt $FAIL ]; then cleanandexit $DEPENDFAIL; fi
		cd $pkgdir
		break
	    fi
	done
    done
else
    DEPENDANT_PACKAGES=`rpm -q --whatrequires ${pkg}`
    rVal=$?
    [ $rVal -eq $OK ] && {
	# Remove each of the dependancies
	for dep in $DEPENDANT_PACKAGES; do
	    rpm -e $dep
	    rVal=$?
	    if [ $rVal -ne $OK ]; then cleanandexit $DEPENDFAIL; fi
	done
    }
fi


if [ ! -d "$pkgdir/$pkginst" ]; then
    echo "$lf_notacomponent$pkg$lf_notacomponent2"
    cleanandexit $NOTACOMPONENT
fi

if [ "$issubpkg" = "t" -a ! -f "$pkgdir/$pkginst/depend" ]; then
    echo "$lf_notacomponent$pkg$lf_notacomponent2"
    cleanandexit $NOTACOMPONENT
fi

# Construct an admin file
cat >$adminfile <<EOF
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=quit
rdepend=quit
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
EOF

echo ""
echo "Removing <$pkginst> $pkgname" | WrapText

res=0
if [ -z "$TTA_RPM" ]; then
    pkgrm -n -a $adminfile $pkginst >>$LOGFILE
else
    RPM_PACKAGE=`awk '{print $1}' $RPM_PACKAGE_FILE`
    rpm -e "$RPM_PACKAGE"
fi

res=$?
if [ "$fulluninstall" = "t" -a "$toplevel" = "t" ]; then
    echo ""
    echo "$lf_configinfo$TTADATADIR$lf_configinfo2"
fi
if [ $res -eq 0 ]; then
    cleanandexit $res 0 stat=$stat toplevel=$toplevel
else
    cleanandexit $FAIL
fi
