#!/bin/bash

# Tenant Service 部署脚本
# 用法: ./deploy.sh [环境] [版本]
# 示例: ./deploy.sh prod 1.0.0

set -e

# 配置
SERVICE_NAME="tenant-service"
SERVICE_PORT=8084
DOCKER_REGISTRY="registry.example.com"
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查参数
if [ -z "$1" ]; then
    PROFILE="dev"
else
    PROFILE="$1"
fi

if [ -z "$2" ]; then
    VERSION=$(date +%Y%m%d%H%M)
else
    VERSION="$2"
fi

log_info "开始部署 ${SERVICE_NAME}..."
log_info "环境: ${PROFILE}"
log_info "版本: ${VERSION}"

# 构建
log_info "开始构建..."
cd "${PROJECT_DIR}"
mvn clean package -DskipTests -P${PROFILE}

# Docker 构建
log_info "开始 Docker 构建..."
docker build -t ${DOCKER_REGISTRY}/${SERVICE_NAME}:${VERSION} .
docker tag ${DOCKER_REGISTRY}/${SERVICE_NAME}:${VERSION} ${DOCKER_REGISTRY}/${SERVICE_NAME}:latest

# 推送镜像
log_info "推送镜像到仓库..."
docker push ${DOCKER_REGISTRY}/${SERVICE_NAME}:${VERSION}
docker push ${DOCKER_REGISTRY}/${SERVICE_NAME}:latest

# 部署（使用 kubectl）
log_info "更新 Kubernetes 部署..."
kubectl set image deployment/${SERVICE_NAME} ${SERVICE_NAME}=${DOCKER_REGISTRY}/${SERVICE_NAME}:${VERSION}
kubectl rollout status deployment/${SERVICE_NAME}

# 或者使用 docker-compose 部署
# log_info "使用 docker-compose 重启服务..."
# docker-compose down
# docker-compose up -d

log_info "部署完成！"
log_info "服务地址: http://localhost:${SERVICE_PORT}"
log_info "健康检查: http://localhost:${SERVICE_PORT}/actuator/health"
