#!/bin/bash
# =============================================================================
# Docker Registry 健康監控腳本
# 用途: 每 5 分鐘檢查 Registry 狀態，異常時自動重啟並發送通知
# Cron: */5 * * * * /home/wooo/momo_pro_system/scripts/registry_health_monitor.sh
# =============================================================================

set -e

# 配置
REGISTRY_URL="https://registry.wooo.work/v2/"
REGISTRY_LOCAL_URL="http://127.0.0.1:5000/v2/"
REGISTRY_DIR="/home/wooo/registry"
REGISTRY_USER="admin"
REGISTRY_PASSWORD="Wooo_Registry_2026"

# Telegram
TELEGRAM_BOT_TOKEN="<TELEGRAM_BOT_TOKEN>"
TELEGRAM_CHAT_ID="5619078117"

# 日誌
LOG_FILE="/var/log/registry_health_monitor.log"

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

send_telegram() {
    local message="$1"
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d chat_id="${TELEGRAM_CHAT_ID}" \
        -d parse_mode="HTML" \
        -d text="$message" > /dev/null 2>&1 || true
}

# =============================================================================
# 健康檢查
# =============================================================================
check_registry() {
    # 檢查本地連線
    local local_status=$(curl -s -o /dev/null -w "%{http_code}" "$REGISTRY_LOCAL_URL" --max-time 10 2>/dev/null)

    if [[ "$local_status" == "200" ]]; then
        log "✅ Registry 本地連線正常"
        return 0
    fi

    log "⚠️ Registry 本地連線失敗 (HTTP $local_status)"

    # 檢查外部連線
    local external_status=$(curl -s -o /dev/null -w "%{http_code}" \
        -u "$REGISTRY_USER:$REGISTRY_PASSWORD" \
        "$REGISTRY_URL" --max-time 10 2>/dev/null)

    if [[ "$external_status" == "200" || "$external_status" == "401" ]]; then
        log "✅ Registry 外部連線正常"
        return 0
    fi

    log "❌ Registry 完全無法連線"
    return 1
}

# =============================================================================
# 自動修復
# =============================================================================
auto_repair() {
    log "🔧 嘗試自動修復..."

    cd "$REGISTRY_DIR" || return 1

    # 重啟 Registry
    docker compose restart

    sleep 10

    # 再次檢查
    if check_registry; then
        log "✅ 自動修復成功"
        send_telegram "✅ <b>Registry 自動修復成功</b>%0A%0A時間: $(date '+%Y-%m-%d %H:%M:%S')"
        return 0
    else
        log "❌ 自動修復失敗"
        send_telegram "❌ <b>Registry 異常</b>%0A%0A自動修復失敗，請手動檢查%0A時間: $(date '+%Y-%m-%d %H:%M:%S')"
        return 1
    fi
}

# =============================================================================
# 主程式
# =============================================================================
main() {
    if check_registry; then
        exit 0
    fi

    send_telegram "⚠️ <b>Registry 異常偵測</b>%0A%0A正在嘗試自動修復...%0A時間: $(date '+%Y-%m-%d %H:%M:%S')"

    auto_repair
}

main
