#!/bin/bash

# ============================================
# 仓库服务部署脚本
# ============================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    if ! command -v docker-compose &> /dev/null; then
        log_error "docker-compose未安装，请先安装docker-compose"
        exit 1
    fi
    log_info "Docker环境检查通过"
}

# 检查Nacos网络
check_network() {
    if ! docker network ls | grep -q "erp-network"; then
        log_info "创建erp-network网络..."
        docker network create erp-network
    else
        log_info "erp-network网络已存在"
    fi
}

# 构建Docker镜像
build_image() {
    log_info "开始构建Docker镜像..."
    docker build -t warehouse-service:1.0.0 .
    log_info "镜像构建完成: warehouse-service:1.0.0"
}

# 停止并删除旧容器
cleanup_old() {
    if docker ps -a | grep -q warehouse-service; then
        log_warn "发现旧容器，正在停止并删除..."
        docker stop warehouse-service 2>/dev/null || true
        docker rm warehouse-service 2>/dev/null || true
        log_info "旧容器已清理"
    fi
}

# 启动服务
start_service() {
    log_info "启动仓库服务..."
    docker-compose up -d
    log_info "服务启动成功"
}

# 等待服务就绪
wait_for_ready() {
    log_info "等待服务就绪..."
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -sf http://localhost:8084/actuator/health > /dev/null 2>&1; then
            log_info "服务已就绪!"
            return 0
        fi
        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo ""
    log_error "服务启动超时"
    return 1
}

# 查看日志
show_logs() {
    log_info "最近50行日志:"
    docker logs --tail 50 warehouse-service
}

# 主函数
main() {
    log_info "========================================"
    log_info "    仓库服务部署脚本"
    log_info "========================================"
    
    check_docker
    check_network
    cleanup_old
    build_image
    start_service
    
    if wait_for_ready; then
        log_info "========================================"
        log_info "    部署成功!"
        log_info "    服务地址: http://localhost:8084"
        log_info "    健康检查: http://localhost:8084/actuator/health"
        log_info "========================================"
        
        echo ""
        read -p "是否查看日志? (y/n) " -n 1 -r
        echo ""
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            show_logs
        fi
    else
        log_error "部署失败，请检查日志"
        show_logs
        exit 1
    fi
}

# 根据参数执行不同操作
case "${1:-deploy}" in
    deploy)
        main
        ;;
    rebuild)
        check_docker
        check_network
        cleanup_old
        build_image
        start_service
        wait_for_ready
        ;;
    start)
        docker-compose start
        ;;
    stop)
        docker-compose stop
        ;;
    restart)
        docker-compose restart
        ;;
    logs)
        docker logs -f warehouse-service
        ;;
    status)
        docker ps | grep warehouse-service
        ;;
    clean)
        log_warn "清理所有相关资源..."
        docker stop warehouse-service 2>/dev/null || true
        docker rm warehouse-service 2>/dev/null || true
        docker rmi warehouse-service:1.0.0 2>/dev/null || true
        log_info "清理完成"
        ;;
    *)
        echo "用法: $0 {deploy|rebuild|start|stop|restart|logs|status|clean}"
        echo ""
        echo "  deploy   - 完整部署 (默认)"
        echo "  rebuild  - 重新构建并部署"
        echo "  start    - 启动服务"
        echo "  stop     - 停止服务"
        echo "  restart  - 重启服务"
        echo "  logs     - 查看日志"
        echo "  status   - 查看状态"
        echo "  clean    - 清理资源"
        exit 1
        ;;
esac
