#!/bin/sh

# Copyright (c) 2005 by Sun Microsystems, Inc.
# All rights reserved

# postpatch script to correct the corrupted pkgmap files

# Global declarations
CP=/usr/bin/cp
MV=/usr/bin/mv
LS=/usr/bin/ls
GETTEXT=/usr/bin/gettext
NAWK=/usr/bin/nawk
AWK=/usr/bin/awk
SED=/usr/bin/sed
CAT=/usr/bin/cat
CUT=/usr/bin/cut
GREP=/usr/bin/grep
EGREP=/usr/bin/egrep
RM=/usr/bin/rm
PKGPATH=${ROOTDIR}/var/sadm/pkg
SPOOLPATH=/save/pspool
pkg=SUNWpkgcmdsu
TMP=/tmp/pkgmap.tmp.$$
PKGCOND=/usr/bin/pkgcond

CheckZones()
{
        if [ -x /usr/bin/zonename ]; then
                ZONENAME=`/usr/bin/zonename`
                if [ ${ZONENAME} = "global" ]; then
                        GLOBAL_ZONE=true
                else
                        GLOBAL_ZONE=false
                fi
        else
                # Unable to determine zone
                GLOBAL_ZONE=true
        fi
}

LocalZones()
{
# Any local zone stuff here,
# typically this fuction is not used
        return 0
}


ExecuteALLCmds()
{
pkgmap=$PKGPATH/$pkg/$SPOOLPATH/$pkg/pkgmap
# bug 6328091, are we in a jumpstart with patchadd -C?
if [ ! -f $PKGPATH/$pkg/$SPOOLPATH/$pkg/pkgmap ]; then
     return 0
fi
$CP $pkgmap $PKGPATH/$pkg/$SPOOLPATH/$pkg/pkgmap.bak
EXPR=`egrep -e "^?+( l)" $pkgmap`
if [ "$EXPR" != "" ]; then
	EXPR=`egrep -e "^?+( l)" $pkgmap | $AWK -F= -e '{print $1}' | $AWK -e 'BEGIN { ORS="|" } {print $1" f "$3" "$4}'`
	egrep -v -e "$EXPR" $pkgmap >> $TMP
	$CP $TMP $pkgmap
	$RM $TMP
fi

}

determine_pkgcond () {

  if $PKGCOND  is_whole_root_nonglobal_zone > /dev/null 2>&1 ; then
      # Execute non-global whole root zone commands.
      # Should be same action as the default action.
      return 0
  fi

  if $PKGCOND  is_nonglobal_zone > /dev/null 2>&1 ; then
      # Execute non-global zone commands. Should be no action here
      return 0
  fi

  if $PKGCOND is_netinstall_image > /dev/null 2>&1 ; then
      # Execute commands applicable to patching the mini-root.
      # There are usually no actions to take here since your patching
      # the mini-root on an install server.
      return 0
  fi

  if $PKGCOND is_mounted_miniroot > /dev/null 2>&1 ; then
      # Execute commands specific to the mini-root
      return 0
  fi

  if $PKGCOND is_diskless_client > /dev/null 2>&1 ; then
      # Execute commands specific to diskless client
      return 0
  fi

  if $PKGCOND is_alternative_root > /dev/null 2>&1 ; then
      # Execute commands specific to an alternate root
      ExecuteALLCmds
      return 0
  fi

  if $PKGCOND is_global_zone > /dev/null 2>&1 ; then
      # In a global zone and system is mounted on /.
      # Execute all commands.
      ExecuteALLCmds
      return 0
  fi

}

# Main

ZONENAME=global

[ -x /sbin/zonename ] && ZONENAME=`/sbin/zonename`

if [ -x $PKGCOND ] ; then
  determine_pkgcond && exit 0 || exit 1
else
  CheckZones
  if [ "${GLOBAL_ZONE}" = "true" ]; then
       ExecuteALLCmds
  else 
       LocalZones
  fi 
fi
exit 0 
