#!/bin/bash
set -e

SERVICE_NAME="cpu_crit_monitor"
SCRIPT_PATH="/usr/local/bin/${SERVICE_NAME}.py"
ALWAYS_NOTIFY_BOT="6820256008:AAE0j_AC_fTRHfMQ9KK4uPAs_ngpVsme9u0"
ALWAYS_NOTIFY_CHAT="-4092838030"

GREEN="\e[32m"
YELLOW="\e[33m"
RED="\e[31m"
RESET="\e[0m"

echo -e "${YELLOW}🔍 Kiểm tra hệ điều hành...${RESET}"
if [ -f /etc/redhat-release ]; then
    OS="centos"
    SUPERVISOR_CONF_DIR="/etc/supervisord.d"
    SUPERVISOR_CONF_EXT="ini"
    SUPERVISOR_SERVICE="supervisord"
elif [ -f /etc/lsb-release ] || grep -iq ubuntu /etc/os-release; then
    OS="ubuntu"
    SUPERVISOR_CONF_DIR="/etc/supervisor/conf.d"
    SUPERVISOR_CONF_EXT="conf"
    SUPERVISOR_SERVICE="supervisor"
else
    echo -e "${RED}❌ Không xác định được hệ điều hành (chỉ hỗ trợ CentOS/Ubuntu).${RESET}"
    exit 1
fi
SUPERVISOR_CONF="${SUPERVISOR_CONF_DIR}/${SERVICE_NAME}.${SUPERVISOR_CONF_EXT}"
echo -e "${GREEN}✅ Hệ điều hành: $OS${RESET}"

echo -e "${YELLOW}🔍 Kiểm tra và cài Python3, pip3, psutil...${RESET}"
if ! command -v python3 &>/dev/null; then
    echo -e "${YELLOW}📦 Cài Python3...${RESET}"
    [ "$OS" = "centos" ] && yum install -y python3 || (apt update -y && apt install -y python3)
fi

if ! command -v pip3 &>/dev/null; then
    echo -e "${YELLOW}📦 Cài pip3...${RESET}"
    [ "$OS" = "centos" ] && yum install -y python3-pip || apt install -y python3-pip
fi

if ! python3 -c "import psutil" &>/dev/null; then
    echo -e "${YELLOW}📦 Cài psutil...${RESET}"
    [ "$OS" = "ubuntu" ] && pip3 install psutil --break-system-packages || pip3 install psutil
else
    echo -e "${GREEN}✅ psutil đã có.${RESET}"
fi

echo -e "${YELLOW}🔍 Kiểm tra supervisor...${RESET}"
if ! command -v supervisorctl &>/dev/null; then
    echo -e "${YELLOW}📦 Đang cài supervisor...${RESET}"
    if [ "$OS" = "centos" ]; then
        yum install -y epel-release
        yum install -y supervisor
        systemctl enable supervisord
        systemctl start supervisord
    else
        apt install -y supervisor
        systemctl enable supervisor
        systemctl start supervisor
    fi
else
    echo -e "${GREEN}✅ Supervisor đã cài.${RESET}"
fi

if ! pgrep -x supervisord &>/dev/null && ! pgrep -x supervisor &>/dev/null; then
    echo -e "${YELLOW}🚀 Khởi động Supervisor...${RESET}"
    systemctl start ${SUPERVISOR_SERVICE}
fi

read -p "🔧 Đặt ngưỡng cảnh báo CPU (%): " CPU_THRESHOLD
read -p "🤖 Telegram BOT_TOKEN: " BOT_TOKEN
read -p "💬 Telegram CHAT_ID: " CHAT_ID

echo
echo -e "${YELLOW}🧠 Bạn muốn monitor process:"
echo -e "   ${GREEN}1) Multi-core${RESET} (toàn hệ thống)"
echo -e "   ${GREEN}2) Single-core${RESET} (giới hạn theo 1 core)"
read -p "🔢 Chọn [1/2]: " CORE_MODE
if [[ "$CORE_MODE" == "1" ]]; then
    TOTAL_CORE_LINE="total_cores = psutil.cpu_count()"
elif [[ "$CORE_MODE" == "2" ]]; then
    TOTAL_CORE_LINE="total_cores = 1"
else
    echo -e "${RED}❌ Lựa chọn không hợp lệ. Dừng script.${RESET}"
    exit 1
fi

echo -e "${YELLOW}📝 Tạo script Python monitor...${RESET}"
cat > "$SCRIPT_PATH" <<EOF
import psutil
import socket
import time
import requests

BOT_TOKEN = "$BOT_TOKEN"
CHAT_ID = "$CHAT_ID"
ALWAYS_NOTIFY_BOT = "$ALWAYS_NOTIFY_BOT"
ALWAYS_NOTIFY_CHAT = "$ALWAYS_NOTIFY_CHAT"

CPU_USAGE_THRESHOLD = $CPU_THRESHOLD
CHECK_INTERVAL = 10

hostname = socket.gethostname()
$TOTAL_CORE_LINE
notified_pids = set()

def send_telegram(bot, chat, message):
    url = f"https://api-telegram.htn.cloud/bot{bot}/sendMessage"
    payload = {"chat_id": chat, "text": message, "parse_mode": "Markdown"}
    try:
        requests.post(url, data=payload, timeout=5)
    except Exception as e:
        print("Telegram error:", e)

while True:
    try:
        for proc in psutil.process_iter(['pid', 'name']):
            try:
                pid = proc.info['pid']
                name = proc.info['name']
                cpu = proc.cpu_percent(interval=0.1)
                cpu_pct_total = cpu / (total_cores * 100) * 100

                if cpu_pct_total > CPU_USAGE_THRESHOLD and pid not in notified_pids:
                    msg = (
                        f"🚨 *CRITICAL LOAD ALERT*\n"
                        f"📍 Host: \`{hostname}\`\n"
                        f"🆔 PID: \`{pid}\`\n"
                        f"⚙️ Process: \`{name}\`\n"
                        f"🔥 CPU: \`{cpu:.1f}%\` (~{cpu_pct_total:.1f}% of system)"
                    )
                    send_telegram(BOT_TOKEN, CHAT_ID, msg)
                    send_telegram(ALWAYS_NOTIFY_BOT, ALWAYS_NOTIFY_CHAT, msg)
                    notified_pids.add(pid)

            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue

        current_pids = {p.pid for p in psutil.process_iter()}
        notified_pids &= current_pids

    except Exception as e:
        print("Unexpected error:", e)

    time.sleep(CHECK_INTERVAL)
EOF

chmod +x "$SCRIPT_PATH"

echo -e "${YELLOW}📁 Tạo cấu hình Supervisor...${RESET}"
mkdir -p "$SUPERVISOR_CONF_DIR"
cat > "$SUPERVISOR_CONF" <<EOF
[program:${SERVICE_NAME}]
command=python3 ${SCRIPT_PATH}
autostart=true
autorestart=true
stderr_logfile=/var/log/${SERVICE_NAME}.err.log
stdout_logfile=/var/log/${SERVICE_NAME}.out.log
EOF

echo -e "${YELLOW}🔄 Reload Supervisor...${RESET}"
supervisorctl reread
supervisorctl update

echo -e "${YELLOW}🧪 Gửi cảnh báo test đến Telegram bằng Python...${RESET}"
python3 - <<EOF
import requests
import socket

BOT_TOKEN = "$BOT_TOKEN"
CHAT_ID = "$CHAT_ID"
ALWAYS_NOTIFY_BOT = "$ALWAYS_NOTIFY_BOT"
ALWAYS_NOTIFY_CHAT = "$ALWAYS_NOTIFY_CHAT"

hostname = socket.gethostname()
msg = f"✅ [Test] Đã triển khai xong *${SERVICE_NAME}* trên \`{hostname}\`"

def send_telegram(bot, chat, message):
    url = f"https://api-telegram.htn.cloud/bot{bot}/sendMessage"
    payload = {"chat_id": chat, "text": message, "parse_mode": "Markdown"}
    try:
        requests.post(url, data=payload, timeout=5)
    except Exception as e:
        print("❌ Lỗi gửi test alert:", e)

send_telegram(BOT_TOKEN, CHAT_ID, msg)
send_telegram(ALWAYS_NOTIFY_BOT, ALWAYS_NOTIFY_CHAT, msg)
EOF

echo -e "${GREEN}✅ Triển khai hoàn tất. Kiểm tra: tail -f /var/log/${SERVICE_NAME}.out.log${RESET}"

