#!/bin/sh
###############################################################################
# Administrative utility for IBM i
#
# Copyright IBM Corp. 2012
# 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.
# 
# ----------------------------------------------------------------------------
#
# The administrator must have *ALLOBJ and *SECADM special authority to run this 
# script.
#

usage() {
  echo ""
  echo "Usage: $0 "
  echo " {POSTINSTALL | PREUNINSTALL | "
  echo "  GRANTAUTH --rolename        server"
  echo "            --userprofilename user_profile_name [options]"
  echo ""
  echo "Options for GRANTAUTH:"
  echo "  --userdir wlp_usr_dir"
  echo "  --outputdir wlp_output_dir"
  echo ""
  echo "The only currently supported value for --rolename is \"server\"." 
  echo "You must specify \"server\" as the value for --rolename."
  echo ""
  echo "You must have *ALLOBJ and *SECADM special authority to use the"
  echo "POSTINSTALL and PREUNINSTALL commands."
  echo ""
  echo "You must have *ALLOBJ special permission, own or have *OBJMGT authority" 
  echo "to all objects in the specified directory subtrees to use the GRANTAUTH"
  echo "command."
  exit 1
}

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

##
## readServerEnv: Read server.env file and export environment variables.
readServerEnv()
{
  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
          value=\'`echo "$line" | sed -e 's/[^=]*=//' -e s/\'/\'\"\'\"\'/g`\'
          eval "$var=$value; export $var"
        fi
      esac
    done < "$1"
  fi
}

##
## installEnvDefaults: Set variable defaults for a non-server or nonexistent
##                     server command.
installEnvDefaults()
{
  readServerEnv "${WLP_INSTALL_DIR}/etc/default.env"

  if [ -z "${WLP_USER_DIR}" ]
  then
    if [ -z "${WLP_DEFAULT_USER_DIR}" ]
    then
      WLP_DEFAULT_USER_DIR=${WLP_INSTALL_DIR}/usr
    fi
    WLP_USER_DIR=${WLP_DEFAULT_USER_DIR}
  fi

  if [ -z "${WLP_OUTPUT_DIR}" ]
  then
    if [ -z "${WLP_DEFAULT_OUTPUT_DIR}" ]
    then
      WLP_DEFAULT_OUTPUT_DIR=${WLP_USER_DIR}/servers
    fi
    WLP_OUTPUT_DIR=${WLP_DEFAULT_OUTPUT_DIR}
  fi

}

##
## setLogsDir: Set LOGS_DIR
setLogsDir()
{
  readServerEnv "${WLP_INSTALL_DIR}/etc/server.env"
  installEnvDefaults
  LOGS_DIR=${WLP_OUTPUT_DIR}/.logs
}


if [ "`uname`" != "OS400" ]; then
  echo "The $0 command is supported only for IBM i."
  exit 1
fi

if [ ! $# -ge 1 ]; then
  usage
fi

WLPUSERDIR=
WLPOUTPUTDIR=
ROLENAME=
USERPROFILENAME=

ACTION=$1
shift
SAVED_OPTS=$@
while [ $# -gt 0 ]; do
  case $1 in
    '--userdir') if [ $# -gt 1 ]; then
	  WLPUSERDIR=$2;shift
	fi
    ;;
    '--outputdir') if [ $# -gt 1 ]; then
	  WLPOUTPUTDIR=$2;shift
	fi
    ;;
    '--rolename') if [ $# -gt 1 ]; then
        ROLENAME=$2;shift
        if [ ${ROLENAME} != "server" ]; then
          usage
        fi
      fi
    ;;
    '--userprofilename') if [ $# -gt 1 ]; then
        USERPROFILENAME=$2;shift
      fi
    ;;
    *) usage
    ;;
  esac
  shift
done


ERR_CHK=0
setWlpInstallDir

if [ ${ACTION} = "POSTINSTALL" ]; then
  if [ -f ${WLP_INSTALL_DIR}/etc/default.env ]; then
    rm ${WLP_INSTALL_DIR}/etc/default.env
    if [ $? -ne 0 ]; then
      echo "Error:  Cannot remove file ${WLP_INSTALL_DIR}/etc/default.env"
      exit 1
    fi
  fi
else
  SCRIPT_DIR="${WLP_INSTALL_DIR}/bin"
  SCRIPT_DIR_OWNER=`ls -ld ${SCRIPT_DIR} | awk '{ print $3 }'`
  if [ ! ${SCRIPT_DIR_OWNER} = "QSYS" ]; then
    if [ ${ACTION} = "PREUNINSTALL" ]; then
      echo "Nothing to do because the \"iAdmin POSTINSTALL\" command has not been run."
      exit 0
    else
      if [ ${ACTION} = "GRANTAUTH" ]; then
        echo "Error: Nothing to do because the \"iAdmin POSTINSTALL\" command has not been run."
        exit 1
      fi
    fi
  fi
  if [ ${ACTION} = "GRANTAUTH" ]; then
    if [ ! ${ROLENAME} ] || [ ! ${USERPROFILENAME} ]; then
      usage
    fi
  fi
fi

_SCRIPT_LOCATION="${WLP_INSTALL_DIR}/lib/native/os400/bin"
setLogsDir    
SAVED_UMASK=$(umask)
umask 022
if [ ! -d ${LOGS_DIR} ]; then
  /usr/bin/mkdir -p ${LOGS_DIR} 
  if [ $? != 0 ]; then
    echo "Error: Cannot create directory ${LOGS_DIR}."
    exit 1
  fi
fi

case "$ACTION" in
  'POSTINSTALL') 
    INSTALL_LOG=${LOGS_DIR}/$(basename $0)PostInstall.log
    if [ ! -f ${INSTALL_LOG} ]; then
      /usr/bin/touch -C 819 ${INSTALL_LOG}
    fi
    umask ${SAVED_UMASK}
    echo "***************************************************************" >> ${INSTALL_LOG} 
    echo `date` >> ${INSTALL_LOG}
    echo "Invoking ${_SCRIPT_LOCATION}/_iPostInstallUtility" >> ${INSTALL_LOG}
    echo "***************************************************************" >> ${INSTALL_LOG}
    ${_SCRIPT_LOCATION}/_iPostInstallUtility >> ${INSTALL_LOG} 2>&1 
    ERR_CHK=$?
    if [ ${ERR_CHK} != 0 ]; then
      echo "The POSTINSTALL action completed with errors.  See ${INSTALL_LOG} for details."
    else
      echo "The POSTINSTALL action completed successfully.  See ${INSTALL_LOG} for details."
    fi
  ;;
  'PREUNINSTALL')
    UNINSTALL_LOG=${LOGS_DIR}/$(basename $0)PreUninstall.log
    if [ ! -f ${UNINSTALL_LOG} ]; then
      /usr/bin/touch -C 819 ${UNINSTALL_LOG}
    fi
    umask ${SAVED_UMASK}
    echo "***************************************************************" >> ${UNINSTALL_LOG} 
    echo `date` >> ${UNINSTALL_LOG}
    echo "Invoking ${_SCRIPT_LOCATION}/_iPreUninstallUtility" >> ${UNINSTALL_LOG}
    echo "***************************************************************" >> ${UNINSTALL_LOG}
    ${_SCRIPT_LOCATION}/_iPreUninstallUtility >> ${UNINSTALL_LOG} 2>&1 
    ERR_CHK=$?
    if [ ${ERR_CHK} != 0 ]; then
      echo "The PREUNINSTALL action completed with errors.  See ${UNINSTALL_LOG} for details."
    else
      echo "The PREUNINSTALL action completed successfully.  See ${UNINSTALL_LOG} for details."
    fi
  ;;
  'GRANTAUTH')
    AUTH_LOG=${LOGS_DIR}/$(basename $0)GrantAuth.log
    if [ ! -f ${AUTH_LOG} ]; then
      /usr/bin/touch -C 819 ${AUTH_LOG}
    fi
    umask ${SAVED_UMASK}
    echo "***************************************************************" >> ${AUTH_LOG} 
    echo `date` >> ${AUTH_LOG}
    echo "Invoking ${_SCRIPT_LOCATION}/_iAuthUtility ${SAVED_OPTS}" >> ${AUTH_LOG}
    echo "***************************************************************" >> ${AUTH_LOG}
    ${_SCRIPT_LOCATION}/_iAuthUtility ${SAVED_OPTS} >> ${AUTH_LOG} 2>&1 
    ERR_CHK=$?
    if [ ${ERR_CHK} != 0 ]; then
      echo "The GRANTAUTH action completed with errors.  See ${AUTH_LOG} for details."
    else 
      echo "The GRANTAUTH action completed successfully.  See ${AUTH_LOG} for details."
    fi
  ;;
  *)
  usage
  ;;
esac

exit ${ERR_CHK}