#!/bin/bash

# Momentry 外部監控 (Layer 1)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/service/external_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/external_check.log"

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

# 記錄結果
record_external() {
    local target=$1
    local target_type=$2
    local reachable=$3
    local response_time=$4
    local error=$5
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_external (target_name, target_type, is_reachable, response_time_ms, error_message, checked_at)
VALUES ('$target', '$target_type', $reachable, $response_time, '$error', NOW());
EOF
}

# 檢查 DDNS
check_ddns() {
    local start=$(date +%s%N)
    local ip=$(dig +short momentry.ddns.net 2>/dev/null | tail -1)
    local end=$(date +%s%N)
    local ms=$(( (end - start) / 1000000 ))
    
    if [ -n "$ip" ]; then
        echo "✓ DDNS (momentry.ddns.net) -> $ip (${ms}ms)"
        record_external "ddns" "ddns" "true" "$ms" ""
        return 0
    else
        echo "✗ DDNS (momentry.ddns.net) - DNS resolution failed"
        record_external "ddns" "ddns" "false" "0" "DNS resolution failed"
        return 1
    fi
}

# 檢查網關
check_gateway() {
    local start=$(date +%s%N)
    if ping -c 1 -W 2 192.168.110.1 > /dev/null 2>&1; then
        local end=$(date +%s%N)
        local ms=$(( (end - start) / 1000000 ))
        echo "✓ Gateway (192.168.110.1) - ${ms}ms"
        record_external "gateway" "gateway" "true" "$ms" ""
        return 0
    else
        echo "✗ Gateway (192.168.110.1) - Unreachable"
        record_external "gateway" "gateway" "false" "0" "Unreachable"
        return 1
    fi
}

# 檢查互聯網
check_internet() {
    local start=$(date +%s%N)
    if ping -c 1 -W 2 8.8.8.8 > /dev/null 2>&1; then
        local end=$(date +%s%N)
        local ms=$(( (end - start) / 1000000 ))
        echo "✓ Internet (8.8.8.8) - ${ms}ms"
        record_external "internet" "internet" "true" "$ms" ""
        return 0
    else
        echo "✗ Internet (8.8.8.8) - Unreachable"
        record_external "internet" "internet" "false" "0" "Unreachable"
        return 1
    fi
}

# 主程序
echo "========================================"
echo "Layer 1: External Monitoring"
echo "Time: $(date)"
echo "========================================"
echo ""

check_ddns
check_gateway
check_internet

echo ""
echo "========================================"
log "External check completed"
