#!/usr/bin/bash

# Source: https://help.nixstats.com/en/article/uninstall-the-monitoring-agent-1iygnn3/

USER_ID=agent360

set -o nounset  # Treat unset variables as an error

logfile="agent360.log"

#: Check root privilege :#
if [ "$(id -u)" != "0" ]; then
   echo "error: Uninstaller needs 'root' permission to run, please run as 'root'."
   exit 1
fi

# TODO: Remove the WHM Service Monitor for the agent

rpm --quiet --query systemd
systemd_rc=$?
# Stop the agent and remove the service
if [ "$systemd_rc" == "0" ]; then
    # systemd
    echo 'cleaning up systemd service'
    systemctl stop agent360
    systemctl disable agent360
    rm -f /etc/systemd/system/agent360
else
    # sysvinit
    echo 'cleaning up sysv service'
    service agent360 stop
    update-rc.d -f agent360 remove
    rm -f /etc/init.d/agent360
fi

# Remove the agents code
echo "Uninstalling agent360 ... "
pip3 list --format=columns | grep -F agent360
rc=$?
if [ "$rc" != "0" ]; then
    # We found the agents pip module
    command pip3 uninstall -y agent360 >>$logfile 2>&1
    rc=$?
    if [ "$rc" != "0" ] && [ "$rc" != "127" ]; then
        echo pip uninstall of agent360 returned error $?. Please see $logfile for details. $rc
        exit
    fi
fi

# Cleanup the configuration files
rm -f /etc/360agent.ini
rm -f /etc/360agent-token.ini

# If the user exists
getent passwd $USER_ID > /dev/null
rc=$?
if [ "$rc" == "0" ]; then
    userdel $USER_ID
fi

exit 0;
