#
#  Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information 
#  and should be treated as confidential

##########################################################################
# set up apache / tomcat

if [ -z "${INSTDIR}" ] ; then
  # Not called from tarantella command or postinstall
  exit
fi

ans_host=`hostname`
if [ -f "$TTADIR/$ans_host.answers" ]; then
    echo "Loading Answers from ${TTADIR}/$ans_host.answers"
    . "$TTADIR/$ans_host.answers"
fi

# Make sure we have sane values in the required config variables
[ -z "${a_AsadPort}" ] && a_AsadPort=3144 export a_AsadPort
[ -z "${a_httpport}" ] && a_httpport=80 export a_httpport
[ -z "${a_httpsport}" ] && a_httpsport=443 export a_httpsport

GetPrivUsrGrp()
{
    cat ${TTAINSTDIR}/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
	'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
	$1 == "tarantella.config.array.privilegeduser" { u = $2 }
	$1 == "tarantella.config.array.webserveruser" { wu = $2 }
	$1 == "tarantella.config.array.privilegedgroup" { g = $2 }
	END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`


#Added
xflag=""
[ "$trace" = "x" ] && xflag="-x"
PortOffset=`expr $a_AsadPort - 3144`
PEERPORT=`expr 5427 + $PortOffset`
SECUREPORT=`expr 5307 + $PortOffset`
#Added end

isnumeric()
{
   stripped=`echo "$1" | tr -cd '[0-9]'`
   [ -n "$1" -a "$1" = "${stripped}" ] && return 0 || return 1
}

notnumeric()
{
   isnumeric "$1" && return 1 || return 0
}

LISTEN_80="Listen 80" LISTEN_443="Listen 443"
DONT_LISTEN_80="#Listen 80" DONT_LISTEN_443="#Listen 443"
LISTEN_HTTP=${TMPDIR:-/tmp}/listen0_$$ LISTEN_HTTPS=${TMPDIR:-/tmp}/listen1_$$
rm -rf "${LISTEN_HTTP}" "${LISTEN_HTTPS}" 2>/dev/null
# set up default ports in case we don't manage to get settings from elsewhere
echo "${LISTEN_80}" >${LISTEN_HTTP}; echo "${LISTEN_443}" >${LISTEN_HTTPS}

# extract "Listen" directives from an Apache httpd.conf file
getHTTPListenDirectives() {
    conffile=$1
    awk '$1=="<IfDefine" && $2=="SSL>" {
	state = 1
    }
    $1=="</IfDefine>" {
	state = 0
    }
    state==0 && $1=="Listen" && bGotListenHttp==0 {
	print >"'"${LISTEN_HTTP}"'"; bGotListenHttp = 1
    }
    state==1 && $1=="Listen" && bGotListenHttps==0 {
	print >"'"${LISTEN_HTTPS}"'"; bGotListenHttps = 1
    }
    END {
	if (bGotListenHttp==0) print "'"${DONT_LISTEN_80}"'" >"'"${LISTEN_HTTP}"'"
	if (bGotListenHttps==0) print "'"${DONT_LISTEN_443}"'" >"'"${LISTEN_HTTPS}"'"
    }' ${conffile}
}

#PREVIOUS_HTTPD_CONF="${INSTDIR}/webserver/apache/${PREVIOUS_apache}/conf.${UPGRADE}/httpd.conf"
NEW_APACHE_VER=`cat "${INSTDIR}/var/info/apacheversion"`
HTTPD_CONF="${INSTDIR}/webserver/apache/${NEW_APACHE_VER}/conf/httpd.conf"
a_httpport=80		# sensible default in case we fail to get the pre-upgrade port number
getHTTPListenDirectives "${HTTPD_CONF}"
a_httpport=`awk '{print $2}' <${LISTEN_HTTP}`
notnumeric "${a_httpport}" && {
    # maybe it was (eg) 127.0.0.1:80
      case "${a_httpport}" in
      *:*) a_httpport=`expr "${a_httpport}" : '.*:\([^:]*\)'` ;;
      esac
}
notnumeric "${a_httpport}" && {
      # try getting the port number from the Port directive instead of the Listen directive
      a_httpport=`awk '$1=="Port"{print $2}' "${HTTPD_CONF}"`
}
notnumeric "${a_httpport}" && a_httpport=80	# oh well, we tried ... just set it to 80 and hope for the best
a_httpsport=443		# sensible default in case we fail to get the pre-upgrade port number
getHTTPListenDirectives "${HTTPD_CONF}"
a_httpsport=`awk '{print $2}' <${LISTEN_HTTPS}`
notnumeric "${a_httpsport}" && {
      # maybe it was (eg) 127.0.0.1:443
      case "${a_httpsport}" in
      *:*) a_httpsport=`expr "${a_httpsport}" : '.*:\([^:]*\)'` ;;
      esac
}
notnumeric "${a_httpsport}" && {
      # try getting the port number from the Port directive instead of the Listen directive
      a_httpsport=`awk '$1=="Port"{print $2}' "${HTTPD_CONF}"`
}
notnumeric "${a_httpsport}" && a_httpsport=443	# oh well, we tried ... just set it to 443 and hope for the best

nextfreeport() {
    [ -z "$1" ] && return
    [ "$1" -lt 1 ] && return
    port=$1
    probe="$INSTDIR/bin/bin/ttahostprobe localhost:"

    while [ "${port}" -eq "${a_httpport}" -o "${port}" -eq "${a_httpsport}" -o "`${probe}${port}`" = "y" ]; do
	port=`expr $port + 1`
    done
    echo $port
}

# PATCH Start
if [ -f ${INSTDIR}/webserver/config_install ]; then
  CONFIG_INSTALL=config_install
elif [ -f ${INSTDIR}/webserver/config_install.sh ]; then
  CONFIG_INSTALL=config_install.sh
fi
# PATCH End

if [ -f ${INSTDIR}/webserver/${CONFIG_INSTALL} ]; then
(
    echo ${N} "${i18n_config_webservices}${C}" | tee -a $LOGFILE
    cd ${INSTDIR}/webserver
  A_VER=`cat "${INSTDIR}/var/info/apacheversion"`
  T_VER=`cat "${INSTDIR}/var/info/tomcatversion"`

    # Set security context on dynamically loadable Apache modules, if applicable (SELinux).
    # First try to find a security context that we can copy:
    sec_con_reference=""
    for sec_con_preferred in textrel_shlib_t texrel_shlib_t shlib_t; do
  sec_con_reference=`find /usr/lib -name '*.so' -print | xargs ls -dZ 2>/dev/null | grep ":${sec_con_preferred}" | sed 1q`
  [ -n "${sec_con_reference}" ] && {
      reference_file=`expr "${sec_con_reference}" : '.* \(/usr/lib/.*\)'`
      [ -n "${reference_file}" ] && (
    cd "${INSTDIR}/webserver/apache/${A_VER}/modules"
    chcon --reference="${reference_file}" *.so 2>/dev/null
      )
      break
  }
    done

    (
  # Put INSTDIR/lib in LD_LIBRARY_PATH for the Apache binaries
  cd "${INSTDIR}/webserver/apache/${A_VER}/bin"
  cp -p envvars envvars.$$; sed "/^[  ]*LD_LIBRARY_PATH=.*:/s|:|:${INSTDIR}/lib:|" envvars.$$ >envvars; rm -f envvars.$$ 2>/dev/null
  cp -p envvars envvars.$$; sed "/^[  ]*LD_LIBRARY_PATH=[^:]*\$/s|\"[   ]*\$|:${INSTDIR}/lib&|" envvars.$$ >envvars; rm -f envvars.$$ 2>/dev/null
    )


    HTTP_PORT=$a_httpport
    if [ -n "${a_httpsport}" ]; then
	HTTPS_PORT=${a_httpsport}
    else
	HTTPS_PORT=443
    fi
    if [ -n "${a_warpport}" ]; then
	WARP_PORT=${a_warpport}
    else
	WARP_PORT=`nextfreeport 8009`
    fi
    if [ -n "${a_shutdownport}" ]; then
	SHUTDOWN_PORT=${a_shutdownport}
    else
	SHUTDOWN_PORT=`nextfreeport 8005`
    fi
    PATCH="--patch"

    PFILE="${INSTDIR}/webserver/tomcat/${T_VER}/shared/classes/com/tarantella/tta/webservices/client/apis/Resources.properties"

    [ -z "`grep '^logdir=' ${PFILE} 2>/dev/null`" ] && echo "logdir=${INSTDIR}/webserver/tomcat/${T_VER}/logs" >>${PFILE}
    [ -z "`grep '^logginglevel=' ${PFILE} 2>/dev/null`" ] && echo "logginglevel=INFO" >>${PFILE}
    
    /bin/sh ${xflag} ./${CONFIG_INSTALL} --ttaversion `echo ${PRODUCT_VERSION_FULL}|tr -d .` \
	$A_VER $T_VER $HTTP_PORT $HTTPS_PORT \
	$WARP_PORT $SHUTDOWN_PORT $PEERPORT $webservusr $privgrp \
	${INSTDIR} ${PATCH} >> $LOGFILE 2>&1
    ret=$?

    if [ $ret -ne 0 ]; then
	    printf "${i18n_pf1_scriptfail}" "${ret}" | tee -a $LOGFILE
	    printf "${i18n_pf1_seesetuplog}" "${INSTDIR}/var/log/setup.log" >>$LOGFILE
	    exit 1
    fi
	    # ... and copy the VDI Broker properties file if present
	    VSBIMPROPS="webapps/sgd/WEB-INF/classes/com/oracle/sgd/vsbim/oracle-vdi-vsb.properties"
	    [ -n "${T_VER}" -a -n "${PREVIOUS_tomcat}" -a "${T_VER}" != "${PREVIOUS_tomcat}" -a \
	      -s "${INSTDIR}/webserver/tomcat/${PREVIOUS_tomcat}/${VSBIMPROPS}" ] &&
      {
	      cp -p "${INSTDIR}/webserver/tomcat/${PREVIOUS_tomcat}/${VSBIMPROPS}" \
		    "${INSTDIR}/webserver/tomcat/${T_VER}/${VSBIMPROPS}"
	    }

  \cp -rpP ${INSTDIR}/webserver/tomcat/${PREVIOUS_tomcat}/shared/classes/com/tarantella/tta/webservices/client/views ${INSTDIR}/webserver/tomcat/${T_VER}/shared/classes/com/tarantella/tta/webservices/client 2>/dev/null
  \cp -rpP ${INSTDIR}/webserver/tomcat/${PREVIOUS_tomcat}/shared/classes/com/sun ${INSTDIR}/webserver/tomcat/${T_VER}/shared/classes/com 2>/dev/null

    # Developers' Note: don't change the *format* of the next line, since
    # devinstall.sh relies on it.  The quoted string can be changed, however.
    _artemisurl="sgdadmin"

    _tomcatDir="${INSTDIR}/webserver/tomcat/`cat ${INSTDIR}/var/info/tomcatversion`"
    _attempts=0
    while [ ! -d "${_tomcatDir}/webapps/${_artemisurl}" ]; do
	sleep 3
	_attempts=`expr "${_attempts}" + 1`
	[ "${_attempts}" -gt 10 ] && break
    done
    _d="${_tomcatDir}/webapps/${_artemisurl}/security"
    [ -d "${_d}" ] || {
	mkdir -p "${_d}" 2>/dev/null; chown $webservusr "${_d}"; chgrp $privgrp "${_d}"; chmod 750 "${_d}"
    }
    (
	cd "${_d}"
	rm -f sslkeystore 2>/dev/null; ln -s ${INSTDIR}/var/info/certs/sslkeystore .
	rm -f key 2>/dev/null; ln -s ${INSTDIR}/var/info/key .
    )
    _d="${_tomcatDir}/webapps/${_artemisurl}/images"
    [ -d "${_d}" ] || {
	mkdir -p "${_d}" 2>/dev/null; chown $webservusr "${_d}"; chgrp $privgrp "${_d}"; chmod 750 "${_d}"
    }
    (
	cd "${_d}"
	rm -f icons 2>/dev/null; ln -s ../../sgd/resources/images/icons .
    )


  # Sort out webserver file/directory permissions.
  # Default permissions are:
  # 	directories:	rwxr-x--- / root / ttaserv
  #	files:		rw-r----- / root / ttaserv
  # unless specifically overridden below
  PERMS="/tmp/perms$$"; rm -f ${PERMS} 2>/dev/null

  [ -z "${TTA_DEVINSTALL}" ] && {
	  find ${INSTDIR}/webserver ! \( -type l -o -user root \) -print | tee -a ${PERMS} | xargs chown root 2>/dev/null
  }
  find ${INSTDIR}/webserver ! \( -type l -o -group $privgrp \) -print | tee -a ${PERMS} | xargs chgrp $privgrp 2>/dev/null
  find ${INSTDIR}/webserver ! \( -type l -o -type d -o -perm 640 \) -print | tee -a ${PERMS} | xargs chmod 640 2>/dev/null
  find ${INSTDIR}/webserver -type d ! -perm 750 -print | tee -a ${PERMS} | xargs chmod 750 2>/dev/null

  # Fitz 605456: Make Tomcat's conf directory 770.
  find ${INSTDIR}/webserver/tomcat -type d -name conf ! -perm 770 -print | tee -a ${PERMS} | xargs chmod 770 2>/dev/null

  # Log directories:	rwxrwx--- / ttaserv / ttaserv
  # - files therein:	rw-rw---- / ttaserv / ttaserv
  A_VER=`cat "${INSTDIR}/var/info/apacheversion"`
  T_VER=`cat "${INSTDIR}/var/info/tomcatversion"`
  LOGDIRS=`find "${INSTDIR}/webserver/apache" "${INSTDIR}/webserver/tomcat" -type d \( -name log -o -name logs -o -name work \) -print`
  if [ -n "$LOGDIRS" ]; then
	  find $LOGDIRS -type d ! -perm 770 -print | tee -a ${PERMS} | xargs chmod 770 2>/dev/null
	  find $LOGDIRS ! \( -type d -o -perm 660 \) -print | tee -a ${PERMS} | xargs chmod 660 2>/dev/null
	  find $LOGDIRS ! -user $webservusr -print | tee -a ${PERMS} | xargs chown $webservusr 2>/dev/null
  fi

  # Executable files:	rwxr-x--- / root / ttaserv
  BINDIRS=`find ${INSTDIR}/webserver -type d \( -name bin -o -name build \) -print`
  [ -n "$BINDIRS" ] && find $BINDIRS ! \( -type d -o -perm 750 \) -print | tee -a ${PERMS} | xargs chmod 750 2>/dev/null

  # Shell scripts:	rwxr-x--- / ttaserv / ttaserv
  find ${INSTDIR}/webserver ! \( -type l -o -type d -o -perm 750 \) \( -name '*.sh' -o -name '*.ini' -o -name 'libtool' \) -print | egrep -v '/ttatcc\.sh$' | tee -a ${PERMS} | xargs chmod 750 2>/dev/null
  find ${INSTDIR}/webserver ! \( -type l -o -type d -o -user $webservusr \) \( -name '*.sh' -o -name '*.ini' -o -name 'libtool' \) -print | tee -a ${PERMS} | xargs chown $webservusr 2>/dev/null

  # Odds and ends

  rm -f "${PERMS}" 2>/dev/null
)
fi

exit 0
