#!/bin/bash

# Momentry 使用者會話追蹤 (Layer 6)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/users/session_tracker.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/Users/accusys/momentry/log/monitor"

mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/session_check.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 記錄會話
record_session() {
    local session_type=$1
    local service=$2
    local username=$3
    local source_ip=$4
    local status=$5
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_sessions (session_type, service_name, username, source_ip, connected_at, status)
VALUES ('$session_type', '$service', '$username', '$source_ip', NOW(), '$status');
EOF
}

# 記錄登入
record_login() {
    local user_type=$1
    local username=$2
    local source_ip=$3
    local success=$4
    local method=$5
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_logins (user_type, username, source_ip, success, login_method, login_at)
VALUES ('$user_type', '$username', '$source_ip', $success, '$method', NOW());
EOF
}

# 記錄異常
record_anomaly() {
    local anomaly_type=$1
    local severity=$2
    local username=$3
    local source_ip=$4
    local description=$5
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_anomalies (anomaly_type, severity, source_type, username, source_ip, description, detected_at)
VALUES ('$anomaly_type', '$severity', 'system', '$username', '$source_ip', '$description', NOW());
EOF
}

# SSH 會話
track_ssh() {
    echo "SSH 會話:"
    
    # 獲取當前 SSH 連線
    who | grep -E "pts|tty" | while read -r line; do
        user=$(echo "$line" | awk '{print $1}')
        tty=$(echo "$line" | awk '{print $2}')
        login_time=$(echo "$line" | awk '{print $3,$4}')
        ip=$(echo "$line" | awk '{print $NF}' | tr -d '()')
        
        if [ -n "$ip" ] && [ "$ip" != "-" ]; then
            echo "  - $user @ $ip (tty $tty) 登入時間: $login_time"
            record_session "ssh" "sshd" "$user" "$ip" "active"
        fi
    done
    
    # 檢查 SSH 登入失敗
    echo ""
    echo "SSH 登入失敗 (最近 5 分鐘):"
    last -5 -f /var/log/auth.log 2>/dev/null | grep -i "failed password" | tail -5 | while read -r line; do
        user=$(echo "$line" | awk '{print $9}')
        ip=$(echo "$line" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | tail -1)
        
        if [ -n "$ip" ]; then
            echo "  - Failed: $user from $ip"
            record_login "system" "$user" "$ip" "false" "ssh"
        fi
    done
}

# Web 服務會話
track_web() {
    echo ""
    echo "Web 服務:"
    
    # n8n 活躍會話 (如果有認證)
    n8n_sessions=0
    echo "  - n8n: 檢查中... (需要 API key)"
    
    # Gitea 活躍會話
    gitea_sessions=0
    echo "  - Gitea: 檢查中... (需要登入)"
}

# 資料庫連線
track_database() {
    echo ""
    echo "資料庫連線:"
    
    # PostgreSQL
    pg_conn=$(psql -U accusys -h localhost -t -A -c "SELECT count(*) FROM pg_stat_activity WHERE datname = 'momentry';" 2>/dev/null || echo "0")
    echo "  - PostgreSQL: $pg_conn connections"
    
    # Redis
    redis_conn=$(redis-cli -a accusys INFO clients 2>/dev/null | grep "connected_clients" | cut -d: -f2 | tr -d '\r')
    echo "  - Redis: $redis_conn clients"
}

# SFTP 會話
track_sftp() {
    echo ""
    echo "SFTP 會話:"
    
    # 檢查 SFTPGo 在線用戶
    if nc -z localhost 2222 2>/dev/null; then
        echo "  - SFTPGo: 檢查中..."
    fi
}

# 檢測暴力破解
detect_bruteforce() {
    echo ""
    echo "異常檢測:"
    
    # 檢查 SSH 暴力破解
    now=$(date +%s)
    window=300  # 5 分鐘
    
    # 統計最近失敗
    fail_count=$(last -f /var/log/auth.log 2>/dev/null | grep -i "failed" | wc -l)
    
    if [ $fail_count -gt 10 ]; then
        echo "  ⚠️  發現潛在暴力破解嘗試: $fail_count 次失敗"
        record_anomaly "bruteforce" "critical" "unknown" "multiple" "SSH暴力破解: $fail_count 次失敗"
    else
        echo "  ✓ 無明顯暴力破解跡象"
    fi
}

# 主程序
echo "========================================"
echo "Layer 6: User Session Tracking"
echo "Time: $(date)"
echo "========================================"
echo ""

track_ssh
track_web
track_database
track_sftp
detect_bruteforce

echo ""
echo "========================================"
log "Session tracking completed"
