#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo "This script must be run as root. Please switch to root and try again."
    exit 1
fi

cpu_arch=$(uname -m)
os_version=$(grep PRETTY_NAME /etc/os-release | cut -d '"' -f 2)
instance_type=$(curl -s --connect-timeout 5 http://metadata.tencentyun.com/latest/meta-data/instance/instance-type)

if [[ -z "$instance_type" ]]; then
    echo "This script is designed to run only on Tencent Cloud instances."
    exit 1
fi

NAIXI_VERSION="2024-09-28"

echo -e '## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##'
echo -e '#              Naixi-Uninstall-QCloud-Agent            #'
echo -e '#                     '$NAIXI_VERSION'                     #'
echo -e '# https://dl.naixi.net/tools/qcloud/uninstall-agent.sh #'
echo -e '## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##'
echo -e

process_check=$(ps -A | grep -E 'agent|barad|YunJing')

if [[ -z "$process_check" ]]; then
    echo "No YunJing or QCloud monitoring services are currently running."
    exit 0
else
    echo "The following YunJing or QCloud monitoring processes are running:"
    echo "$process_check"
fi

echo "Uninstalling YunJing and QCloud monitoring services..."
for script in /usr/local/qcloud/stargate/admin/uninstall.sh \
              /usr/local/qcloud/YunJing/uninst.sh \
              /usr/local/qcloud/monitor/barad/admin/uninstall.sh; do
    if [ -f "$script" ]; then
        bash "$script" || echo "Failed to execute $script. You may need to manually remove YunJing."
    else
        echo "$script not found or not executable"
    fi
done

echo 'Uninstall of QCloud services completed.'

echo "Uninstalling QCloud TAT Agent..."
curl -sL https://tat-1258344699.cos.accelerate.myqcloud.com/tat_agent/uninstall.sh | bash
echo "Uninstall of QCloud TAT AGENT done"

echo 'Cleaning QCloud processes and files...'
process_names=("sap100" "secu-tcs-agent" "sgagent64" "barad_agent" "agent" "agentPlugInD" "pvdriver")
for process in "${process_names[@]}"; do
    pkill -f "$process"
done

rm -rf /usr/local/sa /usr/local/agenttools /usr/local/qcloud

remaining_processes=$(ps -A | grep -E 'agent|barad|YunJing')
if [[ -n "$remaining_processes" ]]; then
    echo "Warning: The following processes are still running after the cleanup:"
    echo "$remaining_processes"
    echo "Consider re-installing the system (dd your system) to ensure complete removal."
else
    echo "All QCloud processes and files have been successfully cleaned."
fi

chkconfig --level 35 postfix off && service postfix stop
echo '' > /var/spool/cron/root
echo '#!/bin/bash' > /etc/rc.local

echo -e '## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##'
echo -e "# Instance Type：$instance_type"
echo -e "# CPU Arch：$cpu_arch"
echo -e "# System：$os_version"
echo -e '## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##'
echo 'Done!'
