#!/bin/bash
set -e

# ============================================
# 部署脚本 — 在 dev 服务器(192.168.100.128)上执行
# 用法:
#   本地执行: ./deploy/deploy-dev.sh
#   会自动 SSH 到 dev 服务器完成部署
# ============================================

DEV_HOST="192.168.100.128"
DEV_USER="root"
DEPLOY_DIR="/opt/sundynix"

HARBOR="192.168.100.140"

# 本地项目根目录
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
CONFIG_DIR="${ROOT_DIR}/deploy/dev"

echo "=========================================="
echo "  Sundynix Dev 环境部署"
echo "  目标: ${DEV_USER}@${DEV_HOST}"
echo "=========================================="

# 1. 在 dev 服务器上创建目录结构
echo "[1/4] 创建远程目录..."
ssh ${DEV_USER}@${DEV_HOST} "mkdir -p ${DEPLOY_DIR}/config"

# 2. 同步配置文件到 dev 服务器
echo "[2/4] 同步配置文件..."
scp ${CONFIG_DIR}/system-rpc.yaml ${DEV_USER}@${DEV_HOST}:${DEPLOY_DIR}/config/
scp ${CONFIG_DIR}/auth-api.yaml   ${DEV_USER}@${DEV_HOST}:${DEPLOY_DIR}/config/
scp ${CONFIG_DIR}/system-api.yaml ${DEV_USER}@${DEV_HOST}:${DEPLOY_DIR}/config/
scp ${CONFIG_DIR}/gateway.yaml    ${DEV_USER}@${DEV_HOST}:${DEPLOY_DIR}/config/
scp ${CONFIG_DIR}/docker-compose.yml ${DEV_USER}@${DEV_HOST}:${DEPLOY_DIR}/

# 3. SSH 到 dev 服务器执行部署
echo "[3/4] 拉取镜像并启动服务..."
ssh ${DEV_USER}@${DEV_HOST} << 'REMOTE_SCRIPT'
set -e
cd /opt/sundynix

# 停止旧容器并用已加载的镜像启动
docker compose down --remove-orphans 2>/dev/null || true
docker compose up -d

# 等待 3 秒后检查状态
sleep 3
echo ""
echo "========== 容器状态 =========="
docker compose ps
echo ""
echo "========== 最近日志 =========="
docker compose logs --tail=10
REMOTE_SCRIPT

echo ""
echo "[4/4] 部署完成 ✅"
echo ""
echo "  网关地址: http://${DEV_HOST}:8888"
echo "  auth-api: http://${DEV_HOST}:9001"
echo "  system-api: http://${DEV_HOST}:9003"
echo "  system-rpc: ${DEV_HOST}:9103"
echo ""
echo "  验证: curl http://${DEV_HOST}:8888/api/auth/captcha"
