#!/bin/ksh -p
#
# ident "@(#)utinstall.ksh	1.10	11/04/11 Oracle"
#
# Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved.
#

PATH=/usr/bin:/bin:/usr/sbin:/sbin
ARGS=
umask 022 
OPTSTR=":a:Acd:j:nufv"
PROGRAM_OPTS="[-u]"
DJ=false
G_PROGRAM_ID="$(basename $0)"
G_TIME_STAMP="$(date '+%Y_%m_%d_%H:%M:%S')"
G_ADM_LOG_DIR=""
UNINSTALL=false
RELEASE_PKG=SUNWutsrs

# Copy/pasted from src/release/image/utinstall.ksh, keep in sync
UTDSD_WAS_DISABLED=false
UTDSD_WAS_STOPPED=false
ETCOPT=/etc/opt/SUNWut
UTDSD_ENABLED=$ETCOPT/utenabled.utdsd

OS="$(uname -s |/bin/sed 's/[	 ]*$$//')"
case "$OS" in
  SunOS) G_ADM_LOG_DIR="/var/adm/log";;
  Linux) G_ADM_LOG_DIR="/var/log";;
esac

G_LOGFILE="${G_ADM_LOG_DIR}/${G_PROGRAM_ID}.${G_TIME_STAMP}.log"

function Usage {
  cat 1>&2 <<-ENDIT
	Usage: $G_PROGRAM_ID $PROGRAM_OPTS
	 -u      uninstall the software
	 -A	 use responses from utdialog_responses.props
	 -c	 use responses from utdialog_defaults.props
	 -n	 error if user interaction is required
	ENDIT

  exit 1
}

# Copy/pasted from src/release/image/utinstall.ksh, keep in sync
function CheckSrdsUp {
    if [ -f /etc/opt/SUNWut/utadmin.conf ]; then
	if [ ! -f $UTDSD_ENABLED ]; then
	    UTDSD_WAS_DISABLED=true
	    touch $UTDSD_ENABLED
	fi
	if ! pgrep utdsd >/dev/null; then
	    UTDSD_WAS_STOPPED=true
	    /etc/init.d/utds start
	fi
    fi
}

# Copy/pasted from src/release/image/utinstall.ksh, keep in sync
function RestoreSrdsEnabledState {
    if $UTDSD_WAS_STOPPED && [ -x /etc/init.d/utds ]; then
	/etc/init.d/utds stop
    fi
    if $UTDSD_WAS_DISABLED; then
	rm -f $UTDSD_ENABLED
    fi
}

# main

while getopts $OPTSTR OPT  
do 
    case $OPT in 
        A|c|f|n|v)    ARGS="$ARGS -$OPT";;
	# we need to recognize uninstall to invoke SRWC uninstaller 
	# only  when -u is specified.
	u)   ARGS="$ARGS -$OPT"; UNINSTALL=true;;
	# we need to know which args take optargs, and handle them appropriately
	d|j|a) ARGS="$ARGS -$OPT $OPTARG"; DJ=true;; 
	# anything else is an illegal option - print Usage
	?)	Usage;;
    esac 
done 

# Source the utility library 
. /opt/SUNWut/lib/support_lib/iu_lib

function main {
    if $DJ; then
	print "d, j and a are install time options. Please use only with utinstall on image."
    fi
  
    if $UNINSTALL ; then
	print "\nAbout to Uninstall Sun Ray Software"
	if ! YesOrNo "\nContinue?" "Y"; then
	    return 0
	fi
	CheckSrdsUp
	/opt/SUNWuttsc/lib/utuninstall-srwc $ARGS
	/opt/SUNWut/lib/utinstall-srss $ARGS
	case "$OS" in
	  SunOS) pkgrm -n $RELEASE_PKG 2>&1 | egrep -v 'was successful|^$';;
          Linux) rpm -e --nodeps $RELEASE_PKG;;
        esac

	RestoreSrdsEnabledState	
    else
	print "Please specify -u option for uninstall. Use the downloaded image utinstall for software installation."
	return 1
    fi
}

main 2>&1 | tee -a $G_LOGFILE
STATUS=$?

cat <<-!

	Please check for errors/warnings in

	    $G_LOGFILE

	+++ Done.
	!
exit $STATUS
