#!/usr/bin/env bash
# scripts/ops/deploy-docker-health-monitor.sh
# Sprint 5.2 Plan A: 部署 docker-health-monitor.sh 到 110 和 188 主機
#
# 用法:
#   bash scripts/ops/deploy-docker-health-monitor.sh [110|188|all]
#
# 前置條件:
#   1. AWOOOI_HMAC_SECRET 已在各主機 /etc/awoooi-ops/secrets.env 設定
#   2. SSH key (~/.ssh/deploy_key) 可連線 110/188（透過 121 跳板）
#
# 部署項目:
#   - /opt/awoooi-ops/docker-health-monitor.sh (可執行)
#   - /etc/awoooi-ops/secrets.env.template (template，不覆蓋現有)
#   - logrotate: /etc/logrotate.d/docker-health-monitor
#   - cron: */5 * * * * (wooo user)
#
# 2026-04-08 Claude Sonnet 4.6 Asia/Taipei (Sprint 5.2 Plan A)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
MONITOR_SCRIPT="${REPO_ROOT}/scripts/ops/docker-health-monitor.sh"
TARGET="${1:-all}"

SSH_KEY="${HOME}/.ssh/id_rsa"
KNOWN_HOSTS_FILE="${HOME}/.ssh/known_hosts"

# 110 用 wooo，188 用 ollama
ssh_user() {
    local host="$1"
    case "$host" in
        192.168.0.188) echo "ollama" ;;
        *) echo "wooo" ;;
    esac
}

ssh_cmd() {
    local host="$1"
    shift
    local user
    user=$(ssh_user "$host")
    mkdir -p "${HOME}/.ssh"
    ssh-keyscan -T 5 -t ed25519,rsa,ecdsa "$host" >> "$KNOWN_HOSTS_FILE" 2>/dev/null || true
    ssh -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$KNOWN_HOSTS_FILE" "${user}@${host}" "$@"
}

scp_cmd() {
    local src="$1"
    local host="$2"
    local dst="$3"
    local user
    user=$(ssh_user "$host")
    mkdir -p "${HOME}/.ssh"
    ssh-keyscan -T 5 -t ed25519,rsa,ecdsa "$host" >> "$KNOWN_HOSTS_FILE" 2>/dev/null || true
    scp -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$KNOWN_HOSTS_FILE" "$src" "${user}@${host}:${dst}"
}

deploy_to_host() {
    local host="$1"
    local host_label="$2"
    echo ""
    echo "══════════════════════════════════════════"
    echo "  部署到 ${host_label} (${host})"
    echo "══════════════════════════════════════════"

    # 1. 建立目錄
    echo "→ 建立 /opt/awoooi-ops/ 和 /etc/awoooi-ops/"
    ssh_cmd "$host" "sudo mkdir -p /opt/awoooi-ops /etc/awoooi-ops && sudo chown wooo:wooo /opt/awoooi-ops"

    # 2. 上傳腳本
    echo "→ 上傳 docker-health-monitor.sh"
    scp_cmd "$MONITOR_SCRIPT" "$host" "/tmp/docker-health-monitor.sh"
    ssh_cmd "$host" "sudo mv /tmp/docker-health-monitor.sh /opt/awoooi-ops/docker-health-monitor.sh && sudo chmod +x /opt/awoooi-ops/docker-health-monitor.sh"

    # 3. 建立 secrets.env.template（不覆蓋現有）
    echo "→ 建立 secrets.env.template"
    ssh_cmd "$host" "
    if [ ! -f /etc/awoooi-ops/secrets.env ]; then
        sudo tee /etc/awoooi-ops/secrets.env.template > /dev/null << 'SECRETS_TEMPLATE'
# /etc/awoooi-ops/secrets.env
# Sprint 5.1 docker-health-monitor 設定
# 填寫後複製為 secrets.env: cp secrets.env.template secrets.env
# 權限: chmod 600 /etc/awoooi-ops/secrets.env

AWOOOI_API_URL=https://awoooi.wooo.work
TELEGRAM_BOT_TOKEN=CHANGE_ME
SRE_GROUP_CHAT_ID=-1003711974679
SEND_COOLDOWN_SECONDS=300
SECRETS_TEMPLATE
        echo '  ⚠️  請填寫 /etc/awoooi-ops/secrets.env.template 後重命名為 secrets.env'
    else
        echo '  ✅ /etc/awoooi-ops/secrets.env 已存在，保留現有設定'
    fi
    "

    # 4. logrotate 設定
    echo "→ 設定 logrotate"
    ssh_cmd "$host" "
    sudo tee /etc/logrotate.d/docker-health-monitor > /dev/null << 'LOGROTATE'
/var/log/docker-health-monitor.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 644 wooo wooo
}
LOGROTATE
    "

    # 5. cron 設定（idempotent）
    echo "→ 設定 cron (*/5 * * * *)"
    local cron_line="*/5 * * * * /opt/awoooi-ops/docker-health-monitor.sh >> /var/log/docker-health-monitor.log 2>&1"
    ssh_cmd "$host" "
    (crontab -l 2>/dev/null | grep -v 'docker-health-monitor' ; echo '$cron_line') | crontab -
    echo '  ✅ cron 已設定'
    crontab -l | grep docker-health
    "

    # 6. 測試執行（dry run）
    echo "→ 測試執行（不傳送 webhook）"
    ssh_cmd "$host" "
    LOG_FILE=/tmp/docker-health-monitor-test.log \
    AWOOOI_API_URL='' \
    TELEGRAM_BOT_TOKEN='' \
    bash /opt/awoooi-ops/docker-health-monitor.sh 2>&1 | head -20 || true
    "

    echo "  ✅ ${host_label} 部署完成"
}

# 確認腳本存在
if [ ! -f "$MONITOR_SCRIPT" ]; then
    echo "❌ 找不到: $MONITOR_SCRIPT"
    exit 1
fi

echo "🚀 docker-health-monitor.sh 部署"
echo "   來源: $MONITOR_SCRIPT"
echo "   目標: $TARGET"

case "$TARGET" in
    110)
        deploy_to_host "192.168.0.110" "HOST-110 (Gitea/Harbor/Sentry)"
        ;;
    188)
        deploy_to_host "192.168.0.188" "HOST-188 (OpenClaw/PostgreSQL/Redis)"
        ;;
    all)
        deploy_to_host "192.168.0.110" "HOST-110 (Gitea/Harbor/Sentry)"
        deploy_to_host "192.168.0.188" "HOST-188 (OpenClaw/PostgreSQL/Redis)"
        ;;
    *)
        echo "用法: $0 [110|188|all]"
        exit 1
        ;;
esac

echo ""
echo "🎉 部署完成！"
echo ""
echo "後續步驟："
echo "  1. 確認 /etc/awoooi-ops/secrets.env 已填寫正確 Token"
echo "  2. 手動執行一次: /opt/awoooi-ops/docker-health-monitor.sh"
echo "  3. 確認 /var/log/docker-health-monitor.log 輸出正常"
echo "  4. 確認 AWOOOI op_log 有 ALERT_RECEIVED 記錄"
