#!/bin/ksh

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

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

BELL_CHAR='\a'

STATE_FILE="$PS_CONFIG_DIR/PSConfig.properties"

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

  ANSWER=`$GREP "^$KEY$SEPARATOR" $FILE | $UNIQ | $SED -e "s/$KEY$SEPARATOR//"`
}

###############################################
# Replace matching lines in file
###############################################
ReplaceMatchingLine() {
  local FILE=$1
  local MATCH=$2
  local TEXT=$3

  $CP $FILE $FILE-tmp || exit 1
  $SED -e "/$MATCH/ {
c\\
$TEXT
}" $FILE-tmp > $FILE
  $RM $FILE-tmp
}


################################################################################
# Update weblogic classpath
################################################################################

UpdateWebLogicClassPath() {

  local STR=$1
  FILES="$DEPLOY_DIR/$DEPLOY_PROJECT_DIR/domains/$DEPLOY_DOMAIN/startWebLogic.sh $DEPLOY_DIR/$DEPLOY_PROJECT_DIR/domains/$DEPLOY_DOMAIN/startManagedWebLogic.sh"
  for FILE in $FILES; do
    $GREP "$STR" $FILE > /dev/null
    if [ $? -ne 0 ]; then
      $GREP "CLASSPATH=\"" $FILE > /dev/null
      if [ $? -ne 0 ]; then
        AppendLine $FILE "SERVER_NAME=" "CLASSPATH=\"$STR:\$CLASSPATH\""
      else 
        $CP $FILE $FILE-tmp
        $SED -e "s#CLASSPATH=\"#CLASSPATH=\"$STR:#" $FILE-tmp > $FILE
        $RM -f $FILE-tmp
      fi
    fi
  done

}

###############################################################
# Update WebSphereClasspath
###############################################################

UpdateWebSphereClassPath() {

  local STR=$1
	  
  FILE=$DEPLOY_DIR/config/cells/$DEPLOY_CELL/nodes/$DEPLOY_NODE/servers/$DEPLOY_INSTANCE/server.xml
  $GREP "$STR" $FILE > /dev/null
  if [ $? -ne 0 ]; then
      $GREP "<classpath>" $FILE > /dev/null
      if [ $? -ne 0 ]; then
	$GREP "<\/jvmEntries>" $FILE > /dev/null
	if [ $? -ne 0 ]; then
	  JVM_ENTRIES=`$GREP "<jvmEntries" $FILE | $SED -e "s#\/##g"`
          DeleteLine $FILE "<jvmEntries"
          AppendLine $FILE "<monitoringPolicy" "$JVM_ENTRIES"
	  AppendLine $FILE "<jvmEntries" "<classpath>$STR</classpath>"
	  AppendLine $FILE "<\/classpath>" "</jvmEntries>"
        else
	  AppendLine $FILE "<jvmEntries" "<classpath>$STR</classpath>"
        fi
      else 
        $CP $FILE $FILE-tmp
        $SED -e "s#<classpath>#<classpath>$STR:#" $FILE-tmp > $FILE
        $RM -f $FILE-tmp
      fi
  fi

}

###############################################
# Append line in file
###############################################
AppendLine() {
  local FILE=$1
  local MATCH=$2
  local TEXT=$3

  $CP $FILE $FILE-tmp || exit 1
  $SED -e "/$MATCH/ {
a\\
$TEXT
}" $FILE-tmp > $FILE
  $RM $FILE-tmp
}

###############################################
# Delete line in file
###############################################
DeleteLine() {
  local FILE=$1
  local MATCH=$2

  $CP -p $FILE $FILE-tmp || exit 1
  $SED -e "/$MATCH/d" $FILE-tmp > $FILE
  $RM $FILE-tmp
}

#
#  TODO:  This is a temporary hack until WS and AS deploy
#  operate in a synchronous fashion.
#
# Wait for CPU(s) to go mostly idle...
WaitForIdle() {
  echo ".......Waiting for CPU to go mostly idle........."
  TOTALCALMCOUNT=0
  CALMCOUNT=0
  CALMLIMIT=3
  TOTALCALMLIMIT=30

  IDLEFN=""

  if [ "$OSTYPE" = "Linux" ]
  then
    IDLEFN='$16'
  fi
                                                                                
  if [ "$OSTYPE" = "SunOS" ]
  then
    IDLEFN='$22'
  fi

  $TEST -n "$IDLEFN" && $VMSTAT 1 2>&1 | while read V
  do
    IDLE=`$ECHO $V | $SED '/swap/d;/free/d;/memory/d' | $AWK "{ print $IDLEFN }"`

    if [ -z "$IDLE" ]
    then
      continue
    fi

    $EXPR $IDLE \< 91 >/dev/null && CALMCOUNT=0
    CALMCOUNT=`$EXPR $CALMCOUNT + 1`
    TOTALCALMCOUNT=`$EXPR $TOTALCALMCOUNT + 1`
    if [ $CALMCOUNT -gt $CALMLIMIT -o $TOTALCALMCOUNT -gt $TOTALCALMLIMIT ]
    then
      break
    fi
  done

  echo "..................... Done! ....................."
}

WaitForIdle


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

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

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

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

if [ "$DEPLOY_TYPE" = "SUNONE" ]; then
  GrabConfig $STATE_FILE "DEPLOY_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_DOMAIN" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DOMAIN=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DOMAIN. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_INSTANCE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_INSTANCE=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_INSTANCE. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_ADMIN" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_ADMIN=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_ADMIN. $BELL_CHAR"
    exit 1
  fi
  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
elif [ "$DEPLOY_TYPE" = "WEBLOGIC" ]; then 
  GrabConfig $STATE_FILE "DEPLOY_PROJECT_DIR" "="
  if [ "$ANSWER" != "" ]; then
     DEPLOY_PROJECT_DIR=$ANSWER
  else
     DEPLOY_PROJECT_DIR="user_projects"
  fi
  GrabConfig $STATE_FILE "DEPLOY_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_DOMAIN" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DOMAIN=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DOMAIN. $BELL_CHAR"
    exit 1
  fi
elif [ "$DEPLOY_TYPE" = "WEBSPHERE" ]; then
  GrabConfig $STATE_FILE "DEPLOY_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_NODE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_NODE=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_NODE. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_CELL" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_CELL=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_CELL. $BELL_CHAR"
    DEPLOY_CELL=$DEPLOY_NODE
  fi
  GrabConfig $STATE_FILE "DEPLOY_INSTANCE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_INSTANCE=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_INSTANCE. $BELL_CHAR"
    exit 1
  fi
else 
  GrabConfig $STATE_FILE "DEPLOY_DIR" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_DIR=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_DIR. $BELL_CHAR"
    exit 1
  fi
  GrabConfig $STATE_FILE "DEPLOY_INSTANCE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_INSTANCE=$ANSWER
  else
    $ECHO "Error: Cannot determine DEPLOY_INSTANCE. $BELL_CHAR"
    exit 1
  fi
  
fi
GrabConfig $STATE_FILE "DEPLOY_DOCROOT" "="
if [ "$ANSWER" != "" ]; then
  DEPLOY_DOCROOT=$ANSWER
else
  $ECHO "Error: Cannot determine DEPLOY_DOCROOT. $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
GrabConfig $STATE_FILE "BASEDIR" "="
if [ "$ANSWER" != "" ]; then
  PS_BASEDIR=$ANSWER
else
  $ECHO "Error: Cannot determine BASEDIR. $BELL_CHAR"
  exit 1
fi


#
# Update desktop help
#

DESKTOP_DIR="$PS_BASEDIR/$PS_PRODUCT_DIR/web-src/docs/en/desktop"
WIRELESS_DIR="$PS_BASEDIR/$PS_PRODUCT_DIR/web-src/docs/en/wireless"
if [ -d $DESKTOP_DIR ] && [ -d $WIRELESS_DIR ]; then
  $CP -r $DESKTOP_DIR $DESKTOP_DIR.save_by_wireless
  CURRENT_DIR=`$PWDCMD`
  cd $WIRELESS_DIR
  $FIND . -type f | while read FILE; do
    if [ -f "$DESKTOP_DIR/$FILE" ]; then
      $DIFF $FILE $DESKTOP_DIR/$FILE > /dev/null
      if [ $? -eq 1 ]; then
	$CP -p $FILE $DESKTOP_DIR/$FILE
	$INSTALLF SUNWpsoh $DESKTOP_DIR/$FILE
      fi
    else
      $CP -p $FILE $DESKTOP_DIR/$FILE
      $INSTALLF SUNWpsoh $DESKTOP_DIR/$FILE
    fi
  done
  $INSTALLF -f SUNWpsoh

  $RM -rf $PS_BASEDIR/$PS_PRODUCT_DIR/web-src/docs/desktop
  $CP -r $DESKTOP_DIR $PS_BASEDIR/$PS_PRODUCT_DIR/web-src/docs

  cd $CURRENT_DIR
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
}



#
# Place common MA components that must be deployed (from SUNWma) in PS staging area...
#
DEPLOY_JARFILES="mobile_filter.jar"

#TODO:  disable until BEA fix
#for JARFILE in $DEPLOY_JARFILES
#do
  #$CP $MA_LIB_DIR/$JARFILE $PS_BASEDIR/$PS_PRODUCT_DIR/web-src/WEB-INF/lib/$JARFILE
#done



#
# Build a classpath that refs common MA components (from SUNWma)...
#
GLOBAL_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"

WCLASSPATH=$SUNMALOCALEDIR
for JARFILE in $GLOBAL_JARFILES
do
  WCLASSPATH=$WCLASSPATH:$MA_LIB_DIR/$JARFILE
done


#
# Perform Sun One Web Server specific configuration...
#
if [ "$DEPLOY_TYPE" == "IWS" ]; then

  #
  # Modify server.xml
  #
  FILE="$DEPLOY_DIR/https-$DEPLOY_INSTANCE/config/server.xml"

  # Update classpathsuffix

  #step1: grep for classpath suffix in server.xml
  classpath=`$GREP classpathsuffix $FILE`
  $ECHO "Original classpath is $classpath"

  #step2: Add our classpath to the existing Classpathsuffix in server.xml
  count=1
  newline=""
  currentToken=`$ECHO $classpath | $CUT -f$count -d " "`
  while [ -n "$currentToken" ]; do
    $ECHO "currentToken is $currentToken"
    classpathToken=`$ECHO $currentToken | $GREP "classpathsuffix"`

    if [ "$classpathToken" != "" ]; then
      $ECHO "classpathToken is $classpathToken"
      classpathToken=`$ECHO $classpathToken | $CUT -f2 -d "\"" `

      $ECHO $classpathToken | $EGREP -s "$MA_LIB_DIR"

      if [ $? -ne 0 ]
      then
        WRLS_CLASSPATH=$WCLASSPATH
      fi

      if [ "$WRLS_CLASSPATH" != "" ]; then
        classpathToken="$classpathToken:$WRLS_CLASSPATH"
      fi

      # add "" around the classpathsuffix
      classpathToken="\"$classpathToken\""

      $ECHO "classpath after appending is $classpathToken"

      classpathsuffix="classpathsuffix=$classpathToken"
      newline="$newline $classpathsuffix"
    else
      newline="$newline $currentToken"
    fi
    count=`expr $count + 1`
    currentToken=`$ECHO $classpath | $CUT -f$count -d " "`
  done

  $ECHO "classpathsuffix is $classpathsuffix"
  $ECHO
  $ECHO "old line is $classpath"
  $ECHO
  $ECHO "new line is $newline"

  ReplaceMatchingLine $FILE classpathsuffix "$newline"

  $ECHO FILE=$FILE
  cp $FILE /tmp/server.xml.DEBUG

  #
  # update mime.types...
  #
  FILE="$DEPLOY_DIR/https-$DEPLOY_INSTANCE/config/mime.types"
  AddMimeTypes $FILE





elif [ "$DEPLOY_TYPE" = "SUNONE" ]; then

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

  #
  # 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 "$instance"

  #
  # Do all the changes that manually edit the server configuration first
  # and call reconfig with --keepmanualchanges=true to keep these changes.
  #
  # 1. update mime.types
  #
  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

  $ECHO "Executing asadmin reconfig with --keepmanualchanges=true on $instance"
  $ECHO "    to sync all manual changes"
  $ASADMIN reconfig -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT --keepmanualchanges=true "$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 "$MA_LIB_DIR"

  if [ $? -ne 0 ]
  then
    java_classpath="$java_classpath:$WCLASSPATH"
    $ASADMIN set -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT "$java_cp_property=$java_classpath"
  fi

  $ECHO "Executing asadmin reconfig with --keepmanualchanges=false on $instance"
  $ASADMIN reconfig -u $DEPLOY_ADMIN -w "${DEPLOY_ADMIN_PASSWORD}" -p $DEPLOY_ADMIN_PORT --keepmanualchanges=false "$instance"

  $ECHO "Executing asadmin restart-instance $instance"
  $ASADMIN restart-instance "$instance"





elif [ "$DEPLOY_TYPE" = "WEBLOGIC" ]; then
  UpdateWebLogicClassPath "$MA_DIR/locale"
  for JARFILE in $GLOBAL_JARFILES
  do
    UpdateWebLogicClassPath "$MA_LIB_DIR/$JARFILE"
  done
elif [ "$DEPLOY_TYPE" = "WEBSPHERE" ]; then
  UpdateWebSphereClassPath "$MA_DIR/locale"
  for JARFILE in $GLOBAL_JARFILES
  do
    UpdateWebSphereClassPath "$MA_LIB_DIR/$JARFILE"
  done
fi

VOICE_DIR=$PS_BASEDIR/$PS_PRODUCT_DIR/export/voice
if [ -d $VOICE_DIR ] && [ -d $DEPLOY_DOCROOT ]; then
  $CP -rp $VOICE_DIR $DEPLOY_DOCROOT
fi

exit 0
