#!/bin/bash

# Logic Control Values
Language=en
Product=Server
MajorVersion=11
MinorVersion=5
MaintVersion=0
BuildNbr=8410
QFE_Nbr=1
QFE_TYPE=Patch
InstallTime=`date '+%m/%d/%y %H:%M:%S'`

if [ ${MaintVersion} -eq 0 ]
then
	Version="$MajorVersion.$MinorVersion"
else
	Version="$MajorVersion.$MinorVersion.$MaintVersion"
fi

#usually same as $Version
FileNameVersion="$MajorVersion.$MinorVersion.$MaintVersion"
OurProductName=WMXServer
ArcGISTargetProductVersion="${Version}"

Product_Release_Version="${Version}"

QFE_ID="QFE-$OurProductName-$MajorVersion.$MinorVersion.$BuildNbr"

bln_oldGeoEventInstalled=false
bln_isAMI=false

case ${Product} in
    Server) AGS_ProductNameShort=ArcGISServer; ProductNameFull="ArcGIS Workflow Manager Server $Product_Release_Version"; OurProductNameFull="ArcGIS Workflow Manager Server $Product_Release_Version $QFE_TYPE $QFE_Nbr";;
esac

case `uname` in
    Linux)   Platform=Linux;;
esac

# L10N Strings
# [en]
#------------------------------------------------------------------------------------------------------------
INSTALL_FILE_IS_NOT_FOUND="Install file is not found."
EXPECTED_LOCATION="Expected location"
THIS_INSTALL_WILL_NOW_EXIT="This install will now exit."
A_VALID_PRODUCT_FOR_THIS_SETUP_WAS_NOT_DETECTED="A valid product for this setup was not detected."
VALID_PRODUCT="Valid product"
VALID_VERSION="Valid version"
DETECTED_PREVIOUS_VERSION="Upgrading to $OurProductNameFull..."
DETECTED_ANOTHER_VERSION="The $OurProductNameFull or later version of this product is already installed." 
INSTALL_START="Please wait while $OurProductNameFull is being installed..." 
UNINSTALL_START="Please wait while $OurProductNameFull is being uninstalled."
UNINSTALL_END="$OurProductNameFull is uninstalled successfully..."
INSTALL_END="$OurProductNameFull is installed successfully..."
#------------------------------------------------------------------------------------------------------------ 

# File Information
NodeName=`uname -n`
ScriptDir=`dirname $0`
ScriptName=`basename $0`
if echo ${ScriptDir} | grep '^./' >/dev/null 2>&1
then
    ScriptPath=`pwd``echo ${ScriptDir} | cut -d '.' -f2-`
elif echo ${ScriptDir} | grep '^/' >/dev/null 2>&1
then
    ScriptPath=${ScriptDir}
elif [ "${ScriptDir}" = "." ]
then
    ScriptPath=`pwd`
else
    ScriptPath=`pwd`/${ScriptDir}
fi

InstallFilePath=${ScriptPath}
# cd to the installfiles dir
cd ${InstallFilePath} >/dev/null 2>&1

# Load the localized installer strings file if exist
# the script will load the first strings-[language].ini e.g. strings-zh_CN.ini.
#
ResourceFileName=$(find . -maxdepth 1 -type f -name "strings-*.ini" | head -1)

if echo ${ResourceFileName} | grep '^./' >/dev/null 2>&1
then
    ResourceFileName=`echo ${ResourceFileName} | cut -c2-`
else
    ResourceFileName=${ResourceFileName}
fi

if [ -f ${InstallFilePath}/${ResourceFileName} ] 
then 
    source ${InstallFilePath}/${ResourceFileName} >/dev/null 2>&1
fi

echo "${INSTALL_START}"

# Get the InstallFileName and trim off the ./ if it is there
# the script will find the latest setup file match the filename pattern
#
InstallFileName=$(find . -maxdepth 1 -type f -name "WorkflowManager-${FileNameVersion}.*-${QFE_TYPE}${QFE_Nbr}.tar.gz" | head -1)

if echo ${InstallFileName} | grep '^./' >/dev/null 2>&1
then
    InstallFileName=`echo ${InstallFileName} | cut -c2-`
else
    InstallFileName=${InstallFileName}
fi

UserHome=${HOME}

#user info: the user install GeoEvent Server has to be the user who install ArcGIS Server as well as running the ArcGIS Server service/daemon
RunAsUser=`whoami`

# GeoEvent Installer script 
#   [Program Flow] 
# 
#   1) Check for resource ProductVersion.tar.gz file. It should be 
#      located in the same directory as the install script.  
#         a) If not found, notify user and exit. ***L10N String*** 

if [ ! -f ${InstallFilePath}/${InstallFileName} ] 
then 
    echo ${INSTALL_FILE_IS_NOT_FOUND}
    echo ${EXPECTED_LOCATION}: ${ScriptPath}
    echo
    echo ${THIS_INSTALL_WILL_NOW_EXIT}
    exit 1
fi


#   2) Check if regular ArcGIS properties file exist in the format of $HOME/.ESRI.properties.${NodeName}.${ArcGISTargetProductVersion}? 
#		If not, look for static AGS properties file exist (AMI machine). If yes, use the static filename as $HOME/.ESRI.properties.arcgis.${ArcGISTargetProductVersion}.
#       a) If none found, notify user and exit. ***L10N String***
# Get the PropFile and trim off the ./ if it is there
# the swcript will find the latest config file match the filename pattern
#

PropFile=$(find ${UserHome} -name ".ESRI.properties.${NodeName}.${ArcGISTargetProductVersion}" | head -1)
if [ -f ${PropFile} ] && [ "x${PropFile}x" != "xx" ]
then  
	bln_isAMI=false 
	
else
	PropFile=$(find ${UserHome} -name ".ESRI.properties.arcgis.${ArcGISTargetProductVersion}" | head -1)
	if [ -f ${PropFile} ] && [ "x${PropFile}x" != "xx" ]
	then
		bln_isAMI=true
	else
		bln_isAMI=false 
	fi
	
fi

if echo ${PropFile} | grep '^./' >/dev/null 2>&1
then
    PropFile=`echo ${PropFile} | cut -c2-`
else
    PropFile=${PropFile}
fi
# Get the correct version from filename; if the properties file defined above is not found; AGS_Version will be empty
if [ "$bln_isAMI" = true ]
then
	AGS_Version=$(echo ${PropFile} | sed 's/.*'".ESRI.properties.arcgis."'//')
else
	AGS_Version=$(echo ${PropFile} | sed 's/.*'".ESRI.properties.${NodeName}."'//')

fi

# check to make sure the ArcGIS version match
case ${AGS_Version} in    
    "$Version") ;;
	*)
		echo ${A_VALID_PRODUCT_FOR_THIS_SETUP_WAS_NOT_DETECTED}
		echo
		echo "  * ${VALID_PRODUCT}: ${ProductNameFull}"		
		echo
		echo ${THIS_INSTALL_WILL_NOW_EXIT}
		exit 1
	;;
esac

case `uname` in
    Linux)   Platform=Linux;;
esac

if [ -f ${PropFile} ]
then   
    InstallDir=`grep Z_ArcWorkflowManager_INSTALL_DIR ${PropFile} | cut -d '=' -f2`    
    AGS_InstallDir=`grep Z_${AGS_ProductNameShort}_INSTALL_DIR ${PropFile} | cut -d '=' -f2`    
fi

if [ "x${InstallDir}x" = "xx" ]
then
    echo ${A_VALID_PRODUCT_FOR_THIS_SETUP_WAS_NOT_DETECTED}
    echo
    echo "  * ${VALID_PRODUCT}: ${ProductNameFull}"    
    echo
    echo ${THIS_INSTALL_WILL_NOW_EXIT}
    exit 1
fi

# delete all files  under data folder
rm -rf ${InstallDir}/data/*

PatchLogFile=${InstallDir}/.ESRI_WMXS_PATCH_LOG

# get the ArcGIS Server installdir
InstallDir=`dirname ${InstallDir}`


if [ -f ${PatchLogFile} ]
then   
    Installed_QFE_ID=`grep QFE_ID ${PatchLogFile} | cut -d ':' -f2`    
    Installed_BuildNbr=`cut -d '.' -f3 <<< "$Installed_QFE_ID"`
else
    Installed_BuildNbr=0
fi


if [ ${Installed_BuildNbr} -ge ${BuildNbr} ]
then
    Installed_QFE_TITLE=`grep QFE_TITLE ${PatchLogFile} | cut -d ':' -f2`    
    echo ${DETECTED_ANOTHER_VERSION}
    echo "Detected:${Installed_QFE_TITLE} installed." 
    echo ${THIS_INSTALL_WILL_NOW_EXIT}
    exit 1
fi

# cd into arcgis installdir instead
cd ${InstallDir} >/dev/null 2>&1

if [ "${?}" = "0" ]
then
    # removed old log4j lib
    rm -rf {InstallDir}/WorkflowManager/lib/shared/org.apache.logging.log4j.log4j-api-2.14.1.jar
    rm -rf {InstallDir}/WorkflowManager/lib/shared/org.apache.logging.log4j.log4j-core-2.11.0.jar
    # install new version of log4j lib
    tar xf ${InstallFilePath}/${InstallFileName} >/dev/null 2>&1
fi


#  update uninstall filelist

InstalledFilesList=${AGS_InstallDir}/.Setup/WorkflowManager_InstalledFiles.list

# Clean up any existing files
# rm -f ${UninstallFile} ${InstalledFilesList} ${InstalledFilesList}.dirs ${InstalledFilesList}.root.dirs


# Output listing of install files to be removed by uninstaller
tar tf ${InstallFilePath}/${InstallFileName} | sed '/^$/d' >> ${InstalledFilesList} 2>/dev/null

echo "./WorkflowManager/.ESRI_WMXS_PATCH_LOG" >> ${InstalledFilesList}

# Create Patch log dynamically
cat > ${PatchLogFile} << EOF
#START
QFE_TYPE: ${QFE_TYPE}
QFE_ID: ${QFE_ID}
QFE_TITLE: ${OurProductNameFull}
INSTALL_TIME: ${InstallTime}
#END
EOF

# Set install permissions
chmod -R go= ${PatchLogFile}


echo "${INSTALL_END}"

#   8) Done.
