#!/bin/sh
###############################################################################
# WebSphere Application Server liberty admininstrative pre-uninstall script for 
# IBM i
#
# Copyright IBM Corp. 2012, 2013
# The source code for this program is not published or other-
# wise divested of its trade secrets, irrespective of what has
# been deposited with the U.S. Copyright Office.
# 
# ----------------------------------------------------------------------------
#
# Run the _iPreUninstallUtility script before removing product files on IBM i. 
# However, this step is only for manual administrative "unzip" 
# installations. Do not use this command for manual developer installations.
# The administrator must have *ALLOBJ and *SECADM special authority to run this 
# script.
#
#

usage() {
  echo ""
  echo "Usage: _iPreUninstallUtility [options]"
  echo ""
  echo "Options:"
  echo "  --action [ DLTPRDLOD | DLTPRDLIB | DLTSHRPRDLIB ]"
  echo "  --appdatadir im_application_data_directory"
  echo ""
  echo "The --appdatadir option is required for the"
  echo "DLTPRDLOD action and is ignored by all other actions."
  exit 1
}

set_wlp_install_dir() {
        CUR_DIR=`pwd`
        WLP_DIR=`dirname ${0}`/../../../../
        cd "${WLP_DIR}"
        WLP_INSTALL_DIR=`pwd`
        cd "${CUR_DIR}"
}

##
## evalJavaPropsFile: Reads Java properties from file specified in $1,
## and for every property it replaces all "." with "_" in the property name, 
## sets the resulting named script variable to the property value and exports 
## the variable.
evalJavaPropsFile()
{
  if [ -f "$1" ]; then
    while read -r line; do
      case $line in
      \#*);;
      *=*)
        # Only accept alphanumeric variable names to avoid eval complexities.
        if var=`echo "$line" | sed -e 's/^\([a-zA-Z0-9_\.][a-zA-Z0-9_\.]*\)=.*/\1/'`; then
          var=`echo $var | sed -e 's/\./_/g'`
          value=\'`echo "$line" | sed -e 's/[^=]*=//' -e s/\'/\'\"\'\"\'/g`\'
          eval "$var=$value; export $var"
        fi
      esac
    done < "$1"
  fi
}

delete_prod_lib() {
  echo "Executing delete_prod_lib"
  if [ -e ${WAS_PRODUCT_LIB_PATH} ]; then
    system "QSYS/DLTLIB LIB(${WAS_PRODUCT_LIB})"
    if [ $? -ne 0 ]; then
      ERR_CHK=1
    fi
  fi
}

delete_shared_prod_lib() {
  echo "Executing delete_shared_prod_lib"
	ALPHABET="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Z"

	PROD_LIB=${SHR_PROD_LIB}A
	DELETE_SHR_PRD_LIB=true
	for letter in $ALPHABET
	do
		if [ -e /QSYS.LIB/${PROD_LIB}.LIB ]; then
			DELETE_SHR_PRD_LIB=false
			echo "Library /QSYS.LIB/${PROD_LIB}.LIB exists, so the shared library will not be deleted"
		else
			echo "Library /QSYS.LIB/${PROD_LIB}.LIB does not exist"
		fi	
		PROD_LIB=${SHR_PROD_LIB}${letter}
	done

	if [ "$DELETE_SHR_PRD_LIB" = "true" ]; then
  	echo "Clearing output queue"
  	system "QSYS/CLROUTQ OUTQ(QWAS9/QWASOUTQ)"
      if [ $? -ne 0 ]; then
        ERR_CHK=1
      fi
  	echo "Removing TCP Service Table port entries"
  	system "QSYS/CALL PGM(QWAS9/QWASCLN)"
      if [ $? -ne 0 ]; then
        ERR_CHK=1
      fi
  	echo "Ending QWAS9 subsystem"
  	system "QSYS/ENDSBS SBS(QWAS9) OPTION(*IMMED)"
  	sleep 5
  	echo "Since this is the last product, we can safely remove the Base Product Load QWAS00M"
      export QIBM_MULTI_THREADED=N
      system "CALL QSYS/QSZDLTPL PARM('$1   QWAS9    ' '')"
      if [ $? -ne 0 ]; then
        ERR_CHK=1
      fi
  	system "QSYS/DLTLIB LIB(QWAS9)"
      if [ $? -ne 0 ]; then
        ERR_CHK=1
      fi
  else 
  	echo "Did not remove the shared product library (QWAS9) because other product installations are using the shared library"
	fi
}

delete_prod_load() {

  APP_DATA_LOC=$1
	echo "IM App Data location used: ${APP_DATA_LOC}"
	if [ "$PRODUCT_EDITION" = "EXPRESS" ]; then
		grep package.*com.ibm.websphere.liberty.EXPRESS.v90 ${APP_DATA_LOC}/installed.xml > tmp
		grep package.*com.ibm.websphere.liberty.EXPRESSTRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.liberty.WEBENAB.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.EXPRESS.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.EXPRESSTRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.WEBENAB.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		PROD_LOAD=QWAS01M
		echo "Product Load = $PROD_LOAD"
	fi
	if [ "$PRODUCT_EDITION" = "BASE" ]; then
		grep package.*com.ibm.websphere.liberty.BASE.v90 ${APP_DATA_LOC}/installed.xml > tmp
		grep package.*com.ibm.websphere.liberty.BASETRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.BASE.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.BASETRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.DEVELOPERS.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.DEVELOPERSILAN.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		PROD_LOAD=QWAS02M
		echo "Product Load = $PROD_LOAD"
	fi
	if [ "$PRODUCT_EDITION" = "DEVELOPERS" ]; then
		grep package.*com.ibm.websphere.liberty.DEVELOPERS.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.liberty.DEVELOPERSILAN.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		PROD_LOAD=QWAS02M
		echo "Product Load = $PROD_LOAD"
	fi
	if [ "$PRODUCT_EDITION" = "ND" ]; then
		grep package.*com.ibm.websphere.liberty.ND.v90 ${APP_DATA_LOC}/installed.xml > tmp
		grep package.*com.ibm.websphere.liberty.NDTRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.ND.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		grep package.*com.ibm.websphere.NDTRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		PROD_LOAD=QWAS03M
		echo "Product Load = $PROD_LOAD"
	fi	
	if [ "$PRODUCT_EDITION" = "LIBERTY_CORE" ]; then
		grep package.*com.ibm.websphere.liberty.v90 ${APP_DATA_LOC}/installed.xml > tmp
		grep package.*com.ibm.websphere.liberty.TRIAL.v90 ${APP_DATA_LOC}/installed.xml >> tmp
		PROD_LOAD=QWAS05M
		echo "Product Load = $PROD_LOAD"
	fi
  count=0
  if [ -e tmp ]; then
    while read line   
      do  
        echo "$line"
        count=`expr $count + 1`
      done < tmp
    rm -f tmp

    echo "Total instances of package $PRODUCT_EDITION = $count"
	
    if [ -e /QSYS.LIB/QWAS9.LIB/${PROD_LOAD}.PRDLOD ]; then
      if [ $count -le 1 ]; then
        export QIBM_MULTI_THREADED=N
        system "CALL QSYS/QSZDLTPL PARM('${PROD_LOAD}   QWAS9    ' '')"
      else
        echo "Not removing product load $PROD_LOAD because there are more than one instance of this offering"
      fi
    else
      echo "Product load $PROD_LOAD was not found"
    fi
  else 
    echo "Could not find any instance of the offering $PRODUCT_EDITION, doing nothing"
  fi

}

do_default() {
#
  echo "Executing $ACTION"
  delete_prod_lib
  delete_shared_prod_lib
}


if [ "`uname`" != "OS400" ]; then
 exit 1
fi

# Validate parameters
# Do the whole 9 yards if no parameters are passed.

ACTION=DODEFAULT
ERR_CHK=0
APPDATADIR=

while [ $# -gt 0 ]; do
  case $1 in
    '--action') if [ $# -gt 1 ]; then
	  ACTION=$2;shift
	fi
    ;;
    '--appdatadir') if [ $# -gt 1 ]; then
	  APPDATADIR=$2;shift
	fi
    ;;
    *) usage
    ;;
  esac
  shift
done

echo "Action = $ACTION"

if [ ${ACTION} = "DLTPRDLOD" ]; then
  if [ ! ${APPDATADIR} ]; then
    usage
  fi
fi

SHR_PROD_LIB=QWAS9
set_wlp_install_dir

echo "WebSphere liberty profile install root is ${WLP_INSTALL_DIR}"

evalJavaPropsFile ${WLP_INSTALL_DIR}/lib/versions/WebSphereApplicationServer.properties
echo "Product edition is "${com_ibm_websphere_productEdition}
echo "Installation type is "${com_ibm_websphere_productInstallType}

IS_IM_INSTALL=
if [ ${com_ibm_websphere_productInstallType} = "InstallationManager" ]; then
  IS_IM_INSTALL=true
else
  SCRIPT_DIR="${WLP_INSTALL_DIR}/bin"
  LSOUT=`ls -ld ${SCRIPT_DIR}`
  SCRIPT_DIR_OWNER=
  FCOUNT=0
  for LSTOKEN in $LSOUT
    do
      FCOUNT=`expr $FCOUNT + 1`
      if [ $FCOUNT = 3 ]; then
        SCRIPT_DIR_OWNER=$LSTOKEN
        break
      fi
  done
  echo Owner of ${SCRIPT_DIR} directory is ${SCRIPT_DIR_OWNER}
  if [ ! ${SCRIPT_DIR_OWNER} = "QSYS" ]; then
    echo "Nothing to do because the \"iAdmin POSTINSTALL\" command has not been run."
    exit 0
  fi
fi

if [ ! -e ${WLP_INSTALL_DIR}/etc/default.env ]; then
  echo "Error: ${WLP_INSTALL_DIR}/etc/default.env does not exist"
  exit 1
fi
. ${WLP_INSTALL_DIR}/etc/default.env

PRODUCT_EDITION=${com_ibm_websphere_productEdition}

case "$ACTION" in
  'DODEFAULT') do_default
  ;;
  'DLTPRDLOD') delete_prod_load ${APPDATADIR}
  ;;
  'DLTPRDLIB') delete_prod_lib
  ;;
  'DLTSHRPRDLIB') delete_shared_prod_lib
  ;;
  *)
  usage
  ;;
esac

exit ${ERR_CHK}