#!/bin/bash

# Momentry WordPress Portal 監控 (Layer 4)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/portal/page_monitor.sh

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

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

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

# WordPress 配置
WP_SITE="https://wp.momentry.ddns.net"
WP_DB_HOST="localhost"
WP_DB_NAME="wordpress"
WP_DB_USER="wp_user"
WP_DB_PASS="wp_password_123"

# 顏色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 記錄頁面檢查結果
record_page() {
    local url=$1
    local page_type=$2
    local accessible=$3
    local response_time=$4
    local http_status=$5
    local error=$6
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_portal_pages (page_url, page_type, is_accessible, response_time_ms, http_status, error_message, checked_at)
VALUES ('$url', '$page_type', $accessible, $response_time, $http_status, '$error', NOW());
EOF
}

# 記錄用戶
record_user() {
    local user_id=$1
    local username=$2
    local email=$3
    local role=$4
    local is_active=$5
    local last_login=$6
    local created_at=$7
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_portal_users (user_id, username, email, role, is_active, last_login, created_at, detected_at)
VALUES ($user_id, '$username', '$email', '$role', $is_active, $last_login, $created_at, NOW())
ON CONFLICT DO NOTHING;
EOF
}

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

# 檢查頁面
check_page() {
    local url=$1
    local page_type=$2
    
    local start=$(date +%s%N)
    local http_code=$(curl -s -o /dev/null -w "%{http_code}" "$url" --max-time 10 -k -L 2>/dev/null || echo "000")
    local end=$(date +%s%N)
    local ms=$(( (end - start) / 1000000 ))
    
    if [ "$http_code" = "200" ]; then
        accessible="true"
        error=""
        echo -e "${GREEN}✓${NC} $page_type - ${ms}ms (HTTP $http_code)"
    else
        accessible="false"
        error="HTTP $http_code"
        echo -e "${RED}✗${NC} $page_type - HTTP $http_code"
    fi
    
    record_page "$url" "$page_type" "$accessible" "$ms" "$http_code" "$error"
}

# 檢查用戶
check_users() {
    echo ""
    echo "WordPress 用戶檢查:"
    echo "----------------------------------------"
    
    # 獲取用戶列表
    users=$(mysql -u"$WP_DB_USER" -p"$WP_DB_PASS" -h "$WP_DB_HOST" "$WP_DB_NAME" -N -e "
        SELECT u.ID, u.user_login, u.user_email, u.user_registered, u.user_status,
               COALESCE(m.meta_value, 'subscriber') as role
        FROM wp_users u
        LEFT JOIN wp_usermeta m ON u.ID = m.user_id AND m.meta_key = 'wp_capabilities'
        ORDER BY u.ID;
    " 2>/dev/null)
    
    if [ -z "$users" ]; then
        echo "無法連接 WordPress 資料庫"
        return 1
    fi
    
    local admin_count=0
    local total_users=0
    
    while IFS='|' read -r id login email registered status role; do
        [ -z "$id" ] && continue
        
        total_users=$((total_users + 1))
        
        # 判斷是否管理員
        if echo "$role" | grep -q "administrator"; then
            admin_count=$((admin_count + 1))
            role="administrator"
        elif echo "$role" | grep -q "editor"; then
            role="editor"
        elif echo "$role" | grep -q "author"; then
            role="author"
        elif echo "$role" | grep -q "contributor"; then
            role="contributor"
        else
            role="subscriber"
        fi
        
        # 記錄用戶
        record_user "$id" "$login" "$email" "$role" "true" "NULL" "'$registered'"
        
        echo "  - $login ($role)"
        
    done <<< "$users"
    
    echo "----------------------------------------"
    echo "總用戶: $total_users | 管理員: $admin_count"
}

# 主程序
echo "========================================"
echo "Layer 4: WordPress Portal Monitoring"
echo "Time: $(date)"
echo "========================================"
echo ""

echo "頁面可訪問性檢查:"
echo "----------------------------------------"

# 檢查首頁
check_page "$WP_SITE/" "homepage"

# 檢查登入頁
check_page "$WP_SITE/wp-login.php" "login_page"

# 檢查 wp-json API
check_page "$WP_SITE/wp-json/" "api"

echo ""
check_users

echo ""
echo "========================================"
log "Portal check completed"
