name: Build, push image, and notify Watchtower
on:
  push:
    branches:
      - main # Only triggers the build on the main branch

jobs:
  build-image:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4

      - name: Login to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: git.matthiasg.dev
          username: ninluc
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Cache Docker layers
        uses: actions/cache@v4
        with:
          path: /tmp/.buildx-cache
          key: buildx-cache-${{ github.sha }}
          restore-keys: |
            buildx-cache-

      - name: Build and push Docker image
        run: |
          docker build --file cloud/Dockerfile -t git.matthiasg.dev/ninluc/smartwave-api:latest .
          docker push git.matthiasg.dev/ninluc/smartwave-api:latest

  notify:
    needs: build-image
    runs-on: ubuntu-latest
    steps:
      - name: Notify Watchtower
        run: |
          # 1. Grab the default gateway hex code from the routing table
          HEX_GW=$(awk '$2 == "00000000" {print $3; exit}' /proc/net/route)
          
          # 2. Convert little-endian Hex (e.g., 010011AC) to standard Decimal IP (172.17.0.1)
          if [ -n "$HEX_GW" ]; then
            HOST_IP=$(printf "%d.%d.%d.%d" 0x${HEX_GW:6:2} 0x${HEX_GW:4:2} 0x${HEX_GW:2:2} 0x${HEX_GW:0:2})
          else
            HOST_IP="172.29.0.1" # Standard fallback
          fi
          
          echo "Detected Docker Host Gateway IP: $HOST_IP"
          
          # 3. Trigger Watchtower directly over local HTTP port 8080 
          curl -i -X POST \
            -H "Authorization: Bearer ${{ secrets.WATCHTOWER_TOKEN }}" \
            "http://$HOST_IP:8007/v1/update"