#!/bin/bash
# =============================================================================
# AWOOOI Database Exporters 部署腳本
# =============================================================================
# 用途: 在 192.168.0.188 部署 PostgreSQL + Redis Exporter
# 執行: ./deploy-exporters.sh [user]
# 版本: v1.0
# 日期: 2026-03-29 (台北時區)
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET_HOST="192.168.0.188"
TARGET_USER="${1:-ogt}"
TARGET_DIR="/home/${TARGET_USER}/monitoring"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  AWOOOI Database Exporters 部署                                 ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# 檢查必要檔案
if [[ ! -f "${SCRIPT_DIR}/docker-compose.exporters.yaml" ]]; then
    echo "❌ 找不到 docker-compose.exporters.yaml"
    exit 1
fi

echo "📁 來源目錄: ${SCRIPT_DIR}"
echo "🎯 目標主機: ${TARGET_USER}@${TARGET_HOST}:${TARGET_DIR}"
echo ""

# Step 1: 建立遠端目錄
echo "1️⃣  建立遠端目錄..."
ssh "${TARGET_USER}@${TARGET_HOST}" "mkdir -p ${TARGET_DIR}"

# Step 2: 複製檔案
echo "2️⃣  複製配置檔案..."
scp "${SCRIPT_DIR}/docker-compose.exporters.yaml" "${TARGET_USER}@${TARGET_HOST}:${TARGET_DIR}/"
scp "${SCRIPT_DIR}/postgres-exporter-queries.yaml" "${TARGET_USER}@${TARGET_HOST}:${TARGET_DIR}/"

# Step 3: 部署容器
echo "3️⃣  部署 Exporters..."
ssh "${TARGET_USER}@${TARGET_HOST}" "cd ${TARGET_DIR} && docker compose -f docker-compose.exporters.yaml up -d"

# Step 4: 驗證
echo "4️⃣  驗證部署..."
sleep 3

echo ""
echo "📊 容器狀態:"
ssh "${TARGET_USER}@${TARGET_HOST}" "docker ps --filter 'name=exporter' --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'"

echo ""
echo "🔍 驗證端點..."

# PostgreSQL Exporter
PG_STATUS=$(ssh "${TARGET_USER}@${TARGET_HOST}" "curl -s -o /dev/null -w '%{http_code}' http://localhost:9187/metrics 2>/dev/null || echo '000'")
if [[ "${PG_STATUS}" == "200" ]]; then
    echo "  ✅ PostgreSQL Exporter: http://${TARGET_HOST}:9187/metrics"
else
    echo "  ❌ PostgreSQL Exporter: HTTP ${PG_STATUS}"
fi

# Redis Exporter
REDIS_STATUS=$(ssh "${TARGET_USER}@${TARGET_HOST}" "curl -s -o /dev/null -w '%{http_code}' http://localhost:9121/metrics 2>/dev/null || echo '000'")
if [[ "${REDIS_STATUS}" == "200" ]]; then
    echo "  ✅ Redis Exporter: http://${TARGET_HOST}:9121/metrics"
else
    echo "  ❌ Redis Exporter: HTTP ${REDIS_STATUS}"
fi

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  ✅ 部署完成！                                                  ║"
echo "╚════════════════════════════════════════════════════════════════╝"
