#!/bin/sh
set -e

# Make sure the OPENSEARCH_HOME environment variable is set
if [ -z "$OPENSEARCH_HOME" ]; then
    OPENSEARCH_HOME=/usr/share/opensearch
fi

# Prepare the RCA reader process for execution
cp -r "$OPENSEARCH_HOME"/plugins/opensearch-performance-analyzer/performance-analyzer-rca $OPENSEARCH_HOME
if [ -f "$OPENSEARCH_HOME"/bin/opensearch-performance-analyzer/performance-analyzer-agent-cli ]; then
  mv "$OPENSEARCH_HOME"/bin/opensearch-performance-analyzer/performance-analyzer-agent-cli "$OPENSEARCH_HOME"/bin
  rm -rf "$OPENSEARCH_HOME"/bin/opensearch-performance-analyzer
fi
mkdir -p "$OPENSEARCH_HOME"/data
mkdir -p "/var/lib/opensearch"
touch "$OPENSEARCH_HOME"/data/rca_enabled.conf
echo 'true' > "$OPENSEARCH_HOME"/data/rca_enabled.conf
echo 'true' > /var/lib/opensearch/performance_analyzer_enabled.conf
echo 'true' > /var/lib/opensearch/rca_enabled.conf
chown opensearch /var/lib/opensearch/performance_analyzer_enabled.conf
chown opensearch /var/lib/opensearch/rca_enabled.conf
chown -R opensearch "$OPENSEARCH_HOME/performance-analyzer-rca"
chmod a+rw /tmp

if ! grep -q '## OpenSearch Performance Analyzer' /etc/opensearch/jvm.options; then
   CLK_TCK=`/usr/bin/getconf CLK_TCK`
   echo >> /etc/opensearch/jvm.options
   echo '## OpenSearch Performance Analyzer' >> /etc/opensearch/jvm.options
   echo "-Dclk.tck=$CLK_TCK" >> /etc/opensearch/jvm.options
   echo "-Djdk.attach.allowAttachSelf=true" >> /etc/opensearch/jvm.options
   echo "-Djava.security.policy=file:///usr/share/opensearch/plugins/opensearch-performance-analyzer/pa_config/opensearch_security.policy" >> /etc/opensearch/jvm.options
fi

IS_UPGRADE=false
# Below codeblock is using the fact that postinst script is called with the most-recently configured version.
# In other words, a fresh installed will be called like "postinst configure" with no previous version ($2 is null)
if [ -z "$2" ]; then
  # If $2 is null, this is an install
  IS_UPGRADE=false
else
  # otherwise this is an upgrade
  IS_UPGRADE=true
fi

#DEBHELPER#

if [ "x$IS_UPGRADE" != "xtrue" ]; then
    if command -v systemctl > /dev/null; then
        echo '# Enabling OpenSearch performance analyzer to start and stop along with opensearch.service'
        systemctl daemon-reload
        systemctl enable opensearch-performance-analyzer.service || true

    elif command -v chkconfig >/dev/null; then
        echo "### Non systemd distro. Please start and stop performance analyzer manually using the command: "
        echo "sh /usr/share/opensearch/plugins/opensearch-performance-analyzer/pa_bin/performance-analyzer-agent /usr/share/opensearch -d"
    fi
fi

exit 0
