#!/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 ES_HOME environment variable is set
if [ -z "$ES_HOME" ]; then
  ES_HOME=/usr/share/elasticsearch
fi

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

if ! grep -q '## OpenDistro Performance Analyzer' /etc/elasticsearch/jvm.options; then
   CLK_TCK=`/usr/bin/getconf CLK_TCK`
   echo >> /etc/elasticsearch/jvm.options
   echo '## OpenDistro Performance Analyzer' >> /etc/elasticsearch/jvm.options
   echo "-Dclk.tck=$CLK_TCK" >> /etc/elasticsearch/jvm.options
   echo "-Djdk.attach.allowAttachSelf=true" >> /etc/elasticsearch/jvm.options
   echo "-Djava.security.policy=file:///usr/share/elasticsearch/plugins/opendistro-performance-analyzer/pa_config/es_security.policy" >> /etc/elasticsearch/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 opendistro performance analyzer to start and stop along with elasticsearch.service'
        systemctl daemon-reload
        systemctl enable opendistro-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/elasticsearch/plugins/opendistro-performance-analyzer/pa_bin/performance-analyzer-agent /usr/share/elasticsearch -d"
    fi
fi
