#!/bin/sh
#
# Perform necessary datadog-agent setup steps prior to remove the old package.
#
# .deb: STEP 1 of 5
# .rpm: STEP 4 of 6

KNOWN_DISTRIBUTION="(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|Arista|SUSE)"
DISTRIBUTION=$(lsb_release -d 2>/dev/null | grep -Eo $KNOWN_DISTRIBUTION  || grep -Eo $KNOWN_DISTRIBUTION /etc/issue 2>/dev/null || grep -Eo $KNOWN_DISTRIBUTION /etc/Eos-release 2>/dev/null || grep -m1 -Eo $KNOWN_DISTRIBUTION /etc/os-release 2>/dev/null || uname -s)

INSTALL_DIR=/opt/datadog-agent
SERVICE_NAME=datadog-agent

if [ -f "/etc/debian_version" ] || [ "$DISTRIBUTION" = "Debian" ] || [ "$DISTRIBUTION" = "Ubuntu" ]; then
    DISTRIBUTION_FAMILY="Debian"
elif [ -f "/etc/SuSE-release" ] || [ "$DISTRIBUTION" = "openSUSE" ] || [ "$DISTRIBUTION" = "SUSE" ]; then
    DISTRIBUTION_FAMILY="SUSE"
fi

if [ "$DISTRIBUTION_FAMILY" = "SUSE" ] && cat /etc/SuSE-release 2>/dev/null | grep VERSION | grep 11; then
    SUSE_SYSVINIT_SUPPORT="yes"
fi

stop_agent()
{
    # Stop an already running agent
    # Only supports systemd and upstart (sysvinit is supported on Debian and SUSE 11)
    if command -v systemctl >/dev/null 2>&1; then
        systemctl stop $SERVICE_NAME-process || true
        systemctl stop $SERVICE_NAME-sysprobe || true
        systemctl stop $SERVICE_NAME-trace || true
        systemctl stop $SERVICE_NAME-security || true
        systemctl stop $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl stop $SERVICE_NAME-process || true
        initctl stop $SERVICE_NAME-sysprobe || true
        initctl stop $SERVICE_NAME-trace || true
        initctl stop $SERVICE_NAME-security || true
        initctl stop $SERVICE_NAME || true
    elif [ "$DISTRIBUTION_FAMILY" = "Debian" ] || [ "$SUSE_SYSVINIT_SUPPORT" = "yes" ]; then
        if command -v service >/dev/null 2>&1; then
            service $SERVICE_NAME-process stop || true
            # TODO: investigate if the following line could be used in other cases than with sysvinit systems (which don't support sysprobe).
            # If not, remove it.
            service $SERVICE_NAME-sysprobe stop || true
            service $SERVICE_NAME-trace stop || true
            service $SERVICE_NAME-security stop || true
            service $SERVICE_NAME stop || true
        else
            echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
        fi
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd and upstart."
    fi
}

deregister_agent()
{
    # Disable agent start on system boot
    # Only supports systemd and upstart
    if command -v systemctl >/dev/null 2>&1; then
        # Force systemd to ignore the sysvinit scripts. Only cosmetic, remove some irrelevant warnings during upgrade
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-process || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-sysprobe || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-trace || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME-security || true
        SYSTEMCTL_SKIP_SYSV=true systemctl disable $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        # Nothing to do, this is defined directly in the upstart job file
        :
    elif [ "$DISTRIBUTION_FAMILY" = "Debian" ]; then
        if command -v update-rc.d >/dev/null 2>&1; then
            update-rc.d -f $SERVICE_NAME-process remove || true
            # TODO: investigate if the following line could be used in other cases than with sysvinit systems (which don't support sysprobe).
            # If not, remove it.
            update-rc.d -f $SERVICE_NAME-sysprobe remove || true
            update-rc.d -f $SERVICE_NAME-trace remove || true
            update-rc.d -f $SERVICE_NAME-security remove || true
            update-rc.d -f $SERVICE_NAME remove || true
        else
            echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
        fi
    elif [ "$SUSE_SYSVINIT_SUPPORT" = "yes" ]; then
        if command -v update-rc.d >/dev/null 2>&1; then
            update-rc.d -f $SERVICE_NAME-process remove || true
            update-rc.d -f $SERVICE_NAME-trace remove || true
            update-rc.d -f $SERVICE_NAME-security remove || true
            update-rc.d -f $SERVICE_NAME remove || true
        elif command -v chkconfig >/dev/null 2>&1; then
            chkconfig --set $SERVICE_NAME off || true
            chkconfig --set $SERVICE_NAME-process off || true
            chkconfig --set $SERVICE_NAME-trace off || true
            chkconfig --set $SERVICE_NAME-security off || true
        fi
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd and upstart."
    fi
}

remove_py_compiled_files()
{
    # Delete all the .pyc files in the embedded dir that are part of the agent's package
    # This MUST be done after using pip or any python, because executing python might generate .pyc files
    if [ -f "$INSTALL_DIR/embedded/.py_compiled_files.txt" ]; then
        # (commented lines are filtered out)
        cat $INSTALL_DIR/embedded/.py_compiled_files.txt | grep -v '^#' | xargs rm -f
    fi
}

remove_custom_integrations()
{
    # Since 6.18.0, a file containing all integrations files which have been installed by
    # the package is available. We use it to remove only the datadog-related check files which
    # have *NOT* been installed by the package (eg: installed using the `integration` command).

    if [ -f "$INSTALL_DIR/embedded/.installed_by_pkg.txt" ]; then
        echo "Removing integrations installed with the 'agent integration' command"

        # List all files in the embedded dir of the datadog-agent install dir
        PREV_DIR=$(pwd)
        cd "$INSTALL_DIR" || return
        find . -depth -path './embedded/lib/python*/site-packages/datadog_*' > $INSTALL_DIR/embedded/.all-integrations.txt

        # List all files in the embedded dir of the datadog-agent install dir
        # which were not installed by the package and rm them.
        grep -Fxv -f $INSTALL_DIR/embedded/.installed_by_pkg.txt $INSTALL_DIR/embedded/.all-integrations.txt | grep -v '^#' | xargs --no-run-if-empty -I '{}' rm -r $INSTALL_DIR/{}

        rm $INSTALL_DIR/embedded/.all-integrations.txt
        cd "$PREV_DIR" || return
    fi
}

remove_version_history()
{
    # Since 6.22.0/7.22.0, a file containing the version history of the currently installed
    # Agent is created (by default in /opt/datadog-agent/run). On a full uninstall, remove this
    # file.
    # This is a best-effort solution, as users can decide to put this file in another place
    # by changing the logs_config.run_path value.

    if [ -f "$INSTALL_DIR/run/version-history.json" ]; then
        echo "Removing version history file"
        rm "$INSTALL_DIR/run/version-history.json" || true
    fi
}

if [ -f "/etc/debian_version" ] || [ "$DISTRIBUTION" = "Debian" ] || [ "$DISTRIBUTION" = "Ubuntu" ]; then
    stop_agent
    deregister_agent
    remove_custom_integrations
    remove_py_compiled_files

    case "$1" in
        remove)
            # We're uninstalling.
            remove_version_history
        ;;
        upgrade)
            # We're upgrading.
        ;;
        *)
        ;;
    esac
elif [ -f "/etc/redhat-release" ] || [ -f "/etc/system-release" ] || [ -f "/etc/SuSE-release" ] || [ "$DISTRIBUTION" = "RedHat" ] || [ "$DISTRIBUTION" = "CentOS" ] || [ "$DISTRIBUTION" = "openSUSE" ] || [ "$DISTRIBUTION" = "Amazon" ] || [ "$DISTRIBUTION" = "SUSE" ] || [ "$DISTRIBUTION" = "Arista" ]; then
    stop_agent
    deregister_agent

    case "$*" in
        0)
            # We're uninstalling.
            remove_custom_integrations
            remove_py_compiled_files
            remove_version_history
        ;;
        1)
            # We're upgrading.
            # The preinst script of the new package has taken care of removing
            # the .pyc/.pyo files, as well as removing custom integrations.
        ;;
        *)
        ;;
    esac
else
    echo "[ FAILED ]\tYour system is currently not supported by this script.";
fi

# Delete all .pyc files in the `agent/` and the `bin/agent/dist` dirs
find $INSTALL_DIR/bin/agent/dist -name '*.py[co]' -type f -delete || echo "Unable to delete .pyc files in $INSTALL_DIR/bin/agent/dist"
find $INSTALL_DIR/bin/agent/dist -name '__pycache__' -type d -delete || echo "Unable to delete __pycache__ directories in $INSTALL_DIR/bin/agent/dist"

exit 0
