#!/bin/sh
#	Copyright (c) 2005 Sun Microsystems, Inc.
#		All Rights Reserved
#
#	@(#)prepatch.sh 1.2 05/07/21 (c) Sun Microsystems, Inc.
#

# This checks for the various required patches.

OSRelease=`/usr/bin/uname -r | /usr/bin/sed s/\\\\.//`
OSArch=`/usr/bin/uname -p`

sparc_58_REQUIREDPATCHES="108987-12 110934-11"
i386_58_REQUIREDPATCHES="108988-12 110935-11"
sparc_59_REQUIREDPATCHES="112951-04 113713-02"
i386_59_REQUIREDPATCHES="114194-01 114568-02"

appliedPatchesFile="/tmp/appliedPatches.$$"
requiredPatches=""

exitCode="0"

#
# SunOS 5.8
if [ "${OSRelease}" = "58" ]; then
    /usr/sbin/patchadd -p | /usr/bin/nawk '
	    {
		idx = 4
		if ( length($0) == 0 ) {
		    next;
		}
		print $2
		obsoletes = $idx
		while ( obsoletes != "" && obsoletes != "Requires:" ) {
		    print obsoletes
		    idx = idx + 1
		    obsoletes = $idx
		};
	    }
	' > ${appliedPatchesFile}.tmp
    /usr/bin/sort -u ${appliedPatchesFile}.tmp > ${appliedPatchesFile}
    /usr/bin/rm ${appliedPatchesFile}.tmp
    if [ "${OSArch}" = "sparc" ]; then
	requiredPatches="${sparc_58_REQUIREDPATCHES}"
    elif [ "${OSArch}" = "i386" ]; then
	requiredPatches="${i386_58_REQUIREDPATCHES}"
    fi
elif [ "${OSRelease}" = "59" ]; then
    /usr/sbin/patchadd -p | /usr/bin/nawk '
	    {
		idx = 4
		if ( length($0) == 0 ) {
		    next;
		}
		print $2
		obsoletes = $idx
		while ( obsoletes != "" && obsoletes != "Requires:" ) {
		    print obsoletes
		    idx = idx + 1
		    obsoletes = $idx
		};
	    }
	' > ${appliedPatchesFile}.tmp
    /usr/bin/sort -u ${appliedPatchesFile}.tmp > ${appliedPatchesFile}
    /usr/bin/rm ${appliedPatchesFile}.tmp
    if [ "${OSArch}" = "sparc" ]; then
	requiredPatches="${sparc_59_REQUIREDPATCHES}"
    elif [ "${OSArch}" = "i386" ]; then
	requiredPatches="${i386_59_REQUIREDPATCHES}"
    fi
fi

for patchID in ${requiredPatches}; do
    basecode=`echo ${patchID} | cut -b1-6`
    version=`echo ${patchID} | cut -b8-9`
    version=`/usr/bin/expr ${version} + 0`
    ok=0
    matches=""

    matches=`/usr/bin/egrep ${basecode} ${appliedPatchesFile}`

    for pid in ${matches}; do
	thisVersion=`echo ${pid} | cut -b8-9`
	thisVersion=`/usr/bin/expr ${thisVersion} + 0`
	if [ ${thisVersion} -ge ${version} ]; then
	    ok=1
	fi
    done

    if [ ${ok} -eq 0 ]; then
	echo "Error. This patch cannot be applied because it requires"
	echo "patch ID ${patchID} which is not applied."
	exitCode=1
	break
    fi
done
	
rm ${appliedPatchesFile}

exit ${exitCode}

