#!/bin/bash

# NGINX Kubernetes 快速启动脚本
# 用于快速设置和部署 NGINX 到 Kubernetes

set -e

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

print_banner() {
    echo -e "${BLUE}"
    echo "╔════════════════════════════════════════════════════════════════╗"
    echo "║                    NGINX Kubernetes 部署工具                   ║"
    echo "║                   快速启动和配置向导                           ║"
    echo "╚════════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# 交互式配置收集
collect_config() {
    print_info "开始收集配置信息..."
    echo
    
    # Harbor 配置
    read -p "$(echo -e ${BLUE}请输入 Harbor 仓库地址${NC} (例: harbor.example.com): " HARBOR_REGISTRY
    read -p "$(echo -e ${BLUE}请输入 Harbor 用户名${NC}: " HARBOR_USERNAME
    read -s -p "$(echo -e ${BLUE}请输入 Harbor 密码${NC}: " HARBOR_PASSWORD
    echo
    
    # 镜像配置
    read -p "$(echo -e ${BLUE}请输入镜像标签${NC} (默认: latest): " NGINX_IMAGE_TAG
    NGINX_IMAGE_TAG=${NGINX_IMAGE_TAG:-latest}
    
    # Kubernetes 配置
    read -p "$(echo -e ${BLUE}请输入 Kubernetes 命名空间${NC} (默认: default): " NAMESPACE
    NAMESPACE=${NAMESPACE:-default}
    
    echo
    print_success "配置收集完成"
}

# 验证配置
validate_config() {
    print_info "验证配置..."
    
    if [[ -z "$HARBOR_REGISTRY" ]]; then
        print_error "Harbor 仓库地址不能为空"
        return 1
    fi
    
    if [[ -z "$HARBOR_USERNAME" ]]; then
        print_error "Harbor 用户名不能为空"
        return 1
    fi
    
    if [[ -z "$HARBOR_PASSWORD" ]]; then
        print_error "Harbor 密码不能为空"
        return 1
    fi
    
    print_success "配置验证通过"
}

# 保存配置到环境文件
save_config() {
    print_info "保存配置到 .env 文件..."
    
    cat > .env << EOF
# NGINX Kubernetes 部署配置
# 由快速启动脚本生成于 $(date)

# Harbor 仓库配置
HARBOR_REGISTRY=$HARBOR_REGISTRY
HARBOR_USERNAME=$HARBOR_USERNAME
HARBOR_PASSWORD=$HARBOR_PASSWORD

# 镜像配置
NGINX_IMAGE_TAG=$NGINX_IMAGE_TAG

# Kubernetes 配置
NAMESPACE=$NAMESPACE
DEPLOYMENT_FILE=./nginx-deployment.yaml
EOF

    print_success "配置已保存到 .env 文件"
}

# 显示配置摘要
show_config_summary() {
    echo
    print_info "配置摘要:"
    echo "  Harbor 仓库: $HARBOR_REGISTRY"
    echo "  Harbor 用户: $HARBOR_USERNAME"
    echo "  镜像标签: $NGINX_IMAGE_TAG"
    echo "  命名空间: $NAMESPACE"
    echo "  完整镜像地址: $HARBOR_REGISTRY/test/nginx:$NGINX_IMAGE_TAG"
    echo
}

# 检查先决条件
check_prerequisites() {
    print_info "检查先决条件..."
    
    local missing_tools=()
    
    # 检查 kubectl
    if ! command -v kubectl &> /dev/null; then
        missing_tools+=("kubectl")
    fi
    
    # 检查 docker (可选)
    if ! command -v docker &> /dev/null; then
        print_warning "Docker 未安装 (可选)"
    fi
    
    if [[ ${#missing_tools[@]} -gt 0 ]]; then
        print_error "缺少必要工具: ${missing_tools[*]}"
        echo "请安装缺少的工具后重试"
        return 1
    fi
    
    # 检查 kubectl 连接
    if ! kubectl cluster-info &> /dev/null; then
        print_error "无法连接到 Kubernetes 集群"
        echo "请确保 kubectl 已正确配置并能访问集群"
        return 1
    fi
    
    print_success "先决条件检查通过"
}

# 测试 Harbor 连接
test_harbor_connection() {
    print_info "测试 Harbor 连接..."
    
    if command -v docker &> /dev/null; then
        if echo "$HARBOR_PASSWORD" | docker login "$HARBOR_REGISTRY" -u "$HARBOR_USERNAME" --password-stdin &> /dev/null; then
            print_success "Harbor 连接测试通过"
            docker logout "$HARBOR_REGISTRY" &> /dev/null
        else
            print_warning "Harbor 连接测试失败，请检查凭据"
        fi
    else
        print_warning "Docker 未安装，跳过 Harbor 连接测试"
    fi
}

# 运行部署
run_deployment() {
    print_info "开始部署..."
    
    # 导出环境变量
    export HARBOR_REGISTRY
    export HARBOR_USERNAME
    export HARBOR_PASSWORD
    export NGINX_IMAGE_TAG
    export NAMESPACE
    
    # 运行部署脚本
    if [[ -f "deploy.sh" ]]; then
        chmod +x deploy.sh
        ./deploy.sh
    else
        print_error "部署脚本 deploy.sh 不存在"
        return 1
    fi
}

# 提供后续操作建议
show_next_steps() {
    echo
    print_success "🎉 部署完成！"
    echo
    print_info "后续操作建议:"
    echo "  1. 查看部署状态: make status"
    echo "  2. 查看日志: make logs"
    echo "  3. 设置端口转发: make port-forward"
    echo "  4. 扩缩容: make scale REPLICAS=5"
    echo "  5. 更新镜像: make update NGINX_IMAGE_TAG=new-version"
    echo "  6. 清理部署: make clean"
    echo
    print_info "配置文件已保存到 .env，下次可以直接运行 ./deploy.sh"
}

# 主函数
main() {
    print_banner
    
    # 检查是否已有配置文件
    if [[ -f ".env" ]]; then
        read -p "$(echo -e ${YELLOW}发现已存在配置文件 .env，是否重新配置？${NC} (y/N): " RECONFIGURE
        if [[ "$RECONFIGURE" =~ ^[Yy]$ ]]; then
            collect_config
        else
            print_info "使用现有配置文件..."
            source .env
        fi
    else
        collect_config
    fi
    
    validate_config || exit 1
    show_config_summary
    
    # 询问是否继续
    read -p "$(echo -e ${YELLOW}是否继续部署？${NC} (Y/n): " CONTINUE
    if [[ "$CONTINUE" =~ ^[Nn]$ ]]; then
        print_info "部署已取消"
        save_config
        echo "配置已保存，可以稍后运行 ./deploy.sh 进行部署"
        exit 0
    fi
    
    check_prerequisites || exit 1
    test_harbor_connection
    save_config
    run_deployment
    show_next_steps
}

# 清理函数
cleanup() {
    # 恢复终端状态
    stty echo 2>/dev/null || true
}

# 设置清理陷阱
trap cleanup EXIT

# 处理中断信号
trap 'print_warning "操作被中断"; exit 130' INT

# 如果直接运行此脚本
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
