#
# 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

set -e

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

export ES_PATH_CONF=${ES_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 elasticsearch service..."
    if command -v systemctl >/dev/null; then
        systemctl --no-reload stop elasticsearch.service || true
    fi
    echo " OK"
fi

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

@scripts.footer@
