#!/bin/bash
# Container Health Check Script
# Checks all OpenClaw containers and reports unhealthy ones

# Target Feishu user
USER_ID="ou_f442e20fd980363ea486b5a6cd8d2a2f"

# Feishu API settings
APP_ID="cli_a91c042e98b8dcc9"
APP_SECRET="BZVSYgxVdAIAVkYzH7aa7c3sOzv7oczq"

# Get all OpenClaw containers
CONTAINERS=$(docker ps -a --filter "name=openclaw-" --format "{{.Names}}")

UNHEALTHY=""
PERMISSION_ISSUE=""

for container in $CONTAINERS; do
    # Check container status
    STATE=$(docker inspect --format='{{.State.Status}}' $container 2>/dev/null)
    if [ "$STATE" != "running" ]; then
        EXIT_CODE=$(docker inspect --format='{{.State.ExitCode}}' $container 2>/dev/null)
        UNHEALTHY="$UNHEALTHY\n• $container: $STATE (exit code: $EXIT_CODE)"
    else
        # Get Gateway port from container config
        PORT=$(docker exec $container sh -c "cat ~/.openclaw/openclaw.json 2>/dev/null | grep -o '\"port\": *[0-9]*' | grep -o '[0-9]*' | head -1")
        if [ -z "$PORT" ]; then
            PORT=18789  # default fallback
        fi
        
        # Check OpenClaw Gateway responsiveness
        GATEWAY_RESP=$(docker exec $container sh -c "curl -s -o /dev/null -w '%{http_code}' --connect-timeout 3 http://127.0.0.1:$PORT/ 2>/dev/null" 2>/dev/null)
        if [ "$GATEWAY_RESP" != "200" ] && [ "$GATEWAY_RESP" != "302" ]; then
            # Try alternative: check if port is listening
            PORT_CHECK=$(docker exec $container sh -c "nc -z 127.0.0.1 $PORT && echo 'ok'" 2>/dev/null)
            if [ "$PORT_CHECK" != "ok" ]; then
                UNHEALTHY="$UNHEALTHY\n• $container: Gateway not responsive (port: $PORT, http: $GATEWAY_RESP)"
            fi
        fi
    fi
    
    # Check directory permission
    CONFIG_DIR="/home/ubuntu/openclaw-config/$container"
    if [ -d "$CONFIG_DIR" ]; then
        OWNER=$(ls -nd "$CONFIG_DIR" | awk '{print $3":"$4}')
        if [ "$OWNER" != "1100:1100" ]; then
            PERMISSION_ISSUE="$PERMISSION_ISSUE\n• $container: permission mismatch (expected 1100:1100, got $OWNER)"
        fi

        # Determine which agents this container actually uses by reading openclaw.json bindings
        USED_AGENTS=$(docker exec $container sh -c "cat ~/.openclaw/openclaw.json 2>/dev/null" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    bindings = data.get('bindings', [])
    agents = set()
    for b in bindings:
        aid = b.get('agentId', '')
        if aid:
            agents.add(aid)
    # Also check agents.defaults.model (for single-agent configs)
    if 'agents' in data:
        for key in data['agents']:
            agents.add(key)
    print(','.join(sorted(agents)))
except:
    print('defaults,main')
" 2>/dev/null)

        # Check auth-profiles.json only for agents that are actually used
        MISSING_AUTH=""
        for agent in defaults main; do
            # Only check if this agent is used by the container
            echo ",$USED_AGENTS," | grep -q ",$agent," || continue
            AUTH_FILE="$CONFIG_DIR/agents/$agent/agent/auth-profiles.json"
            # Also skip if auth is defined inline in openclaw.json (common for defaults agent)
            INLINE_AUTH=$(docker exec $container sh -c "cat ~/.openclaw/openclaw.json 2>/dev/null" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    auth = data.get('auth', {})
    print('yes' if auth.get('profiles') else 'no')
except:
    print('no')
" 2>/dev/null)
            if [ "$INLINE_AUTH" != "yes" ] && [ ! -f "$AUTH_FILE" ]; then
                MISSING_AUTH="${MISSING_AUTH}$agent/agent/, "
            fi
        done
        MISSING_AUTH=$(echo "$MISSING_AUTH" | sed 's/, $//')
        [ -n "$MISSING_AUTH" ] && PERMISSION_ISSUE="$PERMISSION_ISSUE\n• $container: auth-profiles.json missing in $MISSING_AUTH"
    fi
done

# Combine issues
if [ -n "$UNHEALTHY" ] || [ -n "$PERMISSION_ISSUE" ]; then
    MESSAGE="Container Health Check Alert"
    
    if [ -n "$UNHEALTHY" ]; then
        MESSAGE="$MESSAGE\n\nUnhealthy containers:$UNHEALTHY"
    fi
    
    if [ -n "$PERMISSION_ISSUE" ]; then
        MESSAGE="$MESSAGE\n\nPermission issues:$PERMISSION_ISSUE"
    fi
    
    MESSAGE="$MESSAGE\n\nTime: $(date '+%Y-%m-%d %H:%M:%S')"
    
    # Send to Feishu
    TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
        -H "Content-Type: application/json" \
        -d "{\"app_id\": \"$APP_ID\", \"app_secret\": \"$APP_SECRET\"}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('tenant_access_token',''))")
    
    CONTENT=$(python3 -c "import json; print(json.dumps(json.dumps({'text': '''$MESSAGE'''})))")
    [ -n "$TOKEN" ] && curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"receive_id\": \"$USER_ID\", \"msg_type\": \"text\", \"content\": $CONTENT}" 2>/dev/null
    
    echo "Alert sent for container issues"
else
    # Log healthy status
    echo "✅ System OK - All containers healthy"
fi
