#!/bin/sh
#
# Copyright (c) 2006 by Sun Microsystems, Inc.
# All rights reserved.
#
# Installation script for the Sun Desktop Manager (including the 
# configuration templates for Gnome, StarOffice, Mozilla and Evolution).
# 
# Please notice, that this script requires a successfully installed 
# Sun Web Console 2.2.5 (aka Lockhart).


################################################################################
#
# Check if user is logged in as root
#
################################################################################

isRoot() 
{
    id=`id | awk '{print $1}'`
    if [ "${id}" != "uid=0(root)" ]; then
        echo "You must be the system's root user to perform the installation."
        echo
        exit 1
   fi }


################################################################################
# Version to convert a version string in X.Y.Z-* or
# X.Y.X_NN format to XYZNN format so can be treated as a
# number.
#
# $1 = version string
# Returns numerical version
#
########################################################
versionString2Num () {
    
   # Minor and micro default to 0 if not specified.
    major=`echo $1 | awk -F. '{print $1}'`
    minor=`echo $1 | awk -F. '{print $2}'`
    if [ ! -n "$minor" ]; then
	minor="0"
    fi
    micro=`echo $1 | awk -F. '{print $3}'`
    if [ ! -n "$micro" ]; then
	micro="0"
    fi
    # The micro version may further be extended to include a patch number.
    # This is typically of the form <micro>_NN, where NN is the 2-digit
    # patch number.  However it can also be of the form <micro>-XX, where
    # XX is some arbitrary non-digit sequence (eg., "rc").  This latter
    # form is typically used for internal-only release candidates or
    # development builds.
    #
    # For these internal builds, we drop the -XX and assume a patch number
    # of "00".  Otherwise, we extract that patch number.
    #
    patch="00"
    dash=`echo $micro | grep "-"`
    if [ $? -eq 0 ]; then
        # Must be internal build, so drop the trailing variant.
        micro=`echo $micro | awk -F- '{print $1}'`
    fi

    underscore=`echo $micro | grep "_"`
    if [ $? -eq 0 ]; then
        # Extract the seperate micro and patch numbers, ignoring anything
        # after the 2-digit patch.
        patch=`echo $micro | awk -F_ '{print substr($2, 1, 2)}'`
        micro=`echo $micro | awk -F_ '{print $1}'`
    fi

    echo "${major}${minor}${micro}${patch}"

} # versionString2Num

################################################################################
#
# Check for an existing Sun Web Console installation
#
################################################################################

isWebConsoleAvailable() 
{
    pkginfo -q SUNWmcon 
    if [ "$?" != 0 ]; then
        echo "Can not find installed Java(tm) Web Console."
        echo "This is a pre-requirement before installing the Sun Desktop Manager."
        echo
        exit 1
    fi
    CURRENT_VERSION=`env LANG=C LC_ALL=C \
                pkgparam SUNWmcon VERSION | awk -F',' '{print $1}'`
    CURRENT_VERSION_NUM=`versionString2Num $CURRENT_VERSION`
    REQUIRED_VERSION_NUM=`versionString2Num "2.2.5"`
    if [ $CURRENT_VERSION_NUM -lt $REQUIRED_VERSION_NUM ]; then
	echo "Sun Web Console version 2.2.5 or higher is required."
	echo "Sun Web Console version "$CURRENT_VERSION" is installed."
	echo "Please upgrade."
	echo
	exit 1
    fi
}


################################################################################
#
# Global constants
#
################################################################################

SMREG=/usr/sbin/smreg
SMCWEBSERVER=/usr/sbin/smcwebserver
APOC_MANAGER_DIR=/usr/share/webconsole/apoc
A_PACKAGE_REMOVED=0
MISSINGPATCHES=""


################################################################################
# 
# Register APOC Manager application in Lockhart console
#
################################################################################

registerApocManagerApp() {
    $SMREG add -a $APOC_MANAGER_DIR
}


################################################################################
# 
# Unregister APOC Manager application in Lockhart console
#
################################################################################

unregisterApocManagerApp() {

    # Unregister 1.0 version
    APOC10=`$SMREG list -a | grep "com.sun.apoc.manager_1.0"`
    if [ $? -eq 0 ]; then
        $SMREG remove -a com.sun.apoc.manager_1.0
    fi
        
    # Unregister 1.1 version
    APOC11=`$SMREG list -a | grep "com.sun.apoc.manager_1.1"`
    if [ $? -eq 0 ]; then
        $SMREG remove -a com.sun.apoc.manager_1.1
    fi     

    # Unregister 2.0 version
    APOC11=`$SMREG list -a | grep "com.sun.apoc.manager_2.0"`
    if [ $? -eq 0 ]; then
        $SMREG remove -a com.sun.apoc.manager_2.0
    fi     
}


################################################################################
# 
# Restart Sun Web Console (Lockhart)
#
################################################################################

restartLockhartServer() {
    # Restart Lockhart server if it is running.
    if [ `$SMCWEBSERVER status --parseable` = 'running=yes' ]
    then
        $SMCWEBSERVER restart
    else
        $SMCWEBSERVER start
    fi
}


################################################################################
# 
# Create pkgadd admin file (used by installPackages/uninstallPackages)
#
################################################################################

createAdminFile() {
    echo "mail=" >> ${ADMIN}
    echo "instance=overwrite" >> ${ADMIN}
    echo "partial=nocheck" >> ${ADMIN}
    echo "runlevel=nocheck" >> ${ADMIN}
    echo "idepend=nocheck" >> ${ADMIN}
    echo "rdepend=quit" >> ${ADMIN}
    echo "space=nocheck" >> ${ADMIN}
    echo "setuid=nocheck" >> ${ADMIN}
    echo "conflict=nocheck" >> ${ADMIN}
    echo "action=nocheck" >> ${ADMIN}
    echo "basedir=default" >> ${ADMIN}
}


################################################################################
# 
# Install Solaris packages
#
################################################################################

installPackages() {
    echo "Installing Packages"

    ADMIN=/tmp/admin.$$
    createAdminFile

    pkgadd -n -a ${ADMIN} -d . SUNWapcli    
    pkgadd -n -a ${ADMIN} -d . SUNWapmcg
    pkgadd -n -a ${ADMIN} -d . SUNWapm
    pkgadd -n -a ${ADMIN} -d . SUNWapg26
    pkgadd -n -a ${ADMIN} -d . SUNWapmso
    pkgadd -n -a ${ADMIN} -d . SUNWapmmo
    pkgadd -n -a ${ADMIN} -d . SUNWapmev
    pkgadd -n -a ${ADMIN} -d . SUNWapmca
    pkgadd -n -a ${ADMIN} -d . SUNWapms8
    pkgadd -n -a ${ADMIN} -d . SUNWapmda
    
    rm -f ${ADMIN}
}

#################################################################################
# Remove a Solaris package
#
################################################################################

removePackage()
{
    pkginfo -q $2
    if [ $? -eq 0 ]; then
	A_PACKAGE_REMOVED=1
        # package installed, remove it
        pkgrm -n -a $1 $2
    fi
}


################################################################################
# 
# Remove Solaris packages
#
################################################################################

removePackages() 
{
    echo "Removing Packages"
    
    ADMIN=/tmp/admin.$$
    createAdminFile

    removePackage ${ADMIN} SUNWapmda
    removePackage ${ADMIN} SUNWapms8
    removePackage ${ADMIN} SUNWapmca
    removePackage ${ADMIN} SUNWapmev
    removePackage ${ADMIN} SUNWapmmo
    removePackage ${ADMIN} SUNWapmso
    removePackage ${ADMIN} SUNWapg26
    removePackage ${ADMIN} SUNWapm    
    removePackage ${ADMIN} SUNWapmcg
    removePackage ${ADMIN} SUNWapcli
     
    rm -f ${ADMIN}
}



################################################################################
#
# Check existing configuration
#
################################################################################

checkConfigurationFile() 
{
    if [ -r $APOC_MANAGER_DIR/WEB-INF/policymgr.cfg ]; then
        SERVER_NAME=`cat $APOC_MANAGER_DIR/WEB-INF/policymgr.cfg | grep "Server="`
        if [ $? -eq 0 ]; then
            SERVER_NAME=`echo $SERVER_NAME | cut -d"=" -f2`
            if [ "$SERVER_NAME" != "" ]; then
                return 0
            fi
        fi
    fi
    return 1
}


################################################################################
# 
# Check user input
# $1 Message to display
# $2 valid answer from the user
#
################################################################################

checkUserInput() {
    while true; do
        echo
        /usr/ucb/echo -n $1
        read INPUT
        if [ "$INPUT" ]; then
	    case "$INPUT" in
  	        y|Y|yes|YES)
		    return 0
		    ;;
	    	n|N|no|NO)
		    echo "Exiting installation"
		    exit
		    ;;
            	*)
                    echo "Invalid input."
		    continue
		    ;;
            esac
         fi
    done
}


################################################################################
# 
# checkPatchLevel
#
################################################################################
checkPatchLevel() {

    TOINSTALLFILE=/tmp/toinstall.$$
    INSTALLEDPATCHES=/tmp/installed.$$
		PATCHESDIR=../Patches
    REQPATCHES=`ls $PATCHESDIR | nawk -F. '{print$1}'`
    showrev -p > $INSTALLEDPATCHES

    for REQPATCH in $REQPATCHES; do
	grep $REQPATCH $INSTALLEDPATCHES 2>&1 > /dev/null
	if [ $? -eq 1 ]; then
	    echo $REQPATCH >> $TOINSTALLFILE
	fi
    done
    
    rm -f $INSTALLEDPATCHES
    
    if [ -f $TOINSTALLFILE ]; then
	MISSINGPATCHES=`uniq $TOINSTALLFILE`
	rm -f $TOINSTALLFILE
    fi
}

################################################################################
# 
# Display Warnings
#
################################################################################

displayWarnings() {
    if [ "x" != "x$MISSINGPATCHES" ]; then
	echo
	echo "********************************************************************"
	echo "WARNING: The following required patches are not installed"
	echo "on your system:"
	echo
	for PATCH in $MISSINGPATCHES; do
	    echo "\t$PATCH"
	done
	echo
        echo "Please install them on your target system."
	echo
	echo "Please refer to the Release Notes for information about the"
	echo "patches and the issues they address."
	echo "A copy that may not be the most up to date is available under "
	echo "the Patches directory, please go to http://sunsolve.sun.com for"
	echo "the latest version of these patches."
	echo "********************************************************************"
	echo
    fi
}


################################################################################
# 
# Installation
#
################################################################################

install() {
    echo
    echo "- Sun Desktop Manager 1.0 - Server Installation -"
    isRoot
    isWebConsoleAvailable
    pkginfo -q -i SUNWapm
    if [ $? -eq 0 ]; then
	echo "A version of Sun Desktop Manager is already installed"
	INSTALLEDVERSION=`pkginfo -l SUNWapm |grep VERSION | awk '{print $2}'| awk -F. '{print$1"."$2"."$3"."$4}'`
	PKGVERSION=`pkginfo -d . -l SUNWapm |grep VERSION |awk '{print $2}'| awk -F. '{print$1"."$2"."$3"."$4}'`
	if [ $INSTALLEDVERSION = $PKGVERSION ]; then
		checkUserInput "Reinstall Sun Desktop Manager - Server? [y/n]"
        else
		checkUserInput "Upgrade Sun Desktop Manager - Server? [y/n]"
        fi
    	unregisterApocManagerApp
    else
	checkUserInput "Install Sun Desktop Manager - Server? [y/n]"
    fi
 
    installPackages
    registerApocManagerApp
    echo "-- Installation completed." 
    echo
    restartLockhartServer
    checkPatchLevel
    displayWarnings
    echo
    echo "You should be able to access the Sun Desktop Manager:" 
    echo "Browse to https://yourserver:6789 and login with a valid user name and password."
    echo
    echo "The install log can be found in " $LOGFILE

}


################################################################################
# 
# Uninstallation
#
################################################################################

uninstall() {
    if [ x$RELOC = "xSCRIPT_RELOCATED" ]; then
	echo
	echo "- Sun Desktop Manager 1.0 - Server Uninstallation -"
	isRoot
        checkUserInput "Do you want to uninstall Sun Desktop Manager - Server? [y/n]"
	unregisterApocManagerApp
	removePackages
	if [ $A_PACKAGE_REMOVED -eq 0 ]; then
		echo "-- The product was not installed."
	else
		echo "-- Uninstallation completed." 
		echo
		restartLockhartServer
	fi
	echo
	echo "The Uninstall log can be found in " $1
    else
	pkginfo -q SUNWapm
	if [ "$?" != 0 ]; then
		echo "No Sun Desktop Manager Server installation found."
		echo "Exiting uninstallation."
		exit 1
	fi
	cp $0 /tmp/setup.$$
        RELOC="SCRIPT_RELOCATED" export RELOC
        (cd /tmp && exec ./setup.$$ -u)
    fi
}


#################################################################################
# Usage
#
################################################################################

usage() {
        cat - << EOF

Usage setup [-h] | [-u]

-h = print this usage statement

-u = uninstall the packages

     When used without arguments it installs the packages. The installation will     ask for confirmation.

EOF

exit 0
}

################################################################################
# 
# acceptLicense
#
################################################################################

acceptLicense() {
	LICENSEBASEDIR="../../../Licenses"
	LICENSEBASENAME="$LICENSEBASEDIR/LICENSE"
	ACCEPTSENTENCE="$LICENSEBASEDIR/AcceptSentence"

	if [ $LANG ]; then
		FILE="$LICENSEBASENAME.$LANG"
		SENTENCE="$ACCEPTSENTENCE.$LANG"
		if [ ! -f $FILE -o ! -f $SENTENCE ]; then
			FILE=$LICENSEBASENAME
			SENTENCE=$ACCEPTSENTENCE
		fi
	else
		FILE=$LICENSEBASENAME
		SENTENCE=$ACCEPTSENTENCE
	fi
	if [ ! -f $FILE ]; then
		echo "No license file available. Exiting the installation"
		exit 1
	fi
	if [ ! -f $SENTENCE ]; then
		echo "No acceptance sentence available. Exiting installation"
		exit 1
	fi

        MSG=`cat "$SENTENCE"`	
	more "$FILE"
	checkUserInput "$MSG"
}

################################################################################
# 
# Main
#
################################################################################

if [ "$1" = "-u" ]; then 
    LOGFILE=/var/sadm/install/logs/SunDesktopManager_uninstall.`date "+%Y%m%d%H%M%S`
    uninstall $LOGFILE 2>&1 | tee $LOGFILE 
elif [ "$1" = "-h" ]; then
    usage
else 
    acceptLicense
    LOGFILE=/var/sadm/install/logs/SunDesktopManager_install.`date "+%Y%m%d%H%M%S`
    install $LOGFILE 2>&1 | tee $LOGFILE 
fi
