#!/bin/bash

# Configuration
DEVICES_FILE="/etc/ping_monitor/devices.list"  # File with IPs/hostnames (one per line)
LOG_FILE="/var/log/ping_monitor.log"          # Log file location
PING_TIMEOUT=2                                # Ping timeout in seconds
CHECK_INTERVAL=5                              # Check interval in seconds
MAX_MISSED=3                                  # Missed pings before marking as down

# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN="YOUR_BOT_TOKEN"           # Replace with your bot token
TELEGRAM_CHAT_ID="YOUR_CHAT_ID"               # Replace with your chat ID

# Ensure devices file exists
if [ ! -f "$DEVICES_FILE" ]; then
    echo "ERROR: Devices file $DEVICES_FILE not found!" | tee -a "$LOG_FILE"
    exit 1
fi

# Read devices into an array
mapfile -t DEVICES < "$DEVICES_FILE"

# Function: Send Telegram notification
send_telegram() {
    local message="$1"
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d "chat_id=${TELEGRAM_CHAT_ID}" \
        -d "text=$message" \
        -d "parse_mode=Markdown" >> /dev/null
}

# Initialize status tracking
declare -A DEVICE_STATUS
declare -A MISSED_PINGS  # Добавлено объявление массива
for device in "${DEVICES[@]}"; do
    DEVICE_STATUS["$device"]="unknown"
    MISSED_PINGS["$device"]=0  # Инициализация счетчика для каждого устройства
done

# Log start of monitoring
{
    echo "=== Monitoring started at $(date +'%Y-%m-%d %H:%M:%S') ==="
    echo "Targets: ${DEVICES[*]}"
    echo "Ping timeout: $PING_TIMEOUT sec | Check interval: $CHECK_INTERVAL sec"
    echo "Max missed pings before alert: $MAX_MISSED"
} >> "$LOG_FILE"

# Main monitoring loop
while true; do
    for device in "${DEVICES[@]}"; do
        if ping -c 1 -W "$PING_TIMEOUT" "$device" > /dev/null 2>&1; then
            # Device is UP
            if [ "${DEVICE_STATUS[$device]}" != "up" ]; then
                if [ "${DEVICE_STATUS[$device]}" != "unknown" ]; then
                    msg="🟢 *$device* is now **UP** (as of $(date +'%Y-%m-%d %H:%M:%S'))"
                    echo "$msg" >> "$LOG_FILE"
                    send_telegram "$msg"
                else
                    echo "🟢 *$device* was UP at startup" >> "$LOG_FILE"
                fi
                DEVICE_STATUS["$device"]="up"
                MISSED_PINGS["$device"]=0
            fi
        else
            # Device is DOWN
            ((MISSED_PINGS["$device"]++))
            if [ "${DEVICE_STATUS[$device]}" = "up" ] && [ "${MISSED_PINGS[$device]}" -ge "$MAX_MISSED" ]; then
                msg="🔴 *$device* is now **DOWN** (as of $(date +'%Y-%m-%d %H:%M:%S'))"
                echo "$msg" >> "$LOG_FILE"
                send_telegram "$msg"
                DEVICE_STATUS["$device"]="down"
            elif [ "${DEVICE_STATUS[$device]}" = "unknown" ]; then
                echo "🔴 *$device* was DOWN at startup" >> "$LOG_FILE"
                DEVICE_STATUS["$device"]="down"
            fi
        fi
    done
    sleep "$CHECK_INTERVAL"
done