#!/bin/ksh -p
#
# ident "@(#)install-support-lib.ksh	1.5	12/05/11 Oracle"
#
# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
#

# install-support-lib
#
# support library functions shared between the SRS image Common
# Installer (release/image/utinstall) and the FW image installer (utfwinstall)

function getutprodinfo {
   # Description:
   #    Print a path to a usable utprodinfo
   #    Searches /opt/SUNWut/lib, then /tmp, then install image
   #
   #    usage:  getutprodinfo <base>
   #		base can be either an installation image base with a
   #		Lib/utprodinfo, or base of a temporary SUNWuti as in
   #		/tmp/....
   #    prints the path it found utprodinfo on
   #
   # Parameters:
   #    $1 - base of install image or temp SUNWuti install base
   #
   # Globals used: none

    typeset image_base=$1
    typeset inst_utprodinfo=/opt/SUNWut/lib/utprodinfo
    typeset image_utprodinfo=$image_base/Lib/utprodinfo

    if [ -x $inst_utprodinfo ]; then
    # if utprodinfo installed via SUNWuti, use it
	print $inst_utprodinfo
    elif [ -x $image_base/$inst_utprodinfo ]; then
    # if utprodinfo installed in /tmp SUNWuti, use it
	print $image_base/$inst_utprodinfo
    elif [ -x $image_utprodinfo ]; then
    # if utprodinfo in image (FW), use it
	print $image_utprodinfo
    else
    # if none of above, must be SRS, with no packages installed
	# /bin/false will ignore any options/args, and just return bad status
	print false
    fi
}

# release version detection functions: installed_version, delivered_version
#
# These functions print a ReleaseNumber_BuildNumber to stdout that can be
# compared to determine newer/older as well as equality.
#

function installed_version {
   # Description:
   #    Print version string of an installed package, or 0
   #
   #    usage:  installed_version <rootdir> <pkgname>
   #
   # Parameters:
   #    $1 - base of installation image, or root BASEDIR for temp SUNWuti
   #    $2 - package name
   #
   # Globals used: none
    typeset iver
    typeset rootdir=$1
    typeset inst_pkg_name=$2
    typeset utprodinfo=$(getutprodinfo $rootdir)

    if iver="$($utprodinfo -p $inst_pkg_name VERSION 2>/dev/null)" ; then
       print ${iver%%,*}
   else
       print "0"
   fi
}

function delivered_version {
   # Description:
   #    Print version string of a package being delivered, or 0
   #
   #    usage:  delivered_version <path_to_package>
   #
   # Parameters:
   #    $1 - path to base of package/rpm
   #
   # Globals used: none
    typeset dver
    typeset pkg_loc=$1

    if [ $G_PLATFORM = SunOS ] ; then
	dver=$(sed -n 's/^VERSION=\([^,]*\),.*/\1/p' $pkg_loc/pkginfo)
    else
	dver=$(rpm -q --queryformat "%{Version}_%{Release}" -p $pkg_loc)
    fi
    
    if [ -n "$dver" ]; then
	print $dver
    else
	print "0"
    fi
}

# define some return values
G_COMPVER_EQ=0
G_COMPVER_GT=1
G_COMPVER_LT=2

function CompareVersion {
   # Description:
   #    Compare two version strings. The version string
   #    must be in the form <n>.<n>[.<n>] where "n" is an integer.
   #    Special provision is made for dealing with version strings of the form
   #    <n>.<n>[.<n>][.<a>] where "a" is alphanumeric. Such strings can be
   #    compared for equality. This allows for uninstallation.
   #
   #    usage:  CompareVersion <ver1> <ver2>
   #
   #    Returns:
   #    $G_COMPVER_EQ if $1 and $2 are the same
   #    $G_COMPVER_GT if $1 is newer than $2
   #    $G_COMPVER_LT if $2 is newer than $1
   #
   # Parameters:
   #    $1 and $2 - version strings to be compared
   #
   # Globals used:
   # G_COMPVER_EQ
   # G_COMPVER_GT
   # G_COMPVER_LT

    typeset r1=${1%%_*}
    typeset v1
    typeset done1=false
    typeset r2=${2%%_*}
    typeset v2
    typeset done2=false
    typeset res
    while /bin/true
    do
	v1=${r1%%.*}
	if [ $v1 = $r1 ]; then
	    r1="0"
	    done1=true
	else
	    r1=${r1#*.}
	fi
	v2=${r2%%.*}
	if [ $v2 = $r2 ]; then
	    r2="0"
	    done2=true
	else
	    r2=${r2#*.}
	fi
	# Deal with feature releases, which are not fully numeric and
	# thus can't be compared except for equality
	if [ "$v1" != "$v2" ]; then
	    let "res=v1-v2"
	    if [ $res -lt 0 ]; then
		# $1 < $2
		return $G_COMPVER_LT
	    elif [ $res -gt 0 ]; then
		# $1 > $2
		return $G_COMPVER_GT
	    fi
	fi
	if $done1 && $done2; then
	    # no more substring to compare
	    # this means match
	    break
	fi
    done
    return $G_COMPVER_EQ
}

function CompareFullVersion {
   # Description:
   #    Compare two version strings with build numbers (preceeded by
   #    an underscore). The version string must be in the form
   #    <n>.<n>[.<n>][_<n>.<x>] where "n" is an integer and "x" is
   #    arbitrary text (ignored) Special provision is made for dealing
   #    with version strings of the form <n>.<n>[.<n>][.<a>][_<n>.<x>]
   #    where "a" is alphanumeric. Such strings can be compared for
   #    equality. This allows for uninstallation.
   #
   #    usage:  CompareFullVersion <ver1> <ver2>
   #
   #    Returns:
   #    $G_COMPVER_EQ if $1 and $2 are the same
   #    $G_COMPVER_GT if $1 is newer than $2
   #    $G_COMPVER_LT if $2 is newer than $1
   #
   # Parameters:
   #    $1 and $2 - version strings to be compared
   #
   # Globals used:
   # G_COMPVER_EQ
    typeset STATUS v1 v2
    
    # Compare the version before any build number (build is preceeded by '_')
    CompareVersion ${1%%_*} ${2%%_*}
    STATUS=$? 

    # if equal, compare the build number, but discard any patch rev
    # patch rev on Linux is preceeded by '.'
    if [ "$STATUS" -eq "$G_COMPVER_EQ" ]; then
	v1=${1##*_}
	if [ "$v1" == "$1" ]; then
	    v1=0
	fi
	v2=${2##*_}
	if [ "$v2" == "$2" ]; then
	    v2=0
	fi
	CompareVersion ${v1%%.*} ${v2%%.*}
	STATUS=$?
    fi
    return $STATUS
}

# YesOrNo
# This is copied verbatim in SRCS
# src/server/admin/install/utfwuninstall.ksh and SRSS
# src/admin/install/support_lib/iu_lib.ksh and probably other
# places. It should be kept in sync with that source unless/until we
# find a way to share it.

# Ultimately we should find a better way to share this. Perhaps it
# should be driven by common source in install-support-lib which can
# then at least be copied around into different products (copied in
# order to avoid unattractive package dependencies)

# Note this function does *not* use utdialog and is not AIC compliant,
# so should only be used in situations where utdialog is not
# necessarily available. Like this one. Should it be enhanced to fall
# back on utdialog if present (in future)? Let's not enhance it until
# it's shared, at least, so we don't diverge.

function YesOrNo {
   # Description:
   #    prompt user for yes or no answer
   #    usage:  YesOrNo <prompt> <default value>
   #    Returns 0 if the user specified "Y" or "Yes" (case insensitive),
   #	nonzero otherwise.
   #
   # Parameters:
   #    $1 - PROMPT prefix
   #    $2 - default value "Y" or "N"
   #
   # Globals used:
   #    G_QUICK_INSTALL (optional)
   #    G_LOGFILE

   typeset PROMPT=""
   typeset DEFAULT=""
   typeset RESPONSE=""

   if [[ $# != 2 ]]; then
      return 1
   fi

   if [[ "$2" == "Y" ]]; then
      PROMPT="$1 ([Y]/N): "
      DEFAULT="Y"
   else
      PROMPT="$1 (Y/[N]): "
      DEFAULT="N"
   fi

   while true; do
      print -n "$PROMPT"

      case "$G_QUICK_INSTALL" in
        yes) RESPONSE="";;    # as if user only pressed Enter
        *)   read RESPONSE;;  # actually get user input
      esac
      print "$RESPONSE" >>$G_LOGFILE

      if [[ -z "$RESPONSE" ]]; then
        RESPONSE="$DEFAULT"  # empty response results in use of default
      fi

      case "$RESPONSE" in
	[Yy] | [Yy][Ee][Ss]) return 0;;
	[Nn] | [Nn][Oo])     return 1;;
      esac
   done
}

function ExitWithFSStatus {
   # Description:
   #    Store exit status into a status file, for use in determining
   #    exit status of a function whose output is piped. Caller must
   #    retrieve exit status from status file.
   #
   #    usage:  ExitWithFSStatus <status>
   #
   #    Exits with specified status after recording status in file.
   #
   #    Caller should arrange to clean up status file after use
   #
   # Parameters:
   #    $1 - exit status
   #
   # Globals used:
   #    G_STATUS_FILE
    
    echo $1 > $G_STATUS_FILE
    exit $1
}

function handle_install_pkg {
   # Description:
   #    Install specified package/rpm
   #
   #    usage:  handle_install_pkg <image_base> <pkgname> <pkg_dir>
   #
   # Parameters:
   #    $1 - base of installation image
   #    $2 - name of package to install
   #    $3 - path to directory containing package to install
   #    $4 - "verbose" iff installation should generate output
   #
   # Globals used:
   #    G_PLATFORM
   #    G_UNINSTALL

    typeset image_base install_pkg install_pkg_dir PKGADD_OUT STATUS
    
    image_base=$1
    install_pkg=$2
    install_pkg_dir=$3
    pkg_opts=

    if [ "$4" != "verbose" ]; then
	pkg_opts=-n
    fi

    case $G_PLATFORM in
	SunOS)
            if pkginfo -q $install_pkg; then
		pkgrm -n -a $image_base/.install/admin_default  $install_pkg 2>&1 | egrep -v 'was successful|^$'
            fi
	    if ! $G_UNINSTALL ; then
		PKGADD_OUT=$(pkgadd $pkg_opts -d $install_pkg_dir $install_pkg 2>&1)
		STATUS=$?
		if [ $install_pkg = "SUNWuti" ] ; then
		    print "$PKGADD_OUT"
		else
		    print "$PKGADD_OUT" | egrep -v 'was successful|^$|Copyright|license terms'
		fi
		if [ $STATUS != 0 ] ; then
		    ExitWithFSStatus $STATUS
		fi		
	    fi
            ;;
	Linux)
	    if rpm -q $install_pkg 1>/dev/null 2>&1; then
	        rpm -e --nodeps $install_pkg >/dev/null
     	    fi
	    if ! $G_UNINSTALL ; then		
		rpm -i --nodeps $install_pkg_dir/$install_pkg-[0-9]*.rpm >/dev/null
		STATUS=$?
		if [ $STATUS != 0 ] ; then
		    ExitWithFSStatus $STATUS
		fi		

	    fi	      
	    ;;
    esac
	
}
