#!/bin/bash -p
#
# ident "@(#)utpkgcheck.bash	1.26	13/01/14 Oracle"
#
# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
#

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

export LC_ALL=C

Prog=$(basename $0)
ProgDir=$(dirname $0)
case "${ProgDir%%/*}" in
	.|..) ProgDir=$(pwd)/$ProgDir;;
esac

function Usage {
    cat 1>&2 <<EOF
Usage: $Prog [options]
Options:
	-i	Install prerequisite packages
EOF
    if [ "$OS" == SunOS ]; then
	cat 1>&2 <<EOF
	-a	Indicate that you agree to and accept the terms of all
		    of the licenses for all of the packages to be
		    installed or updated
	-l	Display all of the licenses for all of the packages to be
		    installed or updated
EOF
    fi
}

function cleanup {
    rm -f $cd_repo_file $cd_repo_file_template
}

trap cleanup 0

OS=$(uname -s)

#
# Interface definition
# Every OS must implement the following functions:
#
# InitVars$OS
#    Any variable initialization belongs here
#    No arguments or status return
# InstallPreReqs$OS
#    The actual work of testing/installing prereqs belongs here
#    No arguments, return 0 on success
#
# This script will exit with the status return from InstallPreReqs$OS
#

# Begin Linux Functions (too bad you can't nest functions)

# Find the matching kernel*-devel RPM for the currently running kernel
# type and version.  Name returned will be first name specified to
# function which matches an installed RPM of the specified version
function MatchRPMVersion {
    typeset verstr
    typeset rpmspec

    verstr=$(uname -r)

    if [[ "${verstr%%el[56]uek*}" != "$verstr" ]]; then
	rpmspec=kernel-uek
    else
	rpmspec=kernel
    fi

    # Might be multiple versions of an rpm installed, test them all
    for rpm in $(rpm -q $rpmspec 2>/dev/null); do
	if [[ "${rpm#$rpmspec}" == "-$verstr" ]]; then
	    # Found a match - print it
	    echo $rpmspec $verstr
	    return
	fi
    done
}

function InitVarsLinux {
    typeset KernelRPM KernelVer
    
    repos_dir=/etc/yum.repos.d
    # Need to detect whether we are running a UEK kernel
    
    # Use bash 'Here String' functionality to read two variables
    # because pipe to read doesn't work like ksh
    read KernelRPM KernelVer <<< $(MatchRPMVersion)
    if [[ -z "$KernelRPM" ]]; then
	echo "$Prog: Error: Unrecognized kernel type '$(uname -r)'" 1>&2
	exit 2
    fi

    # Determine the appropriate 32-bit RPM label. For 5.x it's i386, else i686.
    # Check the coreutils OS RPM, look for a ".el5" component in the name
    # to identify 5.x. Sometimes it comes at the tail end (5.7), sometimes
    # earlier (5.8), unfortunately we can't constrain the pattern further.
    if rpm -q coreutils | grep "\.el5" >/dev/null; then
	Arch_32_Bit=i386
    else
	Arch_32_Bit=i686
    fi

    # We can drop the following code when we no longer support GDM 2.22- versions
    GDM_OLD=false
    GDM_VERSION=$(rpm -q --qf '%{VERSION}' gdm)
    GDM_VERSION_MAJOR=$(echo $GDM_VERSION | awk -F. '{print $1}')
    typeset -i GDM_VERSION_MINOR=$(echo $GDM_VERSION | awk -F. '{print $2}')
    if [[ $GDM_VERSION_MAJOR == 2 ]] && (( GDM_VERSION_MINOR < 22 )); then
	GDM_OLD=true
    fi

    # These are required RPMs for installs on OEL and RHEL 5.x and 6.x systems
    DEPENDENCIES=""
    DEPENDENCIES="${DEPENDENCIES} compat-openldap"
    DEPENDENCIES="${DEPENDENCIES} compat-openldap.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} dhcp"
    DEPENDENCIES="${DEPENDENCIES} gcc"
    DEPENDENCIES="${DEPENDENCIES} gdbm.$Arch_32_Bit"
    if ! $GDM_OLD; then
	DEPENDENCIES="${DEPENDENCIES} gdm-multiseat"
    fi
    DEPENDENCIES="${DEPENDENCIES} ksh"
    DEPENDENCIES="${DEPENDENCIES} libgcc.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libusb.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXcursor.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXfixes.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXfont.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXinerama.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXp.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXpm.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXtst.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} libXv.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} openldap-clients"
    DEPENDENCIES="${DEPENDENCIES} openmotif.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} pam.$Arch_32_Bit"
    DEPENDENCIES="${DEPENDENCIES} tftp"
    DEPENDENCIES="${DEPENDENCIES} tftp-server"
    DEPENDENCIES="${DEPENDENCIES} tk"
    DEPENDENCIES="${DEPENDENCIES} xorg-x11-fonts-misc"
    DEPENDENCIES="${DEPENDENCIES} ${KernelRPM}-devel-${KernelVer}"

}

function DoYum {
    typeset Missing_Dependencies=
    for pkg in $DEPENDENCIES; do
	if ! rpm -q --quiet $pkg; then
	    Missing_Dependencies="$Missing_Dependencies $pkg"
	fi
    done
    yum -y install $Missing_Dependencies

    # everything OK?
    rpm -q --quiet $DEPENDENCIES
}

function TryCustConfig {
    DoYum
}

function TryOurRepo {
    typeset PossibleRPMs RepoPath BaseURL
    
    PossibleRPMs=$(ls /media/*/Server/kernel-[0-9]*.$(uname -p).rpm 2>/dev/null)
    RepoPath=$(echo "$PossibleRPMs" \
	| awk -F/ '{print "/media/" $3 "/Server"}')
    if [[ ! -d "$RepoPath" ]]; then
	if (( $(echo "$PossibleRPMs" | wc -l) > 1 )); then
	    echo "$Prog: Error: Multiple OS installation DVDs detected" 1>&2
	else
	    echo "$Prog: Error: No OS installation DVD detected" 1>&2
	fi
	return 2
    fi
    BaseURL=$(Path2URL "$RepoPath")
    
    cd_repo_file_template=$(mktemp $repos_dir/ut_os.dvd.$$.XXX)
    cd_repo_file=${cd_repo_file_template}.repo
    mv $cd_repo_file_template $cd_repo_file

    # tabs must be preserved (or removed) in the inline text.
    # (i.e., don't substitute space chars for tabs)
    cat > $cd_repo_file <<- EOF
	[os-dvd]
	name=Oracle Linux
	baseurl=$BaseURL
	enabled=1
	gpgcheck=0
	EOF
    DoYum
}

function Path2URL {
    # For now, just percent-encode space characters.
    # Does yum require other characters to be encoded here? Unclear.
    # Note one slash comes in the argument, so the result is a proper URL
    echo "file://$1" | sed -e 's/%/%25/g' -e 's/ /%20/g'
}

function DoQuery {
    typeset -i STATUS
    
    # any dependent packages missing?
    RpmOutput=$(rpm -q $DEPENDENCIES)
    STATUS=$?

    if (( STATUS != 0 )); then
	echo "$RpmOutput" | grep "is not installed"
    else
	echo "All dependent packages are installed"
    fi
    return $STATUS
}

function InstallPreReqsLinux {
    # Install any dependencies
    typeset -i STATUS
    echo "Checking required dependent packages"

    DoQuery
    STATUS=$?

    if ! $DoInstall; then
	return $STATUS	# exit with DoQuery's status
    fi

    echo "Checking for updates"

    if ! TryCustConfig ; then

	echo "Packages not found in network repository, trying DVD"

	if ! TryOurRepo ; then

	    return 1
	fi
    fi

    # report unresolved dependencies
    if rpm -q $DEPENDENCIES | grep "not installed"; then
	    return 1
    else
	    return 0
    fi
}

# End Linux Functions

# Begin Solaris Functions

function InitVarsSunOS {
    :
}

function InstallPreReqsSunOS {
    typeset Status Depend
    if [[ "$(uname -r)" == "5.10" ]]; then
	# Can't do anything for S10
	echo "WARNING: Prerequisite packages must be manually installed for Solaris 10"
	echo "WARNING: See the Administration Guide for details"
	return 0
    fi

    if ! $DoInstall; then
	PkgOpts="-nv"
    fi
    pkg set-publisher -g ${ProgDir}/IPS.$(uname -p) sunray
    pkg install $PkgOpts SUNWut-extdeps
    Status=$?
    pkg unset-publisher sunray
    if $DoInstall && [[ "$(svcs -Ho STATE gdm)" != "online" ]]; then
	echo "WARNING: System must be rebooted in order to complete installation"
    fi
    return $Status
}

# End Solaris Functions

DoInstall=false
PkgFlags=

OSOPTS=i
if [ "$OS" == SunOS ]; then
    OSOPTS="${OSOPTS}al"
fi

while getopts $OSOPTS opt; do
    case $opt in
	a)	PkgFlags="${PkgFlags} --accept";;
	i)	DoInstall=true;;
	l)	PkgFlags="${PkgFlags} --license";;
	*)	Usage; exit 1;;
    esac
done

InitVars$OS
InstallPreReqs$OS
