#!/bin/ksh

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

# 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
GW_STATE_FILE=$PS_CONFIG_DIR/GWConfig.properties

# AMConfig.properties file pointer
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 gateway informations
###############################################
GetExistingGWInfo() {

  # Identity server base directory.
  GrabConfig $GW_STATE_FILE "IDSAME_BASEDIR" "="
  IS_BASEDIR=$ANSWER

  # Gateway base directory.
  GrabConfig $GW_STATE_FILE "GW_BASEDIR" "="
  GW_BASEDIR=$ANSWER

  # Gateway host.
  GrabConfig $GW_STATE_FILE "GW_HOST" "="
  GW_HOST=$ANSWER

  # Gateway IP.
  GrabConfig $GW_STATE_FILE "GW_IP" "="
  GW_IP=$ANSWER

  # Gateway Virtual host.
  GW_VIRTUAL_HOST="${GW_HOST} ${GW_IP}"

  # SSL connection.
  SSL_CONNECTION="true"

  # Gateway bin directory.
  BIN_DIR=$GW_BASEDIR/$PS_PRODUCT_DIR/bin

  # Gateway lib directory.
  LIB_DIR=$GW_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 gateway instance Eg:http://portalhost:portalport/portaldeployuri'`" "a-zA-Z0-9\/:\."
  LOAD_BALANCER_URL=$ANSWER


 fi
}

#########################################################################
# Get the new Identity server 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 Identity server 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 Identity Configuration on this node?'`" "y"

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

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

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

    QuestionWithoutDefault "`$GETTEXT 'What is the IdentityServer 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=$GW

}

################################################################
# 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 gateway instance info
###############################################
GetNewGWInfo() {

  # New gateway instance name.
  local VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    QuestionWithoutDefault "`$GETTEXT 'What is the name of the new gateway instance?'`" "a-zA-Z0-9\./_-"
    GW_GATEWAY_PROFILE=$ANSWER
    if [ -f $PS_CONFIG_DIR/platform.conf.$GW_GATEWAY_PROFILE ]; then
      $ECHO ""
      print "`$GETTEXT 'Error: Gateway instance with this name is already configured in the system. Try again.'` $BELL_CHAR"
      $ECHO ""
    else
      VALIDATED="y"
    fi
  done

  # Gateway protocol.
  VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    Question "`$GETTEXT 'What protocol will the new gateway instance use?'`" "a-zA-Z" "https"
    GW_PROTOCOL=$ANSWER
    if [ "$GW_PROTOCOL" = "http" ] ||  [ "$GW_PROTOCOL" = "https" ]; then
      VALIDATED="y"
    else
      VALIDATED="n"
    fi
  done

  # Gateway port.
  VALIDATED="n"
  while [ "$VALIDATED" = "n" ]; do
    QuestionWithoutDefault "`$GETTEXT 'What port will the new gateway instance listen on?'`" "0-9"
    GW_PORT=$ANSWER
    CheckPort $GW_PORT
    if [ $? -eq 1 ]; then
      print "`$GETTEXT 'The port number entered is not valid. Try again.'` $BELL_CHAR"
    else
      IsPortFree $GW_IP $GW_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 gateway instance.
################################################################
GetServerInfo() {

  IsPortalServerInstalled

  if [ "$ANSWER" = "y" ]; then
    YesNo "`$GETTEXT 'Will the new gateway 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.
################################################################
GetNewGWCertInfo() {

    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=$GW_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 gateway after installation ?
    YesNo "`$GETTEXT 'Have you created the new gateway profile in the admin console?'`" "y"
    PROFILE_CREATED=$ANSWER
    if [ "$PROFILE_CREATED" = "y" ]; then
      YesNo "`$GETTEXT 'Start the gateway after installation?'`" "y"
      START_GATEWAY=$ANSWER
    else
      START_GATEWAY="n"
    fi

}

################################################################
# Get the information needed for creating a new instance.
################################################################
GetNewInfo() {

    # Get the new gateway instance details
    GetNewGWInfo

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

    # Get the certificate information
    GetNewGWCertInfo

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

}

##############################################################################
# Write the collected information to the state file                          #
##############################################################################
WriteNewGWInfo() {

    # Create a new state file from config template.
    GW_CONFIG_TEMPLATE=$PS_CONFIG_DIR/GWConfig.properties.template
    NEW_GW_STATE_FILE="$PS_CONFIG_DIR/GWConfig-${GW_GATEWAY_PROFILE}.properties"
    $CP $GW_CONFIG_TEMPLATE $NEW_GW_STATE_FILE
    if [ "$OSTYPE" = "SunOS" ]; then
        $INSTALLF "SUNWpsgw" ${NEW_GW_STATE_FILE}
    fi

    # Replace the tokens in newly created GWConfig-<GW_GATEWAY_PROFILE>.properties file
    FILES="$NEW_GW_STATE_FILE"
    for FILE in $FILES; do
        $CP -p $FILE $FILE-tmp
        $SED  -e "s#GW_BASEDIR_VAL#$GW_BASEDIR#g" \
              -e "s#GW_PROTOCOL_VAL#$GW_PROTOCOL#g" \
              -e "s#GW_HOST_VAL#${GW_HOST}#g" \
              -e "s#GW_PORT_VAL#${GW_PORT}#g" \
              -e "s#GW_HOST_VAL#${GW_HOST}#g" \
              -e "s#GW_PORT_VAL#${GW_PORT}#g" \
              -e "s#GW_IP_VAL#${GW_IP}#g" \
              -e "s#GW_GATEWAY_PROFILE_VAL#${GW_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_GATEWAY_VAL#${START_GATEWAY}#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_GW_STATE_FILE} ${NEW_GW_STATE_FILE}+
    if [ $? -eq 0 ]; then
        mv ${NEW_GW_STATE_FILE}+ ${NEW_GW_STATE_FILE}
    fi

}

##############################################################################
# Display the summary.
##############################################################################
DisplaySummary() {
  $CLEAR

  print ""
  print "`$GETTEXT 'New gateway instance installation summary'`"
  print ""
  print "`$GETTEXT '  New gateway instance name               : '`" "$GW_GATEWAY_PROFILE"
  print "`$GETTEXT '  Gateway host                            : '`" "$GW_HOST"
  print "`$GETTEXT '  Gateway port                            : '`" "$GW_PORT"
  print "`$GETTEXT '  Gateway protocol                        : '`" "$GW_PROTOCOL"
  print "`$GETTEXT '  Portal Server orLoadBalancer URL        : '`" "$LOAD_BALANCER_URL"
  print "`$GETTEXT '  Identity Server Host                    : '`" "$SERVER_HOST"
  print "`$GETTEXT '  Identity Server Port                    : '`" "$SERVER_PORT"
  print "`$GETTEXT '  Identity Server Protocol                : '`" "$SERVER_PROTOCOL"
  print "`$GETTEXT '  Organization DN                         : '`" "$IS_ORG_DN"
  print "`$GETTEXT '  Identity server deploy URI              : '`" "$IS_DEPLOY_URI"
  print "`$GETTEXT '  Identity server 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_GATEWAY"
  print ""
}

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

##############################################################################
# Collect info, display summary, and create new instance.
##############################################################################
CreateInstance() {

  local CREATED="n"

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

    # Clear the screen.
    $CLEAR
    print ""

    # Get the other information needed from the user.
    GetNewInfo

    # 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.
        WriteNewGWInfo
  	print ""
	print "`$GETTEXT 'Configuring new gateway instance...'`"
        # Configure the new gateway instance
        ${LIB_DIR}/postinstall_GW ${GW_GATEWAY_PROFILE}
  	print ""

    fi

  done

}

##############################################################################
# Removes a gateway instance
##############################################################################

RemoveInstance() {

    print ""

    QuestionWithoutDefault "`$GETTEXT 'What is the name of the gateway 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: Gateway 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 "`$GETTEXT 'Uninstallation in progres...'`"
	print ""
        if [ "$BACKUP_MODE" = "n" ]; then
	    ${LIB_DIR}/remove_GW --purge $INSTANCE_NAME
	else
	    ${LIB_DIR}/remove_GW $INSTANCE_NAME
	fi

    fi

}


##############################################################################
# Removes a gateway instance
##############################################################################

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_GW --purge
	else
	    ${LIB_DIR}/remove_GW
	fi
    fi

}

##############################################################################
# List the existing gateway instances.
##############################################################################

ListGWInstances() {

    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/GWConfig-${INSTANCE_NAME}.properties ]; then
                INSTANCES="${INSTANCES} ${INSTANCE_NAME}"
            fi

        fi

    done

    # Print the instances.
    if [ "${INSTANCES}" != "" ]; then
        print "`$GETTEXT 'Detected gateway 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 gateway instance'`;CREATE;"
  if [ "$INSTANCES" != "" ]; then
      MENU_ITEMS="$MENU_ITEMS`$GETTEXT 'Remove a gateway instance'`;REMOVE;"
      MENU_ITEMS="$MENU_ITEMS`$GETTEXT 'Remove all gateway 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

}

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

StartMultiInstance() {

    local DONE="n"

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

	# Clear the screen
	$CLEAR
	print ""

        # List the existing gateway instances.
        ListGWInstances

        # 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, GW_BASEDIR, GW_HOST, GW_IP, GW_VIRTUAL_HOST, SSL_CONNECTION
GetExistingGWInfo

# Enter the main loop.
StartMultiInstance

exit 0

