name: Build and Deploy to Kubernetes

on:
  push:
    branches:
      - kub-stage

env:
  REGISTRY: 194.5.195.53:30080
  IMAGE_NAME: admin/backoffice
  K8S_SERVER: 194.5.195.53

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    container:
      image: 194.5.195.53:32082/docker-sshpass:latest
      options: --privileged
    steps:
      - name: Start Docker daemon
        run: |
          mkdir -p /etc/docker
          cat > /etc/docker/daemon.json << 'DAEMON'
          {
            "insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32500", "194.5.195.53:32082"]
          }
          DAEMON
          echo "🚀 Starting Docker daemon..."
          dockerd --iptables=false --ip6tables=false --bridge=none --storage-driver=vfs &
          
          # Wait up to 3 minutes for Docker to be ready
          for i in $(seq 1 90); do 
            if docker info >/dev/null 2>&1; then
              echo "✅ Docker daemon is ready (attempt $i)"
              docker version
              break
            else
              echo "⏳ Waiting for Docker daemon... (attempt $i/90)"
              sleep 2
            fi
          done
          
          # Final check
          if ! docker info >/dev/null 2>&1; then
            echo "❌ Docker daemon failed to start after 3 minutes"
            exit 1
          fi

      - name: Checkout code
        run: |
          git clone --depth 1 --branch kub-stage http://gitea-svc:3000/admin/BackOffice.git .

      - name: Login to Docker registries
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login 194.5.195.53:32082 -u admin --password-stdin
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin

      - name: Build Docker Image
        run: |
          cd src
          DOCKER_BUILDKIT=0 docker build --network host -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest -f BackOffice/Dockerfile .

      - name: Push to Registry
        run: |
          docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest

      - name: Deploy to Kubernetes
        run: |
          export SSHPASS="${{ secrets.SERVER_PASSWORD }}"
          sshpass -e ssh -o StrictHostKeyChecking=no root@${{ env.K8S_SERVER }} "
            kubectl rollout restart deployment/backoffice
            kubectl rollout status deployment/backoffice --timeout=180s
          "
          echo "✅ Deployed!"
