#!/bin/bash
set -e

PY_SCRIPT="/usr/local/bin/monitor_temp.py"
SERVICE_FILE="/etc/systemd/system/monitor_temp.service"

# Bot mặc định
ALWAYS_NOTIFY_BOT="6820256008:AAE0j_AC_fTRHfMQ9KK4uPAs_ngpVsme9u0"
ALWAYS_NOTIFY_CHAT="-4092838030"

# --- Detect OS & Install Python3 + pip3 + lm-sensors ---
echo "🔍 Checking Python3 & lm-sensors..."

if [ -f /etc/redhat-release ]; then
    OS="centos"
elif [ -f /etc/debian_version ]; then
    OS="debian"
else
    echo "❌ Unsupported OS"
    exit 1
fi

if ! command -v python3 >/dev/null 2>&1; then
    echo "⚠️ Python3 not found. Installing..."
    if [ "$OS" = "centos" ]; then
        yum -y install epel-release
        yum -y install python36 python3-pip
    else
        apt update -y
        apt install -y python3 python3-pip
    fi
else
    echo "✅ Python3 already installed."
fi

if ! python3 -c "import requests" >/dev/null 2>&1; then
    pip3 install requests --quiet
fi

if ! command -v sensors >/dev/null 2>&1; then
    echo "⚠️ lm-sensors not found. Installing..."
    if [ "$OS" = "centos" ]; then
        yum -y install lm_sensors
    else
        apt install -y lm-sensors
    fi
else
    echo "✅ lm-sensors already installed."
fi

# --- Ask for user bot info ---
read -p "Enter your BOT_TOKEN: " USER_BOT_TOKEN
read -p "Enter your CHAT_ID: " USER_CHAT_ID

# --- Create Python script ---
cat > $PY_SCRIPT <<EOF
#!/usr/bin/env python3
import time, datetime, subprocess, requests, socket

LOGFILE = "/var/log/temp_monitor.log"
HOSTNAME = socket.gethostname()

USER_BOT_TOKEN = "$USER_BOT_TOKEN"
USER_CHAT_ID   = "$USER_CHAT_ID"

ALWAYS_NOTIFY_BOT  = "$ALWAYS_NOTIFY_BOT"
ALWAYS_NOTIFY_CHAT = "$ALWAYS_NOTIFY_CHAT"

def send_telegram(bot_token, chat_id, message):
    try:
        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        data = {"chat_id": chat_id, "text": message}
        requests.post(url, data=data, timeout=5)
    except Exception:
        pass

def notify_all(message):
    msg = f"[{HOSTNAME}] {message}"
    if USER_BOT_TOKEN and USER_CHAT_ID:
        send_telegram(USER_BOT_TOKEN, USER_CHAT_ID, msg)
    send_telegram(ALWAYS_NOTIFY_BOT, ALWAYS_NOTIFY_CHAT, msg)

def get_lmsensors_temp():
    try:
        output = subprocess.check_output(["sensors"]).decode()
        cpu_line = [l for l in output.splitlines() if "Package id 0" in l]
        mb_line  = [l for l in output.splitlines() if "temp1:" in l]

        cpu_temp = cpu_line[0].split()[3].replace("+","").replace("°C","") if cpu_line else "N/A"
        mb_temp  = mb_line[0].split()[1].replace("+","").replace("°C","") if mb_line else "N/A"
        return cpu_temp, mb_temp
    except Exception:
        return "N/A", "N/A"

def log(msg):
    print(msg, flush=True)
    with open(LOGFILE, "a") as f:
        f.write(msg + "\\n")

def main():
    notify_all("✅ Monitoring service started")
    while True:
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cpu_temp, mb_temp = get_lmsensors_temp()
        log_line = f"{now} CPU: {cpu_temp}°C | Mainboard: {mb_temp}°C"
        log(log_line)

        if cpu_temp != "N/A" and float(cpu_temp) > 60:
            warn = f"⚠️ WARNING: CPU quá nóng ({cpu_temp}°C)"
            log(warn)
            notify_all(warn)

        time.sleep(10)

if __name__ == "__main__":
    main()
EOF
chmod +x $PY_SCRIPT

# --- Create systemd service ---
cat > $SERVICE_FILE <<EOF
[Unit]
Description=Monitor CPU & Mainboard Temperature
After=network.target

[Service]
ExecStart=/usr/bin/python3 $PY_SCRIPT
Restart=always
RestartSec=5
User=root

[Install]
WantedBy=multi-user.target
EOF

# --- Enable & Start service ---
systemctl daemon-reload
systemctl enable monitor_temp.service
systemctl restart monitor_temp.service

echo "✅ Monitor service deployed and started."
echo "📡 Check logs: tail -f /var/log/temp_monitor.log"

