#
# This script is executed in the post-removal phase
#
#   On Debian,
#       $1=remove    : indicates a removal
#       $1=purge     : indicates an upgrade
#
#   On RedHat,
#       $1=0         : indicates a removal
#       $1=1         : indicates an upgrade

# source the default env file
if [ -f "${path.env}" ]; then
    . "${path.env}"
fi

export OPENSEARCH_PATH_CONF=${OPENSEARCH_PATH_CONF:-${path.conf}}

REMOVE_DIRS=false
REMOVE_JVM_OPTIONS_DIRECTORY=false
REMOVE_USER_AND_GROUP=false

case "$1" in

    # Debian ####################################################
    remove)
        REMOVE_DIRS=true
    ;;

    purge)
        REMOVE_DIRS=true
        REMOVE_JVM_OPTIONS_DIRECTORY=true
        REMOVE_USER_AND_GROUP=true
    ;;
    failed-upgrade|abort-install|abort-upgrade|disappear|upgrade|disappear)
    ;;

    # RedHat ####################################################
    0)
        REMOVE_DIRS=true
        REMOVE_USER_AND_GROUP=true
    ;;
    1)
        # If $1=1 this is an upgrade
        IS_UPGRADE=true
    ;;

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

if [ "$REMOVE_DIRS" = "true" ]; then

    if [ -d /var/log/opensearch ]; then
        echo -n "Deleting log directory..."
        rm -rf /var/log/opensearch
        echo " OK"
    fi

    if [ -d /usr/share/opensearch/plugins ]; then
        echo -n "Deleting plugins directory..."
        rm -rf /usr/share/opensearch/plugins
        echo " OK"
    fi

    # plugins may have contained bin files
    if [ -d /usr/share/opensearch/bin ]; then
        echo -n "Deleting plugin bin directories..."
        rm -rf /usr/share/opensearch/bin
        echo " OK"
    fi

    if [ -d /var/run/opensearch ]; then
        echo -n "Deleting PID directory..."
        rm -rf /var/run/opensearch
        echo " OK"
    fi

    # Delete the data directory if and only if empty
    if [ -d /var/lib/opensearch ]; then
        rmdir --ignore-fail-on-non-empty /var/lib/opensearch
    fi

    # delete the jvm.options.d directory if and only if empty
    if [ -d "${OPENSEARCH_PATH_CONF}/jvm.options.d" ]; then
        rmdir --ignore-fail-on-non-empty "${OPENSEARCH_PATH_CONF}/jvm.options.d"
    fi

    # delete the jvm.options.d directory if we are purging
    if [ "$REMOVE_JVM_OPTIONS_DIRECTORY" = "true" ]; then
      if [ -d "${OPENSEARCH_PATH_CONF}/jvm.options.d" ]; then
        echo -n "Deleting jvm.options.d directory..."
        rm -rf "${OPENSEARCH_PATH_CONF}/jvm.options.d"
        echo " OK"
      fi
    fi

    # delete the conf directory if and only if empty
    if [ -d "${OPENSEARCH_PATH_CONF}" ]; then
        rmdir --ignore-fail-on-non-empty "${OPENSEARCH_PATH_CONF}"
    fi

fi

if [ "$REMOVE_USER_AND_GROUP" = "true" ]; then
    if id opensearch > /dev/null 2>&1 ; then
        userdel opensearch
    fi

    if getent group opensearch > /dev/null 2>&1 ; then
        groupdel opensearch
    fi
fi

${scripts.footer}
