#!/bin/ksh

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

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

# AMConfig.properies key names.

AMCONFIG_ORG_DN="com.iplanet.am.defaultOrg"
AMCONFIG_AMSERVER="com.iplanet.am.services.deploymentDescriptor"
AMCONFIG_PASSWORD_KEY="am.encryption.pwd"

# State files.

PS_STATE_FILE=$PS_CONFIG_DIR/PSConfig.properties
NLP_STATE_FILE=$PS_CONFIG_DIR/NLPConfig.properties

AMCONFIG_FILE=$IDSAME_CONFIG_DIR/config/AMConfig.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//"`
}

###############################################
# Check for ASCII characters
###############################################
CheckChars() {

  local VALID_CHARS=$1
  local STR=$2
  local US_SPECIFIC=""

  if [ "${LANG}" != "" ]; then
    $ECHO ${LANG} | $GREP "en_US" > /dev/null 2>&1
    if [ $? -eq 1 ]; then
      US_SPECIFIC="n"
      $ECHO $VALID_CHARS | $GREP "a-z" > /dev/null 2>&1
      if [ $? -eq 0 ]; then
	US_SPECIFIC="y"
      fi
      $ECHO $VALID_CHARS | $GREP "A-Z" > /dev/null 2>&1
      if [ $? -eq 0 ]; then
	US_SPECIFIC="y"
      fi
      if [ "$US_SPECIFIC" = "y" ]; then
	return 0
      fi
    fi
  fi

  if [ "$STR" != "" ]; then
    $ECHO $STR | $GREP "[^$VALID_CHARS]" > /dev/null 2>&1
    if [ $? -eq 1 ]; then
      return 0
    else
      return 1
    fi
  else
    return 1
  fi
}

###############################################
# Question
###############################################
Question() {

  local PROMPT=$1
  local VALID_CHARS=$2
  local DEFAULT=$3
  local DONE=""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    eval print "$PROMPT [$DEFAULT] \$OMIT_CHAR"
    read ANSWER
    HAD_INPUT="y"
    if [ "$ANSWER" = "" ]; then
      ANSWER=$DEFAULT
      DONE="y"
    else
      CheckChars "$VALID_CHARS" "$ANSWER"
      if [ $? -eq 0 ]; then
        DONE="y"
      else
        print "`$GETTEXT 'Invalid answer!'` $BELL_CHAR"
      fi
    fi
  done
}

###############################################
# Get password
###############################################

GetPassword() {

  local PROMPT=$1
  local ANSWER_REPEAT=""
  local DONE=""
  local LENGTH=""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    eval print "$PROMPT \$OMIT_CHAR"
    $STTY -echo
    read ANSWER
    $STTY echo
    HAD_INPUT="y"
    if [ "$ANSWER" != "" ]; then
      LENGTH=`$ECHO "$ANSWER" | $WC -m`
      if [ "$LENGTH" -lt 9 ]; then
        print ""
        print "`$GETTEXT 'Password must be at least 8 characters!'` $BELL_CHAR"
      else
        print "`$GETTEXT 'Again?'` $OMIT_CHAR"
        $STTY -echo
        read ANSWER_REPEAT
        $STTY echo
        print ""
        if [ "$ANSWER" != "$ANSWER_REPEAT" ]; then
          print "`$GETTEXT 'Password verification failed!'` $BELL_CHAR"
        else
          DONE="y"
        fi
      fi
    else
      print ""
    fi
  done

}

###############################################
# Question
###############################################

QuestionWithoutDefault() {

  local PROMPT=$1
  local VALID_CHARS=$2
  local DONE=""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    eval print "$PROMPT \$OMIT_CHAR"
    read ANSWER
    HAD_INPUT="y"
    if [ "$ANSWER" = "" ]; then
      DONE="n"
    else
      CheckChars "$VALID_CHARS" "$ANSWER"
      if [ $? -eq 0 ]; then
        DONE="y"
      else
        print "`$GETTEXT 'Invalid answer!'` $BELL_CHAR"
      fi
    fi
  done

}


###############################################
# Yes or no
###############################################

YesNo() {

  local PROMPT=$1
  local DEFAULT=$2
  local DONE=""
  local FULL_ANSWER=""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    if [ "$DEFAULT" = "y" ]; then
      eval print "$PROMPT [y]/n \$OMIT_CHAR"
      FULL_ANSWER="n"
    elif [ "$DEFAULT" = "n" ]; then
      eval print "$PROMPT y/[n] \$OMIT_CHAR"
      FULL_ANSWER="n"
    elif [ "$DEFAULT" = "yes" ]; then
      eval print "$PROMPT [yes]/no \$OMIT_CHAR"
      FULL_ANSWER="y"
    elif [ "$DEFAULT" = "no" ]; then
      eval print "$PROMPT yes/[no] \$OMIT_CHAR"
      FULL_ANSWER="y"
    else
      eval print "$PROMPT y/n \$OMIT_CHAR"
      FULL_ANSWER="n"
    fi

    read ANSWER
    HAD_INPUT="y"

    if [ "$ANSWER" = "" ] && [ "$DEFAULT" != "" ]; then
      ANSWER=$DEFAULT
      DONE="y"
    else
      ANSWER=`$ECHO $ANSWER | $SED -e "y/YESNO/yesno/"`
      if [ "$FULL_ANSWER" = "n" ]; then
        if [ "$ANSWER" = "yes" ]; then
          ANSWER="y"
        elif [ "$ANSWER" = "no" ]; then
          ANSWER="n"
        fi
        if [ "$ANSWER" = "y" ]; then
          DONE="y"
        elif [ "$ANSWER" = "n" ]; then
          DONE="y"
        else
          print "`$GETTEXT 'Invalid response! y/n only.'` $BELL_CHAR"
        fi
      else
        if [ "$ANSWER" = "yes" ]; then
          DONE="y"
        elif [ "$ANSWER" = "no" ]; then
          DONE="y"
        else
          print "`$GETTEXT 'Invalid response! yes/no only.'` $BELL_CHAR"
        fi
      fi
    fi
  done

}

###############################################
# Get password
###############################################

GetLogUserPassword() {

  local PROMPT=$1
  local ANSWER_REPEAT=""
  local DONE=""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    eval print "$PROMPT \$OMIT_CHAR"
    $STTY -echo
    read ANSWER
    $STTY echo
    HAD_INPUT="y"
    if [ "$ANSWER" != "" ]; then
        print "`$GETTEXT 'Again?'` $OMIT_CHAR"
        $STTY -echo
        read ANSWER_REPEAT
        $STTY echo
        print ""
        if [ "$ANSWER" != "$ANSWER_REPEAT" ]; then
          print "`$GETTEXT 'Password verification failed!'` $BELL_CHAR"
        else
          DONE="y"
        fi
    else
      print ""
    fi
  done

}


###############################################
# Check port value
###############################################

CheckPort() {

  local PORT=$1

  if [ $PORT -lt 1 ] || [ $PORT -gt 65535 ]; then
    return 1
  else
    return 0
  fi

}

###############################################
# Check port availability
###############################################

IsPortFree() {

  local IP=$1
  local PORT=$2
  local CHECKPORT=""

  return 0

  CHECKPORT="$BIN_DIR/checkport"
  $CHECKPORT $IP $PORT 5
  if [ $? -eq 1 ]; then
    return "y"
  else
    return "n"
  fi

}

###############################################
# Get the existing netlet proxy informations
###############################################

GetExistingNLPInfo() {
 
  # Access Manager base directory.
  GrabConfig $NLP_STATE_FILE "IDSAME_BASEDIR" "="
  IS_BASEDIR=$ANSWER

  # Netlet proxy base directory.
  GrabConfig $NLP_STATE_FILE "NLP_BASEDIR" "="
  NLP_BASEDIR=$ANSWER

  # Netlet proxy host.
  GrabConfig $NLP_STATE_FILE "NLP_HOST" "="
  NLP_HOST=$ANSWER

  # Netlet proxy IP.
  GrabConfig $NLP_STATE_FILE "NLP_IP" "="
  NLP_IP=$ANSWER
  
  # Netlet proxy Virtual host.
  NLP_VIRTUAL_HOST="${NLP_HOST} ${NLP_IP}"

  # SSL connection.
  SSL_CONNECTION="true"

  # Netlet proxy bin directory.
  BIN_DIR=$NLP_BASEDIR/$PS_PRODUCT_DIR/bin

  # Netlet proxy lib directory.
  LIB_DIR=$NLP_BASEDIR/$PS_PRODUCT_DIR/lib

}

#########################################################################
# Get the existing Portal server informations from PSConfig.properties
#########################################################################

GetExistingPSInfo() {

  # Portal server host.
   GrabConfig $PS_STATE_FILE "SERVER_HOST" "="
   LPS_HOST=$ANSWER

   # Portal server port.
   GrabConfig $PS_STATE_FILE "SERVER_PORT" "="
   LPS_PORT=$ANSWER

   # Portal server protocol
   GrabConfig $PS_STATE_FILE "SERVER_PROTOCOL" "="
   LPS_PROTOCOL=$ANSWER

   # Portal server deploy URI.
   GrabConfig $PS_STATE_FILE "DEPLOY_URI" "="
   LPS_DEPLOY_URI=$ANSWER

 # Portal server Load Balancer.
   GrabConfig $PS_STATE_FILE "LOAD_BALANCER_URL" "="
   LOAD_BALANCER_URL=$ANSWER


}

#########################################################################
# Get the new Portal server informations.
#########################################################################

GetNewPSInfo() {

  YesNo "`$GETTEXT 'Is there a Load Balancer for Portal Instances ?'`" "y"

   if [ "$ANSWER" = "n" ]; then


   # Portal server host.
   QuestionWithoutDefault "`$GETTEXT 'What is the fully qualified hostname of the portal server?'`" "a-zA-Z0-9\./_-"
   LPS_HOST=$ANSWER

   # Portal server port.
   local VALIDATED="n"
   while [ "$VALIDATED" = "n" ]; do
   QuestionWithoutDefault "`$GETTEXT 'What port should be used to access the portal server?'`" "0-9"
   LPS_PORT=$ANSWER
   CheckPort $LPS_PORT
   if [ $? -eq 1 ]; then
      print "`$GETTEXT 'The port number entered is not valid. Try again.'` $BELL_CHAR"
   else
      VALIDATED="y"
   fi
   done

   # Portal server protocol.
   VALIDATED="n"
   while [ "$VALIDATED" = "n" ]; do
    Question "`$GETTEXT 'What protocol should be used to access the portal server?'`" "a-zA-Z" "http"
    LPS_PROTOCOL=$ANSWER
    if [ "$LPS_PROTOCOL" = "http" ] ||  [ "$LPS_PROTOCOL" = "https" ]; then
      VALIDATED="y"
    else
      VALIDATED="n"
    fi
  done

   # Portal server deploy URI
   Question "`$GETTEXT 'What is the portal server deploy URI?'`" "a-zA-Z0-9\./_-" "/portal"
   LPS_DEPLOY_URI=$ANSWER
   LOAD_BALANCER_URL=$LPS_PROTOCOL://$LPS_HOST:$LPS_PORT$LPS_DEPLOY_URI

  else

   # Load Balancer URL
  QuestionWithoutDefault "`$GETTEXT 'What is the Portal server Load Balancer URL for this netletproxy instance Eg:http://portalhost:portalport/portaldeployuri'`" "a-zA-Z0-9\/:\."
  LOAD_BALANCER_URL=$ANSWER


 fi

}

#########################################################################
# Get the new Access Manager informations from user.
#########################################################################

GetExistingISInfo() {

   # Organization DN
   GrabConfig $AMCONFIG_FILE $AMCONFIG_ORG_DN "="
   IS_ORG_DN=$ANSWER

   # IS deploy URI
   GrabConfig $AMCONFIG_FILE $AMCONFIG_AMSERVER "="
   IS_DEPLOY_URI=$ANSWER

   # IS password encryption key.
   GrabConfig $AMCONFIG_FILE $AMCONFIG_PASSWORD_KEY "="
   IS_PASSWORD_KEY=$ANSWER
     # IS host
   GrabConfig $AMCONFIG_FILE "com.iplanet.am.server.host" "="
   SERVER_HOST=$ANSWER
   SERVER_HOSTNAME=$ANSWER

   # IS port
   GrabConfig $AMCONFIG_FILE "com.iplanet.am.server.port" "="
   SERVER_PORT=$ANSWER

   #IS Protocol
   GrabConfig $AMCONFIG_FILE "com.iplanet.am.server.protocol" "="
   SERVER_PROTOCOL=$ANSWER

}

#########################################################################
# Get the existing Access Manager informations from AMConfig.properties
#########################################################################

GetNewISInfo() {

    # Get the default values from existing configuration.
   GetExistingISInfo



   YesNo "`$GETTEXT 'Will the new gateway instance be used with a default Access Manager Configuration on this node?'`" "y"

   if [ "$ANSWER" = "n" ]; then

    QuestionWithoutDefault "`$GETTEXT 'What is the Access Manager Host Name?'`" "a-zA-Z0-9\./_-="
    SERVER_HOST=$ANSWER
    SERVER_HOSTNAME=$ANSWER

    QuestionWithoutDefault "`$GETTEXT 'What is the Access Manager Port?'`" "0-9"
    SERVER_PORT=$ANSWER

    QuestionWithoutDefault "`$GETTEXT 'What is the Access Manager Protocol?'`" "a-zA-Z"
    SERVER_PROTOCOL=$ANSWER

   fi

   # Organization DN
   Question "`$GETTEXT 'What is the organization DN?'`" "a-zA-Z0-9\./_-=\,," "$IS_ORG_DN"
   IS_ORG_DN=$ANSWER

   # IS deploy URI
   Question "`$GETTEXT 'What is the identity server URI?'`" "a-zA-Z0-9\./_-" "$IS_DEPLOY_URI"
   IS_DEPLOY_URI=$ANSWER

   # IS password encryption key.
   Question "`$GETTEXT 'What is the identity server password encryption key?'`" "a-zA-Z0-9\./_-=" "$IS_PASSWORD_KEY"
   IS_PASSWORD_KEY=$ANSWER


}

###############################################
# Check package 
###############################################

CheckPackage() {

  local PACKAGE=$1

  $PKGINFO -q $PACKAGE
  if [ $? -eq 0 ]; then
    ANSWER="y"
  else
    ANSWER="n"
  fi

}

###############################################
# Check rpm
###############################################
CheckRpm() {

  local RPM_NAME=$1

  rpm -q --quiet $RPM_NAME
  if [ $? -eq 0 ]; then
    ANSWER="y"
  else
    ANSWER="n"
  fi
}

###############################################
# Check file
###############################################

CheckFile() {

  local FILE=$1

  if [ -f $FILE ]; then
    ANSWER="y"
  else
    ANSWER="n"
  fi

}

###########################################################################
# Check if the portal server is properly installed in this node.
###########################################################################

IsPortalServerInstalled() {
    
    if [ "$OSTYPE" = "Linux" ]; then
        CheckRpm "sun-portal-core"
    else
        CheckPackage "SUNWps"
    fi

    if [ "$ANSWER" = "y" ]; then
        CheckFile $PS_STATE_FILE
    fi

}

###########################################################################
# Get the instance type
###########################################################################

GetInstanceType() {

  INSTANCE_TYPE=$NLP

}

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

}

###############################################
# get new netlet proxy instance info
###############################################
GetNewNLPInfo() {

  # Netlet proxy protocol.
  local VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    Question "`$GETTEXT 'What protocol will the new netlet proxy instance use?'`" "a-zA-Z" "https"
    NLP_PROTOCOL=$ANSWER
    if [ "$NLP_PROTOCOL" = "http" ] ||  [ "$NLP_PROTOCOL" = "https" ]; then
      VALIDATED="y"
    else
      VALIDATED="n"
    fi
  done
  
  # Netlet proxy port.
  VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    QuestionWithoutDefault "`$GETTEXT 'What port will the new netlet proxy instance listen on?'`" "0-9"
    NLP_PORT=$ANSWER
    CheckPort $NLP_PORT
    if [ $? -eq 1 ]; then
      print "`$GETTEXT 'The port number entered is not valid. Try again.'` $BELL_CHAR"
    else
      IsPortFree $NLP_IP $NLP_PORT
      if [ $? = "n" ]; then
        print "`$GETTEXT 'The port number entered is already in use. Try again.'` $BELL_CHAR"
      else
        VALIDATED="y"
      fi
    fi
  done

}


################################################################
# Get the portal/identity server details for the new netlet proxy instance.
################################################################

GetServerInfo() {

  IsPortalServerInstalled

  if [ "$ANSWER" = "y" ]; then
    YesNo "`$GETTEXT 'Will the new netlet proxy instance be used with a portalserver instance running on this node?'`" "y"
  fi
    
  if [ "$ANSWER" = "y" ]; then
    CREATE_IS_INSTANCE="n"
    GetExistingPSInfo
    #GetExistingISInfo
  else
    CREATE_IS_INSTANCE="y"
    GetNewPSInfo

  fi
     GetNewISInfo
}

################################################################
# Get the certificate information needed for creating a new instance.
################################################################

GetNewNLPCertInfo() {

    local ORG=""
    local DIV=""
    local CITY=""
    local STATE=""

    local PROMPT="`$GETTEXT 'Please provide the following informations needed for creating self-signed certificate:'`"	
    print ""
    print "${PROMPT}"
    SELF_SIGNED_CERT="y"

    if [ "$SELF_SIGNED_CERT" = "y" ]; then
        Question "`$GETTEXT 'What is the name of your organization?'`" "a-zA-Z0-9\ ._-," "MyOrganization"
        ORG="$ANSWER"

        Question "`$GETTEXT 'What is the name of your division?'`" "a-zA-Z0-9\ ._-," "MyDivision"
        DIV="$ANSWER"

        Question "`$GETTEXT 'What is the name of your city or locality?'`" "a-zA-Z\ ._-," "MyCity"
        CITY="$ANSWER"

        Question "`$GETTEXT 'What is the name of your state or province?'`" "a-zA-Z\ ._-," "MyState"
        STATE="$ANSWER"

        Question "`$GETTEXT 'What is the two-letter country code?'`" "a-zA-Z" "us"
        COUNTRY=`$ECHO "$ANSWER" | $AWK '{print(substr($0,0,2));}'`

        CERT_INFO="CN=$NLP_HOST,L=\"$CITY\",ST=\"$STATE\",C=$COUNTRY,O=\"$DIV\",OU=\"$ORG\""

        GetPassword "`$GETTEXT 'What is the password for the Certificate Database?'`"
        CERT_DB_PASSWORD=$ANSWER
	export CERT_DB_PASSWORD

        print ""
    fi

}

################################################################
# Get Misc information like log user password, start after installation.
################################################################

GetMiscInformation() {

    # Logging user password.
    GetLogUserPassword "What is the password for the logging user?"
    SRA_LOG_USER_PASSWORD=$ANSWER
    export SRA_LOG_USER_PASSWORD

    # Start netlet proxy after installation ?
    YesNo "`$GETTEXT 'Have you created the new netlet proxy profile in the admin console?'`" "y"
    PROFILE_CREATED=$ANSWER
    if [ "$PROFILE_CREATED" = "y" ]; then
        YesNo "`$GETTEXT 'Start the netlet proxy after installation?'`" "y"
        START_NETLETPROXY=$ANSWER
    else
        START_NETLETPROXY="n"
    fi

}

################################################################
# Read the config info from RWPConfig to script variables.
################################################################

ReadInConfigInfo() {

  NLP_GATEWAY_PROFILE=$1

  RWP_CONFIG_FILE="$PS_CONFIG_DIR/RWPConfig-${NLP_GATEWAY_PROFILE}.properties"

  # Netlet proxy protocol.
  GrabConfig $RWP_CONFIG_FILE "RWP_PROTOCOL" "="
  NLP_PROTOCOL=$ANSWER

  # Self signed certificate
  GrabConfig $RWP_CONFIG_FILE "SELF_SIGNED_CERT" "="
  SELF_SIGNED_CERT=$ANSWER
  
  # Certicate information.
  GrabConfig $RWP_CONFIG_FILE "CERT_INFO" "="
  CERT_INFO=$ANSWER

  # Portal server host
  GrabConfig $RWP_CONFIG_FILE "SERVER_HOST" "="
  SERVER_HOST=$ANSWER

  # Portal server port
  GrabConfig $RWP_CONFIG_FILE "SERVER_PORT" "="
  SERVER_PORT=$ANSWER

  # Portal server protcol
  GrabConfig $RWP_CONFIG_FILE "SERVER_PROTOCOL" "="
  SERVER_PROTOCOL=$ANSWER

  # Portal server deploy URI
  GrabConfig $RWP_CONFIG_FILE "DEPLOY_URI" "="
  DEPLOY_URI=$ANSWER

  # Organization DN
  GrabConfig $RWP_CONFIG_FILE "IDSAME_ORG_DN" "="
  IS_ORG_DN=$ANSWER

  # Access Manager URI
  GrabConfig $RWP_CONFIG_FILE "IDSAME_AMSERVER" "="
  IS_DEPLOY_URI=$ANSWER

  # Access Manager password encryption key.
  GrabConfig $RWP_CONFIG_FILE "IDSAME_PASSWORD_KEY" "="
  IS_PASSWORD_KEY=$ANSWER

}

################################################################
# Use the existing RWP configuration for this NLP instance.
################################################################

UseExistingConfiguration() {

  print ""
  # Netlet proxy port.
  local VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    QuestionWithoutDefault "`$GETTEXT 'What port will the new netlet proxy instance listen on?'`" "0-9"
    NLP_PORT=$ANSWER
    CheckPort $NLP_PORT
    if [ $? -eq 1 ]; then
      print "`$GETTEXT 'The port number entered is not valid. Try again.'` $BELL_CHAR"
    else
      IsPortFree $NLP_IP $NLP_PORT
      if [ $? = "n" ]; then
        print "`$GETTEXT 'The port number entered is already in use. Try again.'` $BELL_CHAR"
      else
        VALIDATED="y"
      fi
    fi
  done

  YesNo "`$GETTEXT 'Start the netlet proxy after installation?'`" "y"
  START_NETLETPROXY=$ANSWER

  # Grab the other configuration information from RWPConfig
  ReadInConfigInfo ${NLP_GATEWAY_PROFILE}

  # Overwrite the values read from RWPConfig.
  CREATE_IS_INSTANCE="n"
  SELF_SIGNED_CERT="n"
}

################################################################
# Get the information needed for creating a new instance.
################################################################

GetNewInfo() {

    # Get the new netlet proxy instance details
    GetNewNLPInfo

    # Get the portal/identity server details for the new netlet proxy instance.
    GetServerInfo

    # Get the certificate information
    GetNewNLPCertInfo

    # Get Misc information like log user password, start after installation.
    GetMiscInformation

}


################################################################
# Validate the new instance name and branch based on user inupt.
# @ Uses global variable INSTANCES.
################################################################

GetNewInstanceInfo() {    

  local VALIDATED="n"

  while [ "$VALIDATED" = "n" ]; do
 
    # Clear the screen.
    $CLEAR
    print ""

    QuestionWithoutDefault "`$GETTEXT 'What is the name of the new netlet proxy instance?'`" "a-zA-Z0-9\./_-"

    NLP_GATEWAY_PROFILE=$ANSWER
    
    ALREADY_CONFIGURED="n"

    for INSTANCE in ${INSTANCES}; do
      if [ "$INSTANCE" = "$NLP_GATEWAY_PROFILE" ]; then
        ALREADY_CONFIGURED="y"
      fi
    done

    if [ "${ALREADY_CONFIGURED}" = "y" ]; then
      print ""
      print "`$GETTEXT 'Error: Netlet proxy instance with this name is already configured in the system.'` $BELL_CHAR"
      print ""
      $SLEEP 4
    else
      if [ -f $PS_CONFIG_DIR/platform.conf.$NLP_GATEWAY_PROFILE ]; then
        print ""
        print "`$GETTEXT 'Rewriter proxy instance with the same name is already configured in the system'`" 
        print ""
        YesNo "`$GETTEXT 'Do you want to use the same configuration for this netlet proxy instance?'`" "y"
        if [ "$ANSWER" = "y" ]; then
            RWP_CONFIG_FILE="$PS_CONFIG_DIR/RWPConfig-${NLP_GATEWAY_PROFILE}.properties"
            if [ ! -f "${RWP_CONFIG_FILE}" ]; then
              print ""
              print "`$GETTEXT 'Error : Unable to locale configuration file '`" "${RWP_CONFIG_FILE}"
              print ""
            else
              VALIDATED="y"
              UseExistingConfiguration
            fi
        fi
      else
        VALIDATED="y"
        GetNewInfo
      fi
    fi

  done

}

##############################################################################
# Write the collected information to the state file                          #
##############################################################################

WriteNewNLPInfo() {

    # Create a new state file from config template.
    NLP_CONFIG_TEMPLATE=$PS_CONFIG_DIR/NLPConfig.properties.template
    NEW_NLP_STATE_FILE="$PS_CONFIG_DIR/NLPConfig-${NLP_GATEWAY_PROFILE}.properties"
    $CP $NLP_CONFIG_TEMPLATE $NEW_NLP_STATE_FILE
    if [ "$OSTYPE" = "SunOS" ]; then
        $INSTALLF "SUNWpsnlp" ${NEW_NLP_STATE_FILE}
    fi

    # Replace the tokens in newly created NLPConfig-<NLP_GATEWAY_PROFILE>.properties file
    FILES="$NEW_NLP_STATE_FILE"
    for FILE in $FILES; do
        $CP -p $FILE $FILE-tmp
        $SED  -e "s#NLP_BASEDIR_VAL#$NLP_BASEDIR#g" \
              -e "s#NLP_PROTOCOL_VAL#$NLP_PROTOCOL#g" \
              -e "s#NLP_HOST_VAL#${NLP_HOST}#g" \
              -e "s#NLP_PORT_VAL#${NLP_PORT}#g" \
              -e "s#NLP_HOST_VAL#${NLP_HOST}#g" \
              -e "s#NLP_PORT_VAL#${NLP_PORT}#g" \
              -e "s#NLP_IP_VAL#${NLP_IP}#g" \
              -e "s#NLP_GATEWAY_PROFILE_VAL#${NLP_GATEWAY_PROFILE}#g" \
              -e "s#SELF_SIGNED_CERT_VAL#${SELF_SIGNED_CERT}#g" \
              -e "s#CERT_INFO_VAL#${CERT_INFO}#g" \
              -e "s#SERVER_PROTOCOL_VAL#${SERVER_PROTOCOL}#g" \
              -e "s#SERVER_HOST_VAL#${SERVER_HOST}#g" \
              -e "s#SERVER_PORT_VAL#${SERVER_PORT}#g" \
              -e "s#DEPLOY_URI_VAL#${DEPLOY_URI}#g" \
              -e "s#IDSAME_BASEDIR_VAL#${IS_BASEDIR}#g" \
              -e "s#CREATE_IS_INSTANCE_VAL#${CREATE_IS_INSTANCE}#g" \
              -e "s#IDSAME_AMSERVER_VAL#${IS_DEPLOY_URI}#g" \
              -e "s#IDSAME_ORG_DN_VAL#${IS_ORG_DN}#g" \
              -e "s#IDSAME_PASSWORD_KEY_VAL#${IS_PASSWORD_KEY}#g" \
              -e "s#START_NETLETPROXY_VAL#${START_NETLETPROXY}#g" \
              -e "s#LOAD_BALANCER_URL_VAL#${LOAD_BALANCER_URL}#g" \
        $FILE-tmp > $FILE
        $RM -f $FILE-tmp
    done

    # Convert newly created state file to ascii.
    NATIVE2ASCII=native2ascii
    if [ "$OSTYPE" = "Linux" ]; then
      # JDK base directory
      GrabConfig "$AMCONFIG_FILE" "com.iplanet.am.jdk.path" "="
      if [ "$ANSWER" != "" ]; then
        JDK_DIR=$ANSWER
      else
        $ECHO "Error: Cannot determine JDK_DIR. $BELL_CHAR"
        exit 1
      fi
      NATIVE2ASCII=$JDK_DIR/bin/native2ascii
    fi

    $NATIVE2ASCII ${NEW_NLP_STATE_FILE} ${NEW_NLP_STATE_FILE}+
    if [ $? -eq 0 ]; then
        mv ${NEW_NLP_STATE_FILE}+ ${NEW_NLP_STATE_FILE}
    fi

}

##############################################################################
# Display the summary.
##############################################################################

DisplaySummary() {
  $CLEAR

  print "" 
  print "`$GETTEXT 'New netlet proxy instance installation summary'`" 
  print "" 
  print "`$GETTEXT '  New netlet proxy instance name               : '`" "$NLP_GATEWAY_PROFILE"
  print "`$GETTEXT '  Netlet proxy host                            : '`" "$NLP_HOST"
  print "`$GETTEXT '  Netlet proxy port                            : '`" "$NLP_PORT"
  print "`$GETTEXT '  Netlet proxy protocol                        : '`" "$NLP_PROTOCOL"
  print "`$GETTEXT '  Access Manager host                         : '`" "$SERVER_HOST"
  print "`$GETTEXT '  Access Manager port                         : '`" "$SERVER_PORT"
  print "`$GETTEXT '  Access Manager protocol                     : '`" "$SERVER_PROTOCOL"
  print "`$GETTEXT '  Load Balancer URL                            : '`" "$LOAD_BALANCER_URL"
  print "`$GETTEXT '  Organization DN                              : '`" "$IS_ORG_DN"
  print "`$GETTEXT '  Access Manager deploy URI                   : '`" "$IS_DEPLOY_URI"
  print "`$GETTEXT '  Access Manager password encryption key      : '`" "$IS_PASSWORD_KEY"
  print "`$GETTEXT '  Create self signed certificate ?             : '`" "$SELF_SIGNED_CERT"
  if [ "$SELF_SIGNED_CERT" == "y" ]; then
      print "`$GETTEXT '  Certificate information                      : '`" "$CERT_INFO"
  fi
  print "`$GETTEXT '  Start instance after installation            : '`" "$START_NETLETPROXY"
  print "" 
}

##############################################################################
# Confirms the details.
##############################################################################
ConfirmSummary() {
    print ""
    YesNo "`$GETTEXT 'Are the above informations correct?'`" "y"
}

##############################################################################
# List the existing netlet proxy instances.
##############################################################################

ListNLPInstances() {

    INSTANCES=""

    # Grab all existing instances.
    for x in $PS_CONFIG_DIR/platform.conf.*; do

        if [ -r $x ]; then

            INSTANCE_NAME=`$ECHO $x | $SED -e "s#$PS_CONFIG_DIR/platform.conf.##"`

            # Check if the state file exists
            if [ -f $PS_CONFIG_DIR/NLPConfig-${INSTANCE_NAME}.properties ]; then
                INSTANCES="${INSTANCES} ${INSTANCE_NAME}"
            fi

        fi

    done
    
    # Print the instances.
    if [ "${INSTANCES}" != "" ]; then
        print "`$GETTEXT 'Detected netlet proxy instances:'`"
        print ""

        for INSTANCE in ${INSTANCES}; do
            print "    ${INSTANCE}"
        done
	
	print ""
    fi

}

#############################################################################
# Show the install options and get user's choice.
#############################################################################

ShowInstallOptions() {

  local PROMPT="`$GETTEXT 'Install options:'`"	

  local MENU_ITEMS="`$GETTEXT 'Create a new netlet proxy instance'`;CREATE;"
  if [ "$INSTANCES" != "" ]; then
      MENU_ITEMS="$MENU_ITEMS`$GETTEXT 'Remove a netlet proxy instance'`;REMOVE;"
      MENU_ITEMS="$MENU_ITEMS`$GETTEXT 'Remove all netlet proxy instances'`;REMOVEALL;"
  fi
  MENU_ITEMS="$MENU_ITEMS`$GETTEXT 'Exit'`;QUIT;"

  local DEFAULT=""
  local DONE=""
  local ITEM=""
  local ITEMS=""
  local ITEM_COUNT=0
  local MENU_ANSWER=""
  local RETURN=""
  local RETURNS=""

  print "$PROMPT"
  print ""

  DONE="n"
  while [ "$DONE" = "n" ]; do
    RETURNS=""
    let ITEM_COUNT=0
    ITEMS=$MENU_ITEMS
    while [ "$ITEMS" != "" ]; do
        let ITEM_COUNT+=1

        ITEM=${ITEMS%%;*}
        ITEMS=${ITEMS#*;}

        RETURN="${ITEMS%%;*}"
        ITEMS=${ITEMS#*;}

        print "$ITEM_COUNT) $ITEM"
        DEFAULT=$ITEM_COUNT

        RETURNS="$RETURNS$RETURN;"
    done

    print ""
    print "`$GETTEXT 'Choice?'` [$DEFAULT] $OMIT_CHAR"
    read MENU_ANSWER

    if [ "$MENU_ANSWER" = "" ]; then
        MENU_ANSWER=$DEFAULT
	DONE="y"
    else
	CheckChars "0-9" $MENU_ANSWER
	if [ $? -eq 0 ]; then
	    if [ $MENU_ANSWER -ge 1 ] && [ $MENU_ANSWER -le $ITEM_COUNT ]; then
	    	DONE="y"
	    else
		print ""
	        print "`$GETTEXT 'Invalid response!'` $BELL_CHAR"
		print ""
	    fi
	else
            print ""
	    print "`$GETTEXT 'Invalid response!'` $BELL_CHAR"
	    print ""
        fi
    fi
  done
    
  let ITEM_COUNT=0
  while [ "$RETURNS" != "" ]; do
    let ITEM_COUNT+=1
    ANSWER="${RETURNS%%;*};"
    RETURNS=${RETURNS#*;}
    if [ "$ITEM_COUNT" = "$MENU_ANSWER" ]; then
      RETURNS="";
    fi
  done

}

##############################################################################
# Collect info, display summary, and create new instance.
##############################################################################

CreateInstance() {

  local CREATED="n"

  while [ "$CREATED" = "n" ]; do

    # Clear the screen.
    $CLEAR

    # Get the information needed from the user.
    GetNewInstanceInfo

    # Display the summary
    DisplaySummary

    # Confirm the details.
    ConfirmSummary

    if [ "$ANSWER" = "y" ]; then
        CREATED="y"

  	print ""
	print "`$GETTEXT 'Installation in progres...'`" 
        # Write the information to the state file.
        WriteNewNLPInfo
  	print ""
	print "`$GETTEXT 'Configuring new netlet proxy instance...'`" 
        # Configure the new netlet proxy instance
        ${LIB_DIR}/postinstall_NLP ${NLP_GATEWAY_PROFILE}
  	print ""

    fi

  done

}

##############################################################################
# Removes a netlet proxy instance
##############################################################################

RemoveInstance() {

    print ""

    QuestionWithoutDefault "`$GETTEXT 'What is the name of the netlet proxy instance to be removed?'`" "a-zA-Z0-9\./_-"
    INSTANCE_NAME=$ANSWER

    if [ ! -f $PS_CONFIG_DIR/platform.conf.$INSTANCE_NAME ]; then
      print ""
      print "`$GETTEXT 'Error: Netlet proxy instance with this name is not configured in the system.'` $BELL_CHAR"
      print ""
      $SLEEP 4
      return
    fi

    YesNo "`$GETTEXT 'Do you want to back up the configuration?'`" "n"
    BACKUP_MODE=$ANSWER
	
    YesNo "`$GETTEXT 'Continue with the removal?'`" "y"
    
    if [ "$ANSWER" = "y" ]; then
	print ""
	print "`$GETTEXT 'Uninstallation in progres...'`" 
	print ""
        if [ "$BACKUP_MODE" = "n" ]; then
	    ${LIB_DIR}/remove_NLP --purge $INSTANCE_NAME
	else
	    ${LIB_DIR}/remove_NLP $INSTANCE_NAME
	fi
    fi

}


##############################################################################
# Removes all netlet proxy instances
##############################################################################

RemoveAllInstances() {
    print ""
    
    YesNo "`$GETTEXT 'Do you want to back up the configuration?'`" "n"
    BACKUP_MODE=$ANSWER
	
    YesNo "`$GETTEXT 'Continue with the removal?'`" "y"
    
    if [ "$ANSWER" = "y" ]; then
	print "`$GETTEXT 'Uninstallation in progres...'`" 
	print ""
        if [ "$BACKUP_MODE" = "n" ]; then
	    ${LIB_DIR}/remove_NLP --purge
	else
	    ${LIB_DIR}/remove_NLP
	fi
    fi

}

##############################################################################
# Start the main method to create multi instances                            #
##############################################################################

StartMultiInstance() {

    local DONE="n"

    while [ "$DONE" = "n" ]; do

	# Clear the screen
	$CLEAR
	print ""

        # List the existing netlet proxy instances.
        ListNLPInstances

        # User option.
	ShowInstallOptions
	
	if [ "$ANSWER" = "CREATE;" ]; then
            CreateInstance
	elif [ "$ANSWER" = "REMOVE;" ]; then
	    RemoveInstance
	elif [ "$ANSWER" = "REMOVEALL;" ]; then
	    RemoveAllInstances
	elif [ "$ANSWER" = "QUIT;" ]; then
	    DONE="y"
        fi

    done

    print ""
    
}

##############################################################################
# Main                                                                       #
##############################################################################
# Make sure root is executing this script.
CheckUser

# Get IS_BASEDIR, NLP_BASEDIR, NLP_HOST, NLP_IP, NLP_VIRTUAL_HOST, SSL_CONNECTION
GetExistingNLPInfo

# Enter the main loop.
StartMultiInstance

exit 0

