#!/bin/bash
# 將 awoooi-startup-110 + harbor-watchdog 部署到 192.168.0.110
# 2026-04-05 Claude Code: 加入 harbor-watchdog（運行中崩潰自動恢復）
# 執行方式: bash scripts/reboot-recovery/deploy-to-110.sh
#
# 前提: 執行端已 ssh-copy-id wooo@192.168.0.110
#       且 wooo 有 sudoers NOPASSWD 權限（feedback_cd_security_nopasswd.md）

set -euo pipefail
HOST="wooo@192.168.0.110"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "=== 部署 awoooi-startup-110 + harbor-watchdog 到 192.168.0.110 ==="

# 1. 上傳腳本
echo "[1/5] 上傳啟動腳本..."
scp "$SCRIPT_DIR/awoooi-startup-110.sh" "$HOST:/tmp/awoooi-startup-110.sh"
scp "$SCRIPT_DIR/awoooi-startup-110.service" "$HOST:/tmp/awoooi-startup-110.service"

# 2. 上傳 watchdog
echo "[2/5] 上傳 harbor-watchdog..."
scp "$SCRIPT_DIR/harbor-watchdog.sh" "$HOST:/tmp/harbor-watchdog.sh"
scp "$SCRIPT_DIR/harbor-watchdog.service" "$HOST:/tmp/harbor-watchdog.service"

# 3. 安裝 startup service
echo "[3/5] 安裝 startup service..."
ssh "$HOST" "sudo cp /tmp/awoooi-startup-110.sh /usr/local/bin/awoooi-startup-110.sh && \
    sudo chmod +x /usr/local/bin/awoooi-startup-110.sh && \
    sudo cp /tmp/awoooi-startup-110.service /etc/systemd/system/awoooi-startup-110.service && \
    sudo systemctl daemon-reload && \
    sudo systemctl enable awoooi-startup-110.service && \
    echo 'startup OK'"

# 4. 安裝 watchdog service（立即啟動）
echo "[4/5] 安裝並啟動 harbor-watchdog..."
ssh "$HOST" "sudo cp /tmp/harbor-watchdog.sh /usr/local/bin/harbor-watchdog.sh && \
    sudo chmod +x /usr/local/bin/harbor-watchdog.sh && \
    sudo cp /tmp/harbor-watchdog.service /etc/systemd/system/harbor-watchdog.service && \
    sudo systemctl daemon-reload && \
    sudo systemctl enable harbor-watchdog.service && \
    sudo systemctl restart harbor-watchdog.service && \
    echo 'watchdog OK'"

# 5. 驗證
echo "[5/5] 驗證..."
ssh "$HOST" "sudo systemctl is-active harbor-watchdog.service && echo '✅ harbor-watchdog active' || echo '❌ harbor-watchdog 失敗'"
ssh "$HOST" "sudo systemctl is-enabled awoooi-startup-110.service && echo '✅ startup-110 enabled' || echo '❌ startup-110 未啟用'"

echo ""
echo "✅ 部署完成！"
echo ""
echo "harbor-watchdog: 每 60 秒檢查 Harbor 健康，不健康自動修復"
echo "startup-110:     下次重開機後自動恢復所有服務"
echo ""
echo "查看 watchdog 狀態:"
echo "  ssh $HOST 'journalctl -u harbor-watchdog.service -f'"
