#!/bin/ksh -p
#
# ident "@(#)utinstall.ksh	1.45	13/01/11 Oracle"
#
# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
#

#
# utinstall
#
# SRS installation wrapper - One Installer to Bind Them All
#
# This wrapper uses the Component/ heirarchy in the CD install image
# to obtain the information it needs to determine for each component
# whether the component need to be patched and where its patches
# reside, or whether its installer needs to invoked for installation
# or upgrade, and where to find the component installer.
#
# At the moment the only components supported are SRSS and SRWC.
#

#
# Algorithm:
# For each component:
#    if installed_version(component_name) != delivered_version(component_name)
#        invoke component installer
#    else for each component patch:
#        if installed_rev(patch_stream) < delivered_rev(patch_stream)
#            invoke platform "patch install" method
#

PATH=/usr/bin:/bin:/usr/sbin:/sbin

export PROGRAM_ID="$(basename $0)"
export TIME_STAMP="$(date '+%Y_%m_%d_%H:%M:%S')"
IMAGE_DIR=$(dirname $0)
# If it's a relative path, make it absolute
case "${IMAGE_DIR%%/*}" in
	.|..) IMAGE_DIR=$(pwd)/$IMAGE_DIR;;
esac

#
# pre-defined variables
#

ADM_LOG_DIR=""

G_IPSABLE=false
G_IPS_APPLIED=false
G_COMPONENT_LIST=

OS=$(uname -s)
case "$OS" in
  SunOS) ADM_LOG_DIR="/var/adm/log";;
  Linux) ADM_LOG_DIR="/var/log";;
esac

OS_REL_TAG=""
case "$OS" in
  SunOS) 
         case "$(uname -r)" in
           5.10) OS_REL_TAG="Solaris_10";;
           *)
		 OS_REL_TAG="Solaris_11plus"
		 G_IPSABLE=true
		 export G_IPS_REPO=${IMAGE_DIR}/IPS.$(uname -p)
		 ;;
	 esac
         ;;
  Linux) 
         case "$(lsb_release -sr)" in
           5.?) OS_REL_TAG="el5";;
           *) OS_REL_TAG="el6+";;
	 esac
         ;;
esac

# Referenced in support lib
G_LOGFILE="${ADM_LOG_DIR}/${PROGRAM_ID}.${TIME_STAMP}.log"
G_STATUS_FILE=$(mktemp /tmp/${PROGRAM_ID}.errcode.$$.XXXXXX)
G_PLATFORM=$OS
export G_UNINSTALL=false

# Sun Ray doesn't have 64-bit specific packages. On 
# 64-bit OS point to the 32-bit pkg/rpm file-location
function BUILD_ISA {
    case "$(uname -m)" in \
      sun4*)      echo sparc;; \
      i?86*|i86*) echo i386;; \
      x86_64)     echo i386;; \
    esac
}
ISA=$(BUILD_ISA)
PLATFORM_REL_ARCH=$G_PLATFORM.$OS_REL_TAG.$ISA

# Global definitions
image_base=$(dirname $0)
component_base="$image_base"/Components
was_up2date=true
auth_props_backup=$(mktemp /tmp/auth.props-backup.$$.XXXXXX)
upgrade_from_preserve=false
release_pkg=SUNWutsrs
srss_shutdown=/opt/SUNWut/lib/utshutdown-srss
showrev_output=$(mktemp /tmp/showrev.$$.XXXXXX)

umask 022 

# Global parameters set by set_component_params(component_name):
# dir containing patches for the given component
patch_base=
# pathname to representative package within component
package_location=
# name of representative package
package_name=
# pointer to component installer
component_installer=
component_shutdown=
# pathname to directory containing Full Pkg Updates
pkg_updates_dir=
release_pkg_dir=

. $image_base/Lib/install-support-lib

function ValidateImage {
	typeset Correct_platform=true
	typeset Image_type=$(cat ${IMAGE_DIR}/platform.id 2>/dev/null)

	if [[ -n "$Image_type" ]]; then
		if [[ "$OS" == Linux ]]; then
			if [[ "$Image_type" != Linux.i386 ]]; then
				Correct_platform=false
			fi
		else
			if [[ "$Image_type" != "$OS_REL_TAG".$(uname -p) ]]; then
				Correct_platform=false
			fi
		fi
	fi

	if $Correct_platform; then
		return 0
	fi
	cat 1>&2 <<-EOF
	Error: This installation image is designed for use on a different platform.
	The target platform for this image is $Image_type.
	EOF
	return 1
}

function set_component_params {
    typeset component_name=$1
    
    if [[ $G_PLATFORM == SunOS ]]; then
	patch_base="$component_base/$component_name/Patches/solaris/$ISA"
	release_pkg_dir="$image_base/Version/Solaris_10+/$ISA/Packages"
	pkg_updates_dir=$component_base/$component_name/Pkg_Updates/Solaris_10+/$ISA/Packages
    else
	patch_base="$component_base/$component_name/Patches/linux"
	release_pkg_dir="$image_base/Version/Linux/Packages"
	pkg_updates_dir=$component_base/$component_name/Pkg_Updates/Linux/Packages
    fi

    package_location="$image_base/$(cat $component_base/$component_name/a_package-path.$PLATFORM_REL_ARCH)"
    package_name=$(basename "$package_location")
    component_installer="$image_base/$(cat $component_base/$component_name/installer-path)"
    component_shutdown="$component_base/$component_name/shutdown"
}

function cleanup {
    rm -f $showrev_output
    rm -f $auth_props_backup
    rm -f $G_STATUS_FILE
    if $G_IPSABLE; then
	pkg unset-publisher sunray 2>/dev/null
    fi
}

# patch_pkg_installed
# See if a patch is relevant to the current system - i.e. if any patch
# packages are installed on the system

function patch_pkg_installed {
    typeset patch_dir=$patch_base/$1 patch_pkg pkg_name
    typeset utprodinfo patch_valid

    patch_valid=false
    for patch_pkg in $(cd $patch_dir; ls -d SUNW*); do
	case $G_PLATFORM in
	    SunOS)
		pkg_name=$patch_pkg
		;;
	    Linux)
		pkg_name=$(rpm -q --queryformat "%{Name}" -p $patch_dir/$patch_pkg)
		;;
	esac
	utprodinfo=$(getutprodinfo "")
	if $utprodinfo -t installed $pkg_name 2>/dev/null ; then
	    patch_valid=true
	    break
	fi
    done	
    $patch_valid
}

# patch version detection functions: installed_rev, delivered_rev
#
# These functions print a patch stream version number to stdout that
# can be compared numerically to determine newer/older as well as
# equality.
#
# Note that on Solaris the printed value represents the rev of the
# specified patch stream, whereas on Linux these functions will return
# the patch build number, not the actual patch rev, because the rev is
# unavailable. However in all cases the output of these functions is
# monotonic across patch releases and can be compared numerically.
#
# Note if no patch is installed an empty line will be printed, but
# this can be used in shell test functions -gt and -lt and is
# equivalent to 0, i.e. lower than any patch rev
function installed_rev {
    typeset patch_stream_name=${1%-*}
    typeset instrev

    case $G_PLATFORM in
	SunOS)
	    if [[ ! -f $showrev_output ]]; then
		showrev -p > $showrev_output
	    fi
	    instrev=$(sed -n "s/^Patch: $patch_stream_name-\([0-9]*\) .*/\1/p" \
		    $showrev_output | sort -nr | head -n 1)
	    ;;
	Linux) 
	    patch_rpm=$(basename $(ls $patch_base/$1/*.rpm |head -n 1))
	    instrev=$(rpm -q --queryformat "%{Release}" ${patch_rpm%%-*})
	    ;;
    esac
    if [[ -z "$instrev" ]]; then
	instrev=0
    fi
    print $instrev
}

function delivered_rev {
    typeset patch_stream=$1
    typeset delrev

    case $G_PLATFORM in
	SunOS)
	    delrev=${patch_stream#*-}
	    ;;
	Linux)
	    # XXX Need to set delrev to patch build #, not rev
	    delrev=$(rpm -q -p --queryformat "%{Release}" $(ls $patch_base/$1/*.rpm |head -n 1))
	    ;;
    esac
    print $delrev
}


function do_patchadd {
    typeset patch=$1
    typeset cmd

    print "Updating software, please wait."
    if [[ -x $srss_shutdown ]] ; then    
	$srss_shutdown 
    else
	$component_shutdown	
    fi
	
    was_up2date=false

    case $G_PLATFORM in
	SunOS)	
	    cmd="patchadd $patch"
	    ;;
	Linux)
            # For each RPM in patch, remove old, install new (see README.patch)
	    cmd="rpm --nodeps -F $patch/*.rpm"	    
	    ;;
    esac 

    $cmd
    STATUS=$?

    if (( STATUS == 0 )); then 
	# Force activation again, so patch actions can be implemented
	# in activation framework
	rm -f $ETCOPT/utctl.run
        # SRDS needs to be up for SRWC unconfig and removal after SRCS patchadd
        CheckSrdsUp
    else 
	print "There was an error in Patch installation. Please check the above output for details."
	ExitWithFSStatus $STATUS

    fi
}

function handle_ips_update {
    typeset metapkg_list comp

    for comp in $(echo $G_COMPONENT_LIST | tr '[A-Z]' '[a-z]'); do
	metapkg_list="$metapkg_list SUNWut-${comp}"
    done
    pkg install $metapkg_list
}

function handle_component { 
    typeset component_name=$1 
    typeset inst_ver deliv_ver
    typeset exp_bld=false
    
    G_COMPONENT_LIST="$G_COMPONENT_LIST ${component_name##*-}"

    set_component_params $component_name 
    inst_ver="$(installed_version $image_base ${package_name%%-*})" 
    deliv_ver="$(delivered_version $package_location)" 

    case ${inst_ver#*_} in
	Experimental|00)
	    exp_bld=true;;
    esac
    case ${deliv_ver#*_} in
	Experimental|00)
	    exp_bld=true;;
    esac

    # If they are the same release version (but not experimental builds),
    # compare build versions to allow build upgrades

    if ! $exp_bld; then
	CompareFullVersion $deliv_ver $inst_ver
	STATUS=$?
    else
	STATUS=$G_COMPVER_GT
    fi
       
    if $G_UNINSTALL || [ "$STATUS" -eq "$G_COMPVER_GT" ]; then
	was_up2date=false

	$component_installer $ARGS
	STATUS=$?
	if (( STATUS != 0 )) ; then
	    ExitWithFSStatus $STATUS
	fi
	
	if $G_IPSABLE; then
		G_IPS_APPLIED=true
	fi

	inst_ver="$(installed_version $image_base ${package_name%%-*})" 
	if ! $exp_bld; then 
	    CompareFullVersion $deliv_ver $inst_ver 
	    STATUS=$? 
	else
	    case "${deliv_ver#*_}" in
		Experimental|00)
		    STATUS=$G_COMPVER_GT;;
		*)
		    STATUS=$G_COMPVER_EQ;;
	    esac
	fi
    fi 
    
    if ! $G_IPS_APPLIED && (( STATUS == G_COMPVER_EQ )); then 
	if $G_IPSABLE; then
	    handle_ips_update
	else
	    # Backup the auth.props file on Linux since we do a remove
	    # & install of rpms for patches.
	    if [[ "$G_PLATFORM" == Linux ]]; then
		rm -f $auth_props_backup
		cp -p $ETCOPT/auth.props $auth_props_backup	     
	    fi 
	    
	    if [[ -d "$patch_base" ]]; then
		for patch in $(cd $patch_base && print -- *); do 
		    if patch_pkg_installed $patch; then
			inst_rev="$(installed_rev $patch)" 
			deliv_rev="$(delivered_rev $patch)" 
			CompareVersion $deliv_rev $inst_rev 
			
			if (( $? == G_COMPVER_GT )); then 
			    do_patchadd $patch_base/$patch
			fi 
		    fi
		done
	    fi
	    
	    if [[ -d "$pkg_updates_dir" ]]; then
		for pkg in $(cd $pkg_updates_dir && print -- *); do
		    handle_install_pkg $image_base ${pkg%%-[0-9]*} $pkg_updates_dir
		done

	    fi
	    
	    # restore the auth.props file 
	    if [[ "$G_PLATFORM" == Linux ]]; then
		cp -p $auth_props_backup $ETCOPT/auth.props 	     
	    fi 
	fi
    fi 
} 

function Usage {
  cat 1>&2 <<-ENDIT
	Usage: $PROGRAM_ID [opts]

	 -a admin_file

	         specify an admin(4) file to be used by pkgadd(1m)
		 calls during install (Solaris only)

	 -d media_dir
	         specify a directory to install the software from

	 -j jre
	         specify a directory to find the Java Runtime Environment

	 -D dialog_dir
		 specify a directory in which to store/access dialog files

	 -A
		 auto-install using dialog response file

	 -c
		 auto-installation should consume default responses

	 -n
		 auto-installation must be non-interactive

	 -u      uninstall the software
	ENDIT

  exit 1 
}

function CheckSetOptA {
  case "$G_PLATFORM" in
    Linux) print -u2 "can not use option '-a' on Linux"; exit 1;;
    *)     ARGS="$ARGS -a $1";;
  esac
}

# Copy/pasted from src/admin/cli/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/admin/cli/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
}

# Copy/pasted from src/release/image/utinstall.ksh, keep in sync
function RestartServiceManifest {
    typeset SVCADM="/usr/sbin/svcadm"
    typeset IMPORT_MANIFEST="svc:/system/manifest-import"
    if [[ -x $SVCADM ]]; then
        if [[ "$(uname -r)" != 5.10 ]]; then
            $SVCADM restart $IMPORT_MANIFEST
        fi
    fi
}
 
# Copy/pasted from src/release/image/utinstall.ksh, keep in sync
function PostRestoreAction {
    RestoreSrdsEnabledState
    RestartServiceManifest
}

function CheckNotSRSession {
    if [[ -n "$SUN_SUNRAY_TOKEN" ]]; then
	print -u2 "ERROR: You are attempting to run the installer while in a Sun Ray session"
	return 1
    fi
    return 0
}

function main {

    if ! CheckNotSRSession; then
	ExitWithFSStatus 1
    fi

    # For some components SRDS operations must be performed for
    # upgrades and uninstalls. So make sure if it's been configured
    # it's enabled and up.

    CheckSrdsUp
   
    if  ls  /var/tmp/SUNWut.upgrade/preserve_* 1> /dev/null 2>&1 ; then
  	upgrade_from_preserve=true
    fi

    if ! $G_UNINSTALL ; then
	if $G_IPSABLE; then
	    pkg set-publisher -g $image_base/IPS.$ISA sunray
	fi
	
	for component in $(cd $component_base && print -- *); do 
	    handle_component $component
	done 
    else
	print "\nAbout to Uninstall Sun Ray Software"
	if ! YesOrNo "\nContinue?" "Y"; then
	    RestoreSrdsEnabledState
	    return
	fi

	for component in $(cd $component_base; ls -r ); do 
	    handle_component $component
	done 
    fi
    # On S11 SUNWutsrs is handled as part of the SUNWut-srss meta package install
    if ! $G_IPSABLE; then
	handle_install_pkg $image_base $release_pkg $release_pkg_dir
    fi

    PostRestoreAction
    if ! $G_UNINSTALL && $was_up2date ; then
	print "The system is up to date with the latest Sun Ray Software."
    fi
}
# MAIN 
 
if ! ValidateImage; then
	exit 2
fi

# ensure the cleanup function gets invoked on any exit 
trap cleanup 0

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

ARGS=
OPTSTR=":a:Acd:D:fj:nuv"

while getopts $OPTSTR opt  
do 
    case $opt in 
        A|c|f|n|v)    ARGS="$ARGS -$opt";;
	# we need to know which args take optargs, and handle them appropriately
	d|D|j)	ARGS="$ARGS -$opt $OPTARG";;
	a)      CheckSetOptA "$OPTARG";;
	# we need to recognize uninstall, to skip a version check to invoke installer
	u)  G_UNINSTALL=true; ARGS="$ARGS -u";;
	# anything else is an illegal option - print Usage
	?)	Usage;;
    esac 
done 

rm -f $showrev_output 

main 2>&1 | tee -a $G_LOGFILE

cat <<-EOF

	Please check for errors/warnings in

	    $G_LOGFILE

	+++ Done.
	EOF
#
# As main is in pipe with tee, we never get the exit code of it
# (we get the one from tee instead, which is always 0). The handle_component procedure,
# then, creates a temporary file ($G_STATUS_FILE) which contains the error code
# of main. 

if [[ -f $G_STATUS_FILE ]]; then
   exit $(cat $G_STATUS_FILE)
fi
exit 0 
