name: Build and Deploy to K3s

on:
  push:
    branches:
      - main
      - master
  pull_request:
    branches:
      - main
      - master

env:
  REGISTRY: gt.wittyoneoff.com
  IMAGE_NAME: jason/socktop-webterm

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.version }}
      image_tag: ${{ steps.get_version.outputs.version }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get version from Cargo.toml
        id: get_version
        run: |
          VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "Building version: ${VERSION}"

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/arm64
          push: ${{ github.event_name != 'pull_request' }}
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.get_version.outputs.version }}
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
          cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
          cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max

  deploy:
    needs: build-and-push
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request'

    steps:
      - name: Checkout code
        uses: actions/checkout@v4gt.wittyoneoff.com/jason/socktop-webterm:0.2.2

      - name: Install kubectl
        run: |
          if ! command -v kubectl &> /dev/null; then
            ARCH=$(uname -m)
            if [ "$ARCH" = "aarch64" ]; then
              ARCH="arm64"
            elif [ "$ARCH" = "x86_64" ]; then
              ARCH="amd64"
            fi
            curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/${ARCH}/kubectl"
            chmod +x kubectl
            sudo mv kubectl /usr/local/bin/
          fi
          kubectl version --client

      - name: Configure kubectl
        run: |
          mkdir -p $HOME/.kube
          echo "${{ secrets.KUBECONFIG }}" | base64 -d > $HOME/.kube/config
          chmod 600 $HOME/.kube/config

      - name: Verify kubectl connection
        run: |
          kubectl get deployment socktop-webterm -n socktop || echo "Deployment will be created"

      - name: Check and create/update deployment
        run: |
          VERSION="${{ needs.build-and-push.outputs.version }}"

          # Check if deployment exists
          if kubectl get deployment socktop-webterm -n socktop &> /dev/null; then
            echo "Deployment exists, updating image..."
            kubectl set image deployment/socktop-webterm \
              webterm=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION} \
              -n socktop
          else
            echo "Deployment does not exist, creating it..."
            kubectl apply -f kubernetes/03-deployment.yaml -n socktop

            # Update the image to the correct version
            kubectl set image deployment/socktop-webterm \
              webterm=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION} \
              -n socktop
          fi

      - name: Wait for rollout to complete
        run: |
          kubectl rollout status deployment/socktop-webterm -n socktop --timeout=30m

      - name: Verify deployment
        run: |
          kubectl get deployment socktop-webterm -n socktop
          kubectl get pods -l app=socktop-webterm -n socktop

      - name: Deployment summary
        if: always()
        run: |
          echo "## Deployment Summary" >> $GITHUB_STEP_SUMMARY
          echo "**Version:** ${{ needs.build-and-push.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "**Image:** ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.build-and-push.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### Pods Status" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          kubectl get pods -l app=socktop-webterm -n socktop >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
