#!/bin/ksh

#####################################
# Defines
#####################################

STATE_FILE="${ROOTDIR}/etc/opt/SUNWps/PSConfig.properties"
PROXYLET_PACKAGES="SUNWpsplt_pkg"
PROXYLET_CONFIG_PACKAGE="SUNWpspltconfig_pkg"

###############################################
# Get configuration from file
###############################################
GrabConfig() {
  FILE="$1"
  KEY="$2"
  SEPARATOR="$3"

  ANSWER=`/usr/bin/grep "^$KEY$SEPARATOR" $FILE | /usr/bin/uniq | /usr/bin/sed -e "s/$KEY$SEPARATOR//"`
}

#####################################
# Add package
#####################################
AddPackage() {
  PACKAGES="$1"
  BASEDIR="$2"

  RESPONSE_FILE=/tmp/"$PatchNum"_response_"$$"
  ADMIN_FILE=/tmp/"$PatchNum"_admin_"$$"
  PACKAGE_DIR="$patchdir"

  /usr/bin/cat > $RESPONSE_FILE << EOF
BASEDIR=$BASEDIR
IDSAME_BASEDIR=$IDSAME_BASEDIR
EOF

  /usr/bin/cat > $ADMIN_FILE << EOF
mail=
instance=unique
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=quit
setuid=nocheck
conflict=nocheck
action=nocheck
EOF

  for PACKAGE in $PACKAGES; do
    TEST_PACKAGE=`/usr/bin/echo $PACKAGE | /usr/bin/sed -e 's/_pkg//'`
    /usr/bin/pkginfo -R ${ROOTDIR} -q $TEST_PACKAGE
    if [ $? -ne 0 ]; then
      /usr/bin/echo "Adding $PACKAGE at $BASEDIR..."
      /usr/sbin/pkgadd -n -R ${ROOTDIR} -r $RESPONSE_FILE -a $ADMIN_FILE -S -d $PACKAGE_DIR/$PACKAGE all
      if [ $? != 0 ]; then
	/usr/bin/echo "$PACKAGE failed to install!"
	exit 1
      fi
    fi
  done
  /usr/bin/rm -f $ADMIN_FILE $RESPONSE_FILE
}

#####################################
# Main
#####################################

if [ ! -f $STATE_FILE ]; then
  /usr/bin/echo "Error: $STATE_FILE does not exist."
  exit 1
fi

GrabConfig $STATE_FILE "BASEDIR" "="
if [ "$ANSWER" != "" ]; then
  PS_BASEDIR=$ANSWER
else
  /usr/bin/echo "Error: Cannot determine BASEDIR."
  exit 1
fi
GrabConfig $STATE_FILE "IDSAME_BASEDIR" "="
if [ "$ANSWER" != "" ]; then
  IDSAME_BASEDIR=$ANSWER
else
  /usr/bin/echo "Error: Cannot determine IDSAME_BASEDIR."
  exit 1
fi

AddPackage "$PROXYLET_PACKAGES" "$PS_BASEDIR"
AddPackage "$PROXYLET_CONFIG_PACKAGE" "/"

exit 0

