#!/bin/bash

# Momentry MongoDB 監控 (Layer 5)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/database/mongodb_monitor.sh

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

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

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

MONGO_USER="accusys"
MONGO_PASS="Test3200Test3200"

record_metric() {
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_databases (db_type, db_name, metric_name, metric_value, checked_at)
VALUES ('mongodb', 'mongodb', '$1', '$2', NOW());
EOF
}

get_status() {
    mongosh --quiet --username "$MONGO_USER" --password "$MONGO_PASS" --authenticationDatabase admin --eval "JSON.stringify(db.adminCommand({ replSetGetStatus: 1 }))" 2>/dev/null || echo "{}"
}

get_server_status() {
    mongosh --quiet --username "$MONGO_USER" --password "$MONGO_PASS" --authenticationDatabase admin --eval "JSON.stringify(db.serverStatus()))" 2>/dev/null || echo "{}"
}

get_databases() {
    mongosh --quiet --username "$MONGO_USER" --password "$MONGO_PASS" --authenticationDatabase admin --eval "JSON.stringify(db.adminCommand({ listDatabases: 1 }))" 2>/dev/null || echo "{}"
}

echo "========================================"
echo "Layer 5: MongoDB Monitoring"
echo "Time: $(date)"
echo "========================================"
echo ""

if ! mongosh --quiet --username "$MONGO_USER" --password "$MONGO_PASS" --authenticationDatabase admin --eval "db.adminCommand('ping')" > /dev/null 2>&1; then
    echo "MongoDB 不可用"
    log "MongoDB unavailable"
    exit 1
fi

echo "✓ MongoDB 連接正常"
echo ""

echo "資料庫:"
echo "----------------------------------------"
databases=$(get_databases)
echo "$databases" | jq -r '.databases[] | "  \(.name): \(.sizeOnDisk / 1024 / 1024 | floor)MB"' 2>/dev/null || echo "  無法獲取資料庫列表"

echo ""
echo "伺服器狀態:"
echo "----------------------------------------"
server_status=$(get_server_status)
connections=$(echo "$server_status" | jq -r '.connections.current' 2>/dev/null || echo "N/A")
active_connections=$(echo "$server_status" | jq -r '.connections.active' 2>/dev/null || echo "N/A")
uptime=$(echo "$server_status" | jq -r '.uptime' 2>/dev/null || echo "N/A")
mem_resident=$(echo "$server_status" | jq -r '.mem.resident' 2>/dev/null || echo "N/A")

echo "  當前連接: $connections"
echo "  活躍連接: $active_connections"
echo "  運行時間: ${uptime}秒"
echo "  記憶體使用: ${mem_resident}MB"

record_metric "connections" "$connections"
record_metric "active_connections" "$active_connections"
record_metric "uptime" "$uptime"
record_metric "mem_resident" "$mem_resident"

echo ""
log "MongoDB check completed: connections=$connections"

echo "========================================"
echo "完成"
echo "========================================"
