#
# This script is executed in the pre-remove phase
#
#   On Debian,
#       $1=remove    : indicates a removal
#       $1=upgrade   : 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}}

STOP_REQUIRED=false
REMOVE_SERVICE=false

case "$1" in

    # Debian ####################################################
    remove)
        STOP_REQUIRED=true
        REMOVE_SERVICE=true
    ;;
    upgrade)
        if [ "$RESTART_ON_UPGRADE" = "true" ]; then
            STOP_REQUIRED=true
        fi
    ;;
    deconfigure|failed-upgrade)
    ;;

    # RedHat ####################################################
    0)
        STOP_REQUIRED=true
        REMOVE_SERVICE=true
    ;;
    1)
        # Dont do anything on upgrade, because the preun script in redhat gets executed after the postinst (madness!)
    ;;

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

# Stops the service
if [ "$STOP_REQUIRED" = "true" ]; then
    echo -n "Stopping opensearch service..."
    if command -v systemctl >/dev/null; then
        systemctl --no-reload stop opensearch.service

    elif [ -x /etc/init.d/opensearch ]; then
        if command -v invoke-rc.d >/dev/null; then
            invoke-rc.d opensearch stop
        else
            /etc/init.d/opensearch stop
        fi

    # older suse linux distributions do not ship with systemd
    # but do not have an /etc/init.d/ directory
    # this tries to start the opensearch service on these
    # as well without failing this script
    elif [ -x /etc/rc.d/init.d/opensearch ] ; then
        /etc/rc.d/init.d/opensearch stop
    fi
    echo " OK"
fi

if [ -f "${OPENSEARCH_PATH_CONF}"/opensearch.keystore ]; then
  if md5sum --status -c "${OPENSEARCH_PATH_CONF}"/.opensearch.keystore.initial_md5sum; then
    rm "${OPENSEARCH_PATH_CONF}"/opensearch.keystore "${OPENSEARCH_PATH_CONF}"/.opensearch.keystore.initial_md5sum
  fi
fi

if [ "$REMOVE_SERVICE" = "true" ]; then
    if command -v systemctl >/dev/null; then
        systemctl disable opensearch.service > /dev/null 2>&1 || true
    fi

    if command -v chkconfig >/dev/null; then
        chkconfig --del opensearch 2> /dev/null || true
    fi

    if command -v update-rc.d >/dev/null; then
        update-rc.d opensearch remove >/dev/null || true
    fi
fi

${scripts.footer}
