#!/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
  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
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi

  # Get the deploy domain
  GrabConfig $STATE_FILE "DEPLOY_DOMAIN" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DOMAIN=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DOMAIN. $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 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 'Updating serverclasspath with '` $1"

  local STR=$1
  local FILE=""

  FILE="$DEPLOY_DOMAIN/$DEPLOY_INSTANCE/config/server.xml"
  $GREP "$STR" $FILE > /dev/null
  if [ $? -ne 0 ]; then
    $CP $FILE $FILE-tmp
    $SED -e "s#server-classpath=\"#server-classpath=\"$STR:#" $FILE-tmp > $FILE
    $RM -f $FILE-tmp
  fi

}

################################################################################
# Update classpathsuffix SunONE appserver
################################################################################

UpdateClasspathSuffix() {

  print "`$GETTEXT 'Updating classpathsuffix with '` $1"

  local STR=$1
  ASADMIN="$DEPLOY_DIR/bin/asadmin"
  instance=$DEPLOY_INSTANCE

  #
  # Modify server.xml
  #
  java_cp_property=$instance.java-config.classpathsuffix
  java_classpath=`$ASADMIN get -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT $java_cp_property | $CUT -d "=" -f 2 | $SED -e "s/ //g" `

  $ECHO $java_classpath | $EGREP -s "$STR"
  if [ $? -ne 0 ]; then
    java_classpath="$java_classpath:$STR"
    $ASADMIN set "$java_cp_property=$java_classpath" -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT
  fi

}

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

RemoveEntry() {

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

  local STR=$1
  local FILE=""

  FILE="$DEPLOY_DOMAIN/$DEPLOY_INSTANCE/config/server.xml"
  $SED -e "s#$STR:##g" $FILE > $FILE-tmp
  if [ -s $FILE-tmp ]; then
    $MV $FILE-tmp $FILE
  fi

}

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

AddMAMimeTypes() {

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

  ASADMIN="$DEPLOY_DIR/bin/asadmin"
  instance=$DEPLOY_INSTANCE
  CONFIG_DIR="$DEPLOY_DOMAIN/$instance/config"

  mime_id=`$ASADMIN list-mimes -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT $instance`

  if [[ ($? -eq 0) && (! -z $mime_id) ]]; then
    mime_file_property="$instance.mime.$mime_id.file"
    mime_file=`$ASADMIN get -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT $mime_file_property | $CUT -d "=" -f 2 | $SED -e "s/ //g" `

    if [[ ! -z $mime_file ]]; then
      FILE="$CONFIG_DIR/$mime_file"
      AddMimeTypes $FILE
    fi
  fi
}

################################################################################
# method to add mime types
################################################################################

AddMimeTypes() {

  MIME_TYPES_FILE=$1

  MIME_TYPES="type=text/vnd.wap.wml type=image/vnd.wap.wbmp"
  set -A MIME_TYPE_EXTS exts=wml exts=wbmp

  export j=0
  for MIME_TYPE in ${MIME_TYPES}; do
    $GREP ${MIME_TYPE} $MIME_TYPES_FILE > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      MIME_TYPE_DEFN="${MIME_TYPE}        ${MIME_TYPE_EXTS[j]}"
      $ECHO "Adding '${MIME_TYPE_DEFN}' in ${MIME_TYPES_FILE}"
      $ECHO "${MIME_TYPE_DEFN}" >> ${MIME_TYPES_FILE}
    else
      $ECHO "Mime type: '${MIME_TYPE}' already exists: Skipping ...."
    fi

    ((j=j+1))
  done

}

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

ConfigureBasePortal() {

  ASADMIN="$DEPLOY_DIR/bin/asadmin"
  
  # Run a reconfig with --keepmanualchanges=true so our configuration doesn't fail
  $ASADMIN reconfig -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT --keepmanualchanges=true "$DEPLOY_INSTANCE"

  print "`$GETTEXT 'Updating server.policy....'`"

  # Update server.policy file.
  FILE="$DEPLOY_DOMAIN/$DEPLOY_INSTANCE/config/server.policy"
  $GREP "permission java.io.FilePermission \"\${/}-\"" $FILE | $GREP "read,write,execute,delete" > /dev/null
  if [ $? -ne 0 ]; then
    $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 libpathsuffix...'`"

  $ASADMIN set "$DEPLOY_INSTANCE.java-config.libpathprefix=.:$PS_BASEDIR/$PS_PRODUCT_DIR/lib" -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT

  # Update serverclasspath
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/container.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/psimapprovider.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portletcommon.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portletcontainercommon.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portlet.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portlettl.jar"
  UpdateServerClasspath "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/jdom.jar"

  # Update classpathsuffix with MA jars and MA locale directory. 
  UpdateClasspathSuffix "$MA_DIR/locale"
  local MA_JARFILES="mobile_services.jar wireless_rendering_util.jar wireless_rendering.jar ccpp-1_0.jar ccpp-ri-1_0.jar jena-1.4.0.jar rdffilter.jar"
  for MA_JARFILE in $MA_JARFILES; do
    UpdateClasspathSuffix "$MA_LIB_DIR/$MA_JARFILE"
  done

  # 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
  
  # Run reconfig with --keepmanualchanges=true on instance
  $DEPLOY_DIR/bin/asadmin reconfig -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT --keepmanualchanges=true $DEPLOY_INSTANCE

}

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

ConfigureSRA() {

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

      FILE="$DEPLOY_DOMAIN/$DEPLOY_INSTANCE/config/server.policy"
      $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

}

###############################################################################
# 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_BASEDIR/$PS_PRODUCT_DIR/bin/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 -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT -H $DEPLOY_ADMIN_HOST --instance $DEPLOY_INSTANCE --type web $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...'`"
  $PS_BASEDIR/$PS_PRODUCT_DIR/lib/wcconfig config -instance $DEPLOY_INSTANCE -deploy_admin_password $DEPLOY_ADMIN_PASSWORD
  $PS_BASEDIR/$PS_PRODUCT_DIR/bin/deploy redeploy -instance $DEPLOY_INSTANCE -deploy_admin_password $DEPLOY_ADMIN_PASSWORD

  # Configure search 
  print "`$GETTEXT 'Configuring search...'`"
  $PS_BASEDIR/$PS_PRODUCT_DIR/lib/searchconfig -is_admin_password "${IDSAME_ADMIN_PASSWORD}" -instance $DEPLOY_INSTANCE -port $PS_PORT

  # Deploy the portlets
  DeployPortlets

}

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

UnConfigure() {

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

  GetISConfigData

  PORTLETDEPLOYER="$PS_BASEDIR/$PS_PRODUCT_DIR/bin/pdeploy"

  if [ -x $PORTLETDEPLOYER ]; then
    DIRS=`$LS $PS_VAR_DIR/tmp/portlet/*_portlet.xml`
    for DIR in $DIRS; do
      UnDeployPortlets `$BASENAME $DIR | $SED -e "s/_portlet.xml//"`
    done
  fi

  # Undeploy the portalserver.
  print "`$GETTEXT 'Undeploying portalserver...'`"
  $PS_BASEDIR/$PS_PRODUCT_DIR/bin/undeploy undeploy -instance $DEPLOY_INSTANCE -deploy_admin_password ${DEPLOY_ADMIN_PASSWORD}

  # Remove PS jars from classpath in server.xml
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/container.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/psimapprovider.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portletcommon.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portletcontainercommon.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portlet.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/portlettl.jar"
  RemoveEntry "$PS_BASEDIR/$PS_PRODUCT_DIR/lib/jdom.jar"

  # Remove MA entries from classpathsuffix in server.xml
  RemoveEntry "$MA_DIR/locale"
  local MA_JARFILES="mobile_services.jar wireless_rendering_util.jar wireless_rendering.jar ccpp-1_0.jar ccpp-ri-1_0.jar jena-1.4.0.jar rdffilter.jar"
  for MA_JARFILE in $MA_JARFILES; do
    RemoveEntry "$MA_LIB_DIR/$MA_JARFILE"
  done

  # Run reconfig with --keepmanualchanges=true on instance
  $DEPLOY_DIR/bin/asadmin reconfig -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT --keepmanualchanges=true $DEPLOY_INSTANCE

  # 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

}

################################################################################
# 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

