name: Build Nanobot OAuth

on:
  push:
    branches: ['main']
  pull_request:
    branches: ['main']
  schedule:
    - cron: '0 3 * * *'
  workflow_dispatch:

env:
  REGISTRY: git.wylab.me
  IMAGE_NAME: wylab/nanobot
  BUILDKIT_PROGRESS: plain

jobs:
  build:
    runs-on: [self-hosted, linux-amd64]
    timeout-minutes: 15
    permissions:
      contents: read
      packages: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Log in to the container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME || github.actor }}
          password: ${{ secrets.REGISTRY_PASSWORD || secrets.GITHUB_TOKEN }}

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

  cleanup:
    if: github.event_name == 'push' || github.event_name == 'schedule'
    runs-on: [self-hosted, linux-amd64]
    needs: build
    steps:
      - name: Delete images older than 24h
        env:
          TOKEN: ${{ secrets.REGISTRY_PASSWORD || secrets.GITHUB_TOKEN }}
        run: |
          cutoff=$(date -u -d '24 hours ago' +%s)
          page=1
          while true; do
            versions=$(curl -sf -H "Authorization: token $TOKEN" \
              "https://${{ env.REGISTRY }}/api/v1/packages/wylab?type=container&q=nanobot&limit=50&page=$page")
            count=$(echo "$versions" | jq length)
            [ "$count" = "0" ] && break
            echo "$versions" | jq -c '.[]' | while read -r pkg; do
              ver=$(echo "$pkg" | jq -r '.version')
              # Keep latest and buildcache, only delete SHA tags
              case "$ver" in latest|buildcache) continue ;; esac
              created=$(echo "$pkg" | jq -r '.created_at')
              ts=$(date -u -d "$created" +%s 2>/dev/null || echo 0)
              if [ "$ts" -lt "$cutoff" ]; then
                id=$(echo "$pkg" | jq -r '.id')
                echo "Deleting nanobot:$ver (id=$id, created=$created)"
                curl -sf -X DELETE -H "Authorization: token $TOKEN" \
                  "https://${{ env.REGISTRY }}/api/v1/packages/wylab/container/nanobot/$ver" || true
              fi
            done
            [ "$count" -lt 50 ] && break
            page=$((page + 1))
          done
