#!/bin/ksh

###############################################
# Sourcing macros
###############################################
DIRNAME=/usr/bin/dirname
. `$DIRNAME $0`/../lib/psmacros

################################################################################
# Define the constants
################################################################################

OMIT_CHAR='\c'
BELL_CHAR='\a'

STATE_FILE="$PS_CONFIG_DIR/PSConfig.properties"

################################################################################
# Get configuration from specified file.
################################################################################

GrabConfig() {

    GRABCONFIG_FILE=$1
    GRABCONFIG_KEY=$2
    GRABCONFIG_SEPARATOR=$3

    ANSWER=`$GREP "^$GRABCONFIG_KEY$GRABCONFIG_SEPARATOR" $GRABCONFIG_FILE | $UNIQ | $SED -e "s/$GRABCONFIG_KEY$GRABCONFIG_SEPARATOR//"`

}

################################################################################
# Exit if non root user is executing this script
################################################################################

CheckUser() {

  if [ `$ID | $AWK '{print $1}'` != "uid=0(root)" ]; then
    $ECHO "You must be root user. $BELL_CHAR"
    exit 1
  fi

}

################################################################################
# Exit if state file in not present
################################################################################

CheckStateFile() {

  if [ ! -f $STATE_FILE ]; then
    $ECHO "Error: $STATE_FILE does not exist. $BELL_CHAR"
    exit 1
  fi

}

################################################################################
# Get the base directory
################################################################################

GetPSBaseDir() {

  GrabConfig $STATE_FILE "BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
    PS_BASEDIR=$ANSWER
    PS_LIB_PATH_PREFIX=$PS_BASEDIR/$PS_PRODUCT_DIR/lib
    PS_BIN_PATH_PREFIX=$PS_BASEDIR/$PS_PRODUCT_DIR/bin
  else
    $ECHO "Error: Cannot determine BASEDIR. $BELL_CHAR"
    exit 1
  fi

}

################################################################################
# Load the state file to memory.
################################################################################

LoadStateFile() {

  print "`$GETTEXT 'Reading the required informations for configuration...'`"

  # Get the configuration level
  GrabConfig $STATE_FILE "CONFIGURATION_LEVEL" "="
  if [ "$ANSWER" != "" ]; then
    CONFIGURATION_LEVEL=$ANSWER
  else
    $ECHO "Error: Cannot determine CONFIGURATION_LEVEL. $BELL_CHAR"
  fi

  # Get the deploy directory 
  GrabConfig $STATE_FILE "DEPLOY_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DIR=$ANSWER
    ASADMIN="$DEPLOY_DIR/bin/asadmin"
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy instance directory
  GrabConfig $STATE_FILE "DEPLOY_INSTANCE_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_INSTANCE_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_INSTANCE_DIR. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy domain(das) dir
  # Note: The DEPLOY_PRODUCT_DIR attribute is used to store the Domain DAS Dir
  # This is used to configure server.policy file since AS8.1 does not support
  # changing the server.policy file in the instance 
  # Note: if you are deploying to a domain then the domain path = instance path
  # i.e. DEPLOY_PRODUCT_DIR = DEPLOY_INSTANCE_DIR
  GrabConfig $STATE_FILE "DEPLOY_PRODUCT_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_PRODUCT_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DOMAIN DAS DIR. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy admin
  GrabConfig $STATE_FILE "DEPLOY_ADMIN" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_ADMIN=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_ADMIN. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy admin host
  GrabConfig $STATE_FILE "DEPLOY_ADMIN_HOST" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_ADMIN_HOST=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_ADMIN_HOST. $BELL_CHAR"
    exit 1
  fi
 
  # Get the deploy admin port
  GrabConfig $STATE_FILE "DEPLOY_ADMIN_PORT" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_ADMIN_PORT=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_ADMIN_PORT. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy instance 
  GrabConfig $STATE_FILE "DEPLOY_INSTANCE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_INSTANCE=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_INSTANCE. $BELL_CHAR"
    exit 1
  fi

  # Get the deployment document root
  GrabConfig $STATE_FILE "DEPLOY_DOCROOT" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DOCROOT=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DOCROOT. $BELL_CHAR"
    exit 1
  fi

  # Get the install time deployment document root
  GrabConfig $STATE_FILE "INSTALLTIME_DEPLOY_DOCROOT" "="
  INSTALLTIME_DEPLOY_DOCROOT=$ANSWER
 
  # Get the portal server port
  GrabConfig $STATE_FILE "PS_PORT" "="
  if [ "$ANSWER" != "" ]; then
    PS_PORT=$ANSWER
  else
    $ECHO "Error: Cannot determine PS_PORT. $BELL_CHAR"
    exit 1
  fi

  GrabConfig $STATE_FILE "IDSAME_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
    IDSAME_BASEDIR=$ANSWER
  else
    $ECHO "Error: Cannot determine IDSAME_BASEDIR. $BELL_CHAR"
    exit 1
  fi
  
  if [ "$DEPLOY_ADMIN_PASSWORD" == "" ]; then
    $ECHO "Error: Cannot determine DEPLOY_ADMIN_PASSWORD. $BELL_CHAR"
    exit 1
  fi 
}

################################################################################
# Update serverclasspath SunONE appserver
################################################################################

UpdateServerClasspath() {

 print "`$GETTEXT 'Adding path to the JAR files to classpath-suffix in server.xml'`"

 if [ $# -eq 0 ]; then
    print "$0:No arguments passed to UpdateServerClasspath()"
    return
 fi

 # Get the current classpath
 local CURRCP=`$ASADMIN get --user $DEPLOY_ADMIN --password $DEPLOY_ADMIN_PASSWORD --host $DEPLOY_ADMIN_HOST --port $DEPLOY_ADMIN_PORT $DEPLOY_INSTANCE.java-config.classpath-suffix | $NAWK ' BEGIN { FS="=" } { print $2 } '`
 if [ $? -eq 1 ]; then
   print "$0::Abnormal Termination(get-1)"
   exit 1
 fi

 CURRCP=`$ECHO $CURRCP| $SED "s/ *//"`
 local TO_ADD=""
 for TO_ADD in $*; do
    CURRCP="$CURRCP:$TO_ADD"
 done

 $ASADMIN set --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --host $DEPLOY_ADMIN_HOST --port $DEPLOY_ADMIN_PORT "$DEPLOY_INSTANCE.java-config.classpath-suffix=$CURRCP"
 if [ $? -eq 1 ]; then
   print "$0::Abnormal Termination(set-1)"
   exit 1
 fi

}

################################################################################
# Remove portalserver entriy from server.xml
################################################################################

RemoveEntry() {

  print "`$GETTEXT 'Removing portalserver entries from server.xml'`"

  if [ $# -eq 0 ]; then
    print "$0:No arguments passed to RemoveEntry()"
    return
  fi

  # Get the current classpath
  local CURRCP=`$ASADMIN get --user $DEPLOY_ADMIN --password $DEPLOY_ADMIN_PASSWORD --host $DEPLOY_ADMIN_HOST --port $DEPLOY_ADMIN_PORT $DEPLOY_INSTANCE.java-config.classpath-suffix | $NAWK ' BEGIN { FS="=" } { print $2 } '`
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(get-2)"
    exit 1
  fi

  local TO_REMOVE=""
  CURRCP="$CURRCP:"
  CURRCP=`$ECHO $CURRCP | $SED -e "s#:::*#:#g"`
  for TO_REMOVE in $*; do
     CURRCP=`$ECHO $CURRCP | $SED -e "s#$TO_REMOVE:##g"`
  done
  CURRCP="$CURRCP@"
  CURRCP=`$ECHO $CURRCP | $SED -e "s#:@##g"`
  CURRCP=`$ECHO $CURRCP | $SED -e "s#@##g"`
 
  $ASADMIN set --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --host $DEPLOY_ADMIN_HOST --port $DEPLOY_ADMIN_PORT "$DEPLOY_INSTANCE.java-config.classpath-suffix=$CURRCP"
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(set-2)"
    exit 1
  fi
}

################################################################################
# method to add MA specific mime types
################################################################################

AddMAMimeTypes() {

  print "`$GETTEXT 'Adding MA mime-types...'`"

}

################################################################################
# Configure the base portal.
################################################################################

ConfigureBasePortal() {

  print "`$GETTEXT 'Adding FilePermission to server.policy....'`"

  # Update server.policy file.
  FILE="$DEPLOY_PRODUCT_DIR/config/server.policy"
  $GREP "permission java.io.FilePermission \"\${/}-\"" $FILE | $GREP "read,write,execute,delete" > /dev/null
  if [ $? -ne 0 ]; then
    print "Need to add permission..."
    $CAT >> $FILE << EOF

// S1PS
grant {
  permission java.util.PropertyPermission "*", "read,write";
  permission java.lang.RuntimePermission "writeFileDescriptor";
  permission java.lang.RuntimePermission "createClassLoader";
  permission java.io.FilePermission "\${/}-", "read,write,execute,delete";
};

EOF
  fi

  # Set LD_LIBRARY_PATH
  print "`$GETTEXT 'Updating libpathprefix...'`"

  # Update native library path
  $ASADMIN set --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --host $DEPLOY_ADMIN_HOST --port $DEPLOY_ADMIN_PORT "$DEPLOY_INSTANCE.java-config.native-library-path-prefix=.:$PS_LIB_PATH_PREFIX"
  if [ $? -ne 0 ]; then
    print "$0::Abnormal Termination(set-3)"
    exit 1
  fi

  # Update serverclasspath with PS jars, MA jars, and MA locale directory.
  UpdateServerClasspath "$PS_LIB_PATH_PREFIX/container.jar" \
                        "$PS_LIB_PATH_PREFIX/psimapprovider.jar" \
                        "$PS_LIB_PATH_PREFIX/portletcommon.jar" \
                        "$PS_LIB_PATH_PREFIX/portletcontainercommon.jar" \
                        "$PS_LIB_PATH_PREFIX/portlet.jar" \
                        "$PS_LIB_PATH_PREFIX/portlettl.jar" \
                        "$PS_LIB_PATH_PREFIX/jdom.jar" \
                        "$MA_DIR/locale" \
                        "$MA_LIB_DIR/mobile_services.jar" \
                        "$MA_LIB_DIR/wireless_rendering_util.jar" \
                        "$MA_LIB_DIR/wireless_rendering.jar" \
                        "$MA_LIB_DIR/ccpp-1_0.jar" \
                        "$MA_LIB_DIR/ccpp-ri-1_0.jar" \
                        "$MA_LIB_DIR/jena-1.4.0.jar" \
                        "$MA_LIB_DIR/rdffilter.jar"

  # Add MA mime-types.
  AddMAMimeTypes

  # Copy MA (voice) files to document root directory.
  if [ "$INSTALLTIME_DEPLOY_DOCROOT" != "" ] && [ "$DEPLOY_DOCROOT" != "$INSTALLTIME_DEPLOY_DOCROOT" ]; then
    $CP -rf $INSTALLTIME_DEPLOY_DOCROOT/voice $DEPLOY_DOCROOT
  fi
  
}

################################################################################
# Configure SRA to web container.
################################################################################

ConfigureSRA() {

  print "`$GETTEXT 'Adding SocketPermission to server.policy...'`"

  # Update server.policy file
  FILE="$DEPLOY_PRODUCT_DIR/config/server.policy"
  $GREP "permission java.net.NetPermission \"*\"" $FILE | $GREP "specifyStreamHandler" > /dev/null
  if [ $? -ne 0 ]; then
    print "Need to add permission..."
    $CAT >> $FILE << EOF

// S1PS - SRA NetFile
grant {
  permission java.net.SocketPermission    "*", "connect,accept,listen,resolve";
  permission java.net.NetPermission "*", "specifyStreamHandler";
};
// END OF S1PS - SRA NetFile

EOF
  fi

}

###############################################################################
# Load IS Config Data
###############################################################################

GetISConfigData() {

  FILE="$IDSAME_CONFIG_DIR/config/AMConfig.properties"

  ADMIN_DN=`$GREP "^com.sun.identity.authentication.super.user=" $FILE | $SED -e "s/com.sun.identity.authentication.super.user=//"`
  ROOT_DN=`$GREP "^com.iplanet.am.rootsuffix=" $FILE | $SED -e "s/com.iplanet.am.rootsuffix=//"`
  ORG_DN=`$GREP "^com.iplanet.am.defaultOrg=" $FILE | $SED -e "s/com.iplanet.am.defaultOrg=//"`
  if [ "$ORG_DN" != "$ROOT_DN" ]; then
    ORG_DN="$ORG_DN,$ROOT_DN"
  fi

}

################################################################################
# Deploy the Portlets.
################################################################################

DeployPortlets() {

  print "`$GETTEXT 'Deploying Portlets...'`"

  GetISConfigData

  PORTLETDEPLOYER="$PS_BIN_PATH_PREFIX/pdeploy"

  if [ -x $PORTLETDEPLOYER ]; then

    FILE="$PS_CONFIG_DIR/portlet/userInfoMapping.properties"
    print "`$GETTEXT 'Loading'` /"$FILE/"..."
    eval $PORTLETDEPLOYER deploy -u "$ADMIN_DN" -w "${IDSAME_ADMIN_PASSWORD}" -p "${DEPLOY_ADMIN_PASSWORD}" -g -f $FILE -i $DEPLOY_INSTANCE "$PS_BASEDIR/$PS_PRODUCT_DIR/samples/portlet/original/portletsamples.war"

  fi

  print "`$GETTEXT 'Completed Deploying Portlets...'`"

}

###############################################
# UnDeploy the Portlets.
###############################################

UnDeployPortlets() {

  local NAME=$1

  print "`$GETTEXT 'Undeploying'` \"$NAME\"..."

  eval $DEPLOY_DIR/bin/asadmin undeploy --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --port $DEPLOY_ADMIN_PORT --host $DEPLOY_ADMIN_HOST --target $DEPLOY_INSTANCE $NAME

  if [ $? -ne 0 ]; then
    print "`$GETTEXT 'Possible error while undeploying'` \"$NAME\"..."
  else
    print "`$GETTEXT 'Completed Undeploying'` \"$NAME\"..."
  fi

}

################################################################################
#
# Configure the required components based on the CONFIGURATION_LEVEL.
# Possible levels - 
# 	01 : Configure BasePortal
#	02 : Configure BasePortal, and SRA
#
################################################################################

Configure() {

  print "`$GETTEXT 'Configuring core portal...'`"

  ConfigureBasePortal

  if [ "$CONFIGURATION_LEVEL" == "02" ]; then
    print "`$GETTEXT 'Configuring Secure Remote Access...'`"
    ConfigureSRA
  fi

  # Deploy the portalserver.
  print "`$GETTEXT 'Deploying portalserver...'`"
  print "`$GETTEXT 'Configuring Web Container...'`"
  $PS_LIB_PATH_PREFIX/wcconfig config -instance $DEPLOY_INSTANCE -deploy_admin_password $DEPLOY_ADMIN_PASSWORD
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(Configuring portalserver)"
    exit 1
  fi

  # Rebounce the server instance
  print "Stop instance \"$DEPLOY_INSTANCE\"..."
  eval $DEPLOY_DIR/bin/asadmin stop-instance --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --port $DEPLOY_ADMIN_PORT --host $DEPLOY_ADMIN_HOST $DEPLOY_INSTANCE

  print "Start instance \"$DEPLOY_INSTANCE\"..."
  eval $DEPLOY_DIR/bin/asadmin start-instance --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --port $DEPLOY_ADMIN_PORT --host $DEPLOY_ADMIN_HOST $DEPLOY_INSTANCE
  if [ $? -ne 0 ]; then
    print "$0:Abnormal Termination(start-instance-6)"
    exit 1
  fi
 
  print "`$GETTEXT 'Redeploying portalserver...'`"
  $PS_BIN_PATH_PREFIX/deploy redeploy -instance $DEPLOY_INSTANCE -deploy_admin_password $DEPLOY_ADMIN_PASSWORD
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(Redeploying portalserver)"
    exit 1
  fi

  # Configure search 
  print "`$GETTEXT 'Configuring search for portalserver...'`"
  $PS_LIB_PATH_PREFIX/searchconfig -is_admin_password "${IDSAME_ADMIN_PASSWORD}" -instance $DEPLOY_INSTANCE -port $PS_PORT
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(Configuring search for portal server)"
    exit 1
  fi

  # Deploy the portlets
  DeployPortlets

}

################################################################################
#
# Unconfigure portalserver.
#
################################################################################

UnConfigure() {

  # Undeploy the portlets.
  print "`$GETTEXT 'Undeploying Portlets...'`"

  GetISConfigData

  DIRS=`$LS $PS_VAR_DIR/tmp/portlet/*_portlet.xml`
  for DIR in $DIRS; do
    UnDeployPortlets `$BASENAME $DIR | $SED -e "s/_portlet.xml//"`
  done

  # Undeploy the portalserver.
  print "`$GETTEXT 'Undeploying portalserver...'`"
  $PS_BIN_PATH_PREFIX/undeploy undeploy -instance $DEPLOY_INSTANCE -deploy_admin_password ${DEPLOY_ADMIN_PASSWORD}
  if [ $? -eq 1 ]; then
    print "$0::Abnormal Termination(Undeploying portalserver)"
    exit 1
  fi

  # Remove PS jars & MA entries from classpathsuffix in server.xml
  RemoveEntry "$PS_LIB_PATH_PREFIX/container.jar" \
              "$PS_LIB_PATH_PREFIX/psimapprovider.jar" \
              "$PS_LIB_PATH_PREFIX/portletcommon.jar" \
              "$PS_LIB_PATH_PREFIX/portletcontainercommon.jar" \
              "$PS_LIB_PATH_PREFIX/portlet.jar" \
              "$PS_LIB_PATH_PREFIX/portlettl.jar" \
              "$PS_LIB_PATH_PREFIX/jdom.jar" \
              "$MA_DIR/locale" \
              "$MA_LIB_DIR/mobile_services.jar" \
              "$MA_LIB_DIR/wireless_rendering_util.jar" \
              "$MA_LIB_DIR/wireless_rendering.jar" \
              "$MA_LIB_DIR/ccpp-1_0.jar" \
              "$MA_LIB_DIR/ccpp-ri-1_0.jar" \
              "$MA_LIB_DIR/jena-1.4.0.jar" \
              "$MA_LIB_DIR/rdffilter.jar"

  # Remove the directories created by deploy and searchconfig
  $RM -rf $PS_VAR_DIR/https-$DEPLOY_INSTANCE
  $RM -rf $PS_VAR_DIR/SAVE-https-$DEPLOY_INSTANCE

  # Rebounce the server instance
  print "Stop instance \"$DEPLOY_INSTANCE\"..."
  eval $DEPLOY_DIR/bin/asadmin stop-instance --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --port $DEPLOY_ADMIN_PORT --host $DEPLOY_ADMIN_HOST $DEPLOY_INSTANCE

  print "Start instance \"$DEPLOY_INSTANCE\"..."
  eval $DEPLOY_DIR/bin/asadmin start-instance --user $DEPLOY_ADMIN --password "${DEPLOY_ADMIN_PASSWORD}" --port $DEPLOY_ADMIN_PORT --host $DEPLOY_ADMIN_HOST $DEPLOY_INSTANCE
  if [ $? -ne 0 ]; then
    print "$0:Abnormal Termination(start-instance-6)"
    exit 1
  fi

}

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

# Make sure root is executing this script.
CheckUser

# Set state file pointer.
if [ "$1" = "-s" ]; then 
  STATE_FILE=$2 
fi

# Make sure the state file is present
CheckStateFile

# Get the base directory.
GetPSBaseDir

# Load the state file to memory.
LoadStateFile

# Configure/Unconfigure the required components.
if [ "$CONFIGURATION_LEVEL" == "11" ]; then
  UnConfigure
else
  Configure
fi

exit 0

