#!/bin/bash

# 设置日志文件路径和Bark API Key
LOG_FILE="/volume1/homes/langke/Connoutput.txt"
BARK_API_KEY="xxxxxxxxxx"//修改为你的BARK_API_KEY
SENT_IPS_FILE="/volume1/homes/langke/sent_ips.txt"
NOTIFICATION_INTERVAL=60  # 30分钟（单位：秒）

# 初始化文件
touch "$SENT_IPS_FILE"
# 本地IP段正则表达式（新增部分）
LOCAL_IPS_REGEX='^(::ffff:(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|127\.)|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|127\.0\.0\.1|::1|fe80:|fc00:|fd00:)'

while true; do
    CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
    CURRENT_TIMESTAMP=$(date +%s)
     
    # 获取当前连接的IP并过滤本地地址（关键修改）
    IPS=$(sudo netstat -atnpW | grep ESTABLISHED | grep ':5001' | awk '{print $5}' | sed 's/:[0-9]*$//' | sort | uniq | grep -vE "$LOCAL_IPS_REGEX")
    for IP in $IPS; do
        NEED_NOTIFY=true
        if grep -q "^$IP " "$SENT_IPS_FILE"; then
            LAST_SENT=$(grep "^$IP " "$SENT_IPS_FILE" | awk '{print $2}')
            TIME_DIFF=$((CURRENT_TIMESTAMP - LAST_SENT))
            if [ $TIME_DIFF -lt $NOTIFICATION_INTERVAL ]; then
                NEED_NOTIFY=false
            fi
        fi

        LOCATION=$(/volume1/homes/langke/get_ip_location.sh <<< "$IP")
        echo "[$CURRENT_TIME] IP: $IP, Location: $LOCATION" >> "$LOG_FILE"
        
        if $NEED_NOTIFY; then
            MESSAGE="Time: $CURRENT_TIME, $LOCATION"
            curl -s -X POST https://api.day.app/$BARK_API_KEY/ \
                 -d "title=群晖连接通知" \
                 -d "group=nas_alert" \
                 -d "body=$MESSAGE" >/dev/null 
            # 更新记录
            sed -i "/^$IP /d" "$SENT_IPS_FILE"
            echo "$IP $CURRENT_TIMESTAMP" >> "$SENT_IPS_FILE"
        fi
    done
    
    # 清理超过30分钟未连接的记录
    while read -r RECORD; do
        RECORD_IP=$(echo "$RECORD" | awk '{print $1}')
        RECORD_TIME=$(echo "$RECORD" | awk '{print $2}')
        TIME_DIFF=$((CURRENT_TIMESTAMP - RECORD_TIME))
        if [ $TIME_DIFF -gt $NOTIFICATION_INTERVAL ]; then
            sed -i "/^$RECORD_IP /d" "$SENT_IPS_FILE"
        fi
    done < <(cat "$SENT_IPS_FILE")
    
    sleep 5
done