#!/bin/sh
# We ignore errors in the rpm context because the package will be considered "installed"
# even if the postinst script fails. Therefore, the postinst script must be written such
# that it cannot fail

# set -e

# Post install script for Redhat like distros. Tested on CentOS 7.

# 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
case "$1" in
    1)
        # If $1=1 this is an install
        IS_UPGRADE=false
    ;;
    2)
        # If $1=2 this is an upgrade
        IS_UPGRADE=true
    ;;

    *)
        echo "post install script called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

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
