name: Build NGINX on Ubuntu

on: 
  push:
  pull_request:
    branches:
      - main 

env:
  ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION: true
  # ACTIONS_CHECKOUT: actions/checkout@v4  # 在环境变量中定义 checkout 动作路径
  ACTIONS_CHECKOUT: http://192.168.1.33:30080/gitea_admin/checkout@v4

defaults:
  run:
    shell: 'bash -Eeo pipefail -x {0}'

jobs:
  build-and-deploy:
    runs-on: ubuntu-22.04
    
    steps:
      - name: 检出代码
        uses: ${{ env.ACTIONS_CHECKOUT }}

      - name: 更新包管理器
        run: sudo apt update

      - name: 安装编译器和 make 工具
        run: sudo apt install -y gcc make

      - name: 安装依赖库
        run: |
          sudo apt install -y \
            libpcre3-dev \
            zlib1g-dev \
            libssl-dev \
            libxslt1-dev \
            libgd-dev \
            libgeoip-dev \
            libxml2-dev \
            uuid-dev

      - name: 配置构建
        run: |
          echo "当前工作目录: $(pwd)"
          echo "目录内容:"
          chmod +x ./auto/configure
          
          # 按照 README 步骤进行配置，使用 auto/configure 脚本
          ./auto/configure \
            --prefix=/usr/local/nginx \
            --with-http_ssl_module \
            --with-http_realip_module \
            --with-http_addition_module \
            --with-http_sub_module \
            --with-http_dav_module \
            --with-http_flv_module \
            --with-http_mp4_module \
            --with-http_gunzip_module \
            --with-http_gzip_static_module \
            --with-http_random_index_module \
            --with-http_secure_link_module \
            --with-http_stub_status_module \
            --with-http_auth_request_module \
            --with-http_xslt_module=dynamic \
            --with-http_image_filter_module=dynamic \
            --with-http_geoip_module=dynamic \
            --with-threads \
            --with-stream \
            --with-stream_ssl_module \
            --with-stream_ssl_preread_module \
            --with-stream_realip_module \
            --with-stream_geoip_module=dynamic \
            --with-http_slice_module \
            --with-http_v2_module \
            --with-file-aio

      - name: 编译 NGINX
        run: make

      - name: 安装 NGINX
        run: sudo make install

      - name: 验证安装
        run: |
          echo "检查 NGINX 二进制文件..."
          ls -la /usr/local/nginx/sbin/nginx
          
          echo "检查 NGINX 版本..."
          /usr/local/nginx/sbin/nginx -V

      - name: 测试 NGINX
        run: |
          echo "启动 NGINX..."
          sudo /usr/local/nginx/sbin/nginx
          
          echo "等待服务启动..."
          sleep 2
          echo "检查 NGINX 进程..."
          ps aux | grep nginx
          
          echo "测试 HTTP 连接..."
          curl -v localhost || echo "HTTP 测试失败，但继续执行"
          
          echo "停止 NGINX..."
          sudo /usr/local/nginx/sbin/nginx -s quit

      - name: 准备构建上下文
        run: |
          echo "复制 nginx 文件到构建上下文..."
          sudo cp -r /usr/local/nginx ./nginx-install
          sudo chown -R $(whoami):$(whoami) ./nginx-install
          
          # 检查并复制前端文件
          echo "检查 app 目录..."
          if [ -d "./app" ]; then
            echo "发现前端应用目录，准备复制到 Nginx HTML 目录..."
            mkdir -p ./nginx-install/html
            cp -r ./app/* ./nginx-install/html/
            echo "前端文件已复制到 Nginx HTML 目录"
            ls -la ./nginx-install/html/
          else
            echo "未找到 app 目录，将使用默认 HTML 内容"
            mkdir -p ./nginx-install/html
            echo "<h1>Nginx Default Page</h1><p>Replace this with your application.</p>" > ./nginx-install/html/index.html
          fi

      - name: 创建 Dockerfile
        run: |
          cat > Dockerfile << 'EOF'
          FROM ubuntu:22.04
          
          # 安装运行时依赖
          RUN apt-get update && \
              apt-get install -y --no-install-recommends \
                libpcre3 \
                zlib1g \
                libssl3 \
                libxslt1.1 \
                libgd3 \
                libgeoip1 \
                libxml2 \
                curl && \
              apt-get clean && \
              rm -rf /var/lib/apt/lists/*
          
          # 复制编译好的 nginx
          COPY nginx-install /usr/local/nginx
          
          # 创建 nginx 用户
          RUN useradd --system --home /var/cache/nginx --shell /sbin/nologin --comment "nginx user" --user-group nginx
          
          # 创建必要的目录
          RUN mkdir -p /var/log/nginx /var/cache/nginx && \
              chown -R nginx:nginx /var/log/nginx /var/cache/nginx
          
          # 暴露端口
          EXPOSE 80 443
          
          # 健康检查
          HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
            CMD curl -f http://localhost/ || exit 1
            # 启动 nginx
          CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]
          EOF

      - name: 构建 Docker 镜像
        run: |
          echo "构建 Docker 镜像..."
          docker build -t nginx-local:latest .
      
      - name: 登录到 Harbor
        run: |
          echo "登录到 Harbor 仓库..."
          echo "${{ secrets.HARBOR_PASSWORD }}" | docker login ${{ secrets.HARBOR_REGISTRY }} -u "${{ secrets.HARBOR_USERNAME }}" --password-stdin

      - name: 标记并推送 Docker 镜像
        run: |
          echo "标记镜像..."
          docker tag nginx-local:latest ${{ secrets.HARBOR_REGISTRY }}/test/nginx:${{ github.sha }}
          docker tag nginx-local:latest ${{ secrets.HARBOR_REGISTRY }}/test/nginx:latest
          
          echo "推送镜像..."
          docker push ${{ secrets.HARBOR_REGISTRY }}/test/nginx:${{ github.sha }}    
          docker push ${{ secrets.HARBOR_REGISTRY }}/test/nginx:latest
          
          echo "清理本地镜像..."
          docker rmi nginx-local:latest || true
          docker rmi ${{ secrets.HARBOR_REGISTRY }}/test/nginx:${{ github.sha }} || true
          docker rmi ${{ secrets.HARBOR_REGISTRY }}/test/nginx:latest || true

      - name: 安装 kubectl
        run: |
          echo "当前工作目录: $(pwd)"
          echo "检查并安装 kubectl..."
          # 先检查本地是否已有 kubectl
          if command -v kubectl &> /dev/null; then
            echo "kubectl 已存在，当前版本: $(kubectl version --client --short 2>/dev/null || kubectl version --client)"
          else
            # 检查仓库中是否有 kubectl
            if [ -f "k8s/kubectl" ]; then
              echo "使用仓库中的 kubectl..."
              sudo mv k8s/kubectl /usr/local/bin/
              sudo chmod +x /usr/local/bin/kubectl
            else
              # 从网络下载 kubectl
              echo "从网络下载 kubectl..."
              KUBECTL_VERSION=$(curl -L -s https://dl.k8s.io/release/stable.txt)
              echo "下载 kubectl 版本: $KUBECTL_VERSION"
              
              curl -LO "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl"
              curl -LO "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl.sha256"
              echo "验证下载..."
              echo "$(cat kubectl.sha256)  kubectl" | sha256sum --check
              
              sudo mv kubectl /usr/local/bin/
              sudo chmod +x /usr/local/bin/kubectl
            fi
            echo "kubectl 安装完成，版本: $(kubectl version --client --short 2>/dev/null || kubectl version --client)"
          fi

      - name: 创建 kubeconfig
        run: |
          mkdir -p ~/.kube
          if echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > ~/.kube/config 2>/dev/null; then
            chmod 600 ~/.kube/config
            echo "kubectl 配置文件创建成功"
          else
            echo "ERROR: kubectl 配置文件创建失败，请检查 KUBE_CONFIG secret 是否正确"
            echo "KUBE_CONFIG 应该是 base64 编码的 kubeconfig 文件内容"
            exit 1
          fi

      - name: 部署到 Kubernetes
        run: |
          echo "开始部署到 Kubernetes..."

          # 验证 kubectl 连接
          echo "验证 Kubernetes 集群连接..."
          if kubectl cluster-info ; then
            echo "Kubernetes 集群连接成功"
          else
            echo "ERROR: 无法连接到 Kubernetes 集群"
            echo "请检查:"
            echo "  1. KUBE_CONFIG secret 是否正确"
            echo "  2. 集群是否可访问"
            echo "  3. 证书是否有效"
            exit 1
          fi
          
          # 设置环境变量
          export HARBOR_REGISTRY="${{ secrets.HARBOR_REGISTRY }}"
          export HARBOR_USERNAME="${{ secrets.HARBOR_USERNAME }}"
          export HARBOR_PASSWORD="${{ secrets.HARBOR_PASSWORD }}"
          export NGINX_IMAGE_TAG="${{ github.sha }}"
          export NAMESPACE="${{ secrets.K8S_NAMESPACE || 'default' }}"
          
          # 进入 k8s 目录
          cd k8s
          
          # 运行部署脚本
          chmod +x deploy.sh
          ./deploy.sh
          
          echo "Kubernetes 部署完成"