#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
NAMESPACE="socktop"
LABEL="app=socktop-webterm"
REFRESH_INTERVAL=5

echo -e "${GREEN}=== Socktop WebTerm Session Monitor ===${NC}"
echo ""
echo "Monitoring namespace: $NAMESPACE"
echo "Refresh interval: ${REFRESH_INTERVAL}s"
echo "Press Ctrl+C to exit"
echo ""

# Function to get connection count from a pod
get_connections() {
    local pod=$1
    kubectl exec -n "$NAMESPACE" "$pod" -- netstat -tn 2>/dev/null | \
        grep :8082 | grep ESTABLISHED | wc -l
}

# Function to get recent timeout events
get_timeout_events() {
    kubectl logs -n "$NAMESPACE" -l "$LABEL" --tail=50 --since=60s 2>/dev/null | \
        grep -i "timeout\|idle\|disconnect" | tail -10
}

# Function to get active terminal sessions
get_active_terminals() {
    kubectl logs -n "$NAMESPACE" -l "$LABEL" --tail=100 --since=300s 2>/dev/null | \
        grep "Started Terminal" | wc -l
}

# Function to get stopped terminal sessions
get_stopped_terminals() {
    kubectl logs -n "$NAMESPACE" -l "$LABEL" --tail=100 --since=300s 2>/dev/null | \
        grep "Stopping Terminal" | wc -l
}

# Main monitoring loop
while true; do
    clear

    echo -e "${CYAN}╔═══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║        Socktop WebTerm - Session Monitor                     ║${NC}"
    echo -e "${CYAN}║        $(date '+%Y-%m-%d %H:%M:%S')                                   ║${NC}"
    echo -e "${CYAN}╚═══════════════════════════════════════════════════════════════╝${NC}"
    echo ""

    # Get pod information
    echo -e "${BLUE}Pods:${NC}"
    kubectl get pods -n "$NAMESPACE" -l "$LABEL" -o wide 2>/dev/null
    echo ""

    # Get connection counts per pod
    echo -e "${BLUE}Active WebSocket Connections per Pod:${NC}"
    TOTAL_CONNECTIONS=0
    PODS=$(kubectl get pods -n "$NAMESPACE" -l "$LABEL" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null)

    if [ -z "$PODS" ]; then
        echo -e "${RED}  No pods found${NC}"
    else
        for pod in $PODS; do
            CONN_COUNT=$(get_connections "$pod")
            TOTAL_CONNECTIONS=$((TOTAL_CONNECTIONS + CONN_COUNT))

            if [ "$CONN_COUNT" -gt 0 ]; then
                echo -e "  ${GREEN}$pod: $CONN_COUNT connections${NC}"
            else
                echo -e "  ${YELLOW}$pod: $CONN_COUNT connections${NC}"
            fi
        done
        echo ""
        echo -e "${CYAN}Total Active Connections: $TOTAL_CONNECTIONS${NC}"
    fi
    echo ""

    # Session statistics (last 5 minutes)
    echo -e "${BLUE}Session Statistics (last 5 minutes):${NC}"
    STARTED=$(get_active_terminals)
    STOPPED=$(get_stopped_terminals)
    echo -e "  ${GREEN}Sessions started: $STARTED${NC}"
    echo -e "  ${YELLOW}Sessions stopped: $STOPPED${NC}"
    echo ""

    # Recent timeout events
    echo -e "${BLUE}Recent Timeout/Disconnect Events (last 60 seconds):${NC}"
    EVENTS=$(get_timeout_events)

    if [ -z "$EVENTS" ]; then
        echo -e "  ${GREEN}No timeout events${NC}"
    else
        echo "$EVENTS" | while IFS= read -r line; do
            if echo "$line" | grep -qi "timeout"; then
                echo -e "  ${RED}$line${NC}"
            elif echo "$line" | grep -qi "disconnect"; then
                echo -e "  ${YELLOW}$line${NC}"
            else
                echo -e "  $line"
            fi
        done
    fi
    echo ""

    # Resource usage
    echo -e "${BLUE}Resource Usage:${NC}"
    kubectl top pods -n "$NAMESPACE" -l "$LABEL" 2>/dev/null || echo "  (metrics-server not available)"
    echo ""

    echo -e "${CYAN}───────────────────────────────────────────────────────────────${NC}"
    echo -e "Refreshing in ${REFRESH_INTERVAL}s... (Ctrl+C to exit)"

    sleep "$REFRESH_INTERVAL"
done
