name: Build base image

# Path-filtered so it fires when the base Dockerfile (or this workflow)
# changes, weekly via cron so Debian security updates land without us
# remembering to bump anything, and on-demand via workflow_dispatch.
#
# The weekly cron passes CACHE_BUST=<ISO week> as a build-arg so the
# apt layers in Dockerfile.base re-execute (otherwise BuildKit's layer
# cache would short-circuit `apt-get update` on a deterministic input
# and silently skip security patches).
on:
  push:
    branches:
      - main
    paths:
      - 'Dockerfile.base'
      - '.forgejo/workflows/build-base.yaml'
  schedule:
    # Sundays 06:00 UTC — runs on a quiet day-of-week so a long base
    # rebuild doesn't collide with mid-week deploys, and matches the
    # cadence that Debian security advisories typically aggregate at.
    - cron: '0 6 * * 0'
  workflow_dispatch:

# Base image lives on Codeberg's container registry. Registry host
# and creds are sourced from the shared REGISTRY_URL / REGISTRY_USER
# / REGISTRY_PASSWORD secrets.
env:
  REGISTRY: ${{ secrets.REGISTRY_URL }}
  IMAGE_NAME: gmcintire/prop-base

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-and-push:
    name: Build and push base image
    runs-on: ubuntu-22.04

    steps:
      - name: Checkout code
        uses: https://github.com/actions/checkout@v4

      # Static docker + buildx download — same dance as build.yaml /
      # build-grid-rs.yaml. The runner image's bookworm apt repos have
      # broken GPG signatures, so we bypass apt entirely.
      - name: Install Docker CLI and buildx
        run: |
          curl -fsSL -o /tmp/docker.tgz \
            https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
          tar xzf /tmp/docker.tgz -C /tmp
          install -m 0755 /tmp/docker/docker /usr/local/bin/docker
          rm -rf /tmp/docker /tmp/docker.tgz

          mkdir -p /usr/libexec/docker/cli-plugins
          curl -fsSL -o /usr/libexec/docker/cli-plugins/docker-buildx \
            https://github.com/docker/buildx/releases/download/v0.19.3/buildx-v0.19.3.linux-amd64
          chmod +x /usr/libexec/docker/cli-plugins/docker-buildx

          docker --version
          docker buildx version

      - name: Wait for Docker daemon
        run: |
          sock="${DOCKER_HOST:-unix:///var/run/docker.sock}"
          echo "Using DOCKER_HOST=${sock}"

          for i in $(seq 1 30); do
            if docker info >/dev/null 2>&1; then
              echo "Docker daemon reachable after ${i}s"
              exit 0
            fi
            echo "Waiting for Docker daemon... ($i/30)"
            sleep 1
          done

          echo "Docker daemon never became reachable — diagnostics:" >&2
          ls -l /var/run/docker.sock 2>&1 || true
          env | grep -i docker 2>&1 || true
          docker info 2>&1 || true
          exit 1

      - name: Generate image tag
        id: tag
        run: |
          # Embed the wgrib2 + g2c versions in the tag so prior bases
          # remain pullable for hotfix rollbacks if a version bump
          # regresses something at runtime.
          WGRIB2=$(grep -E '^ARG WGRIB2_VERSION=' Dockerfile.base | head -1 | cut -d= -f2)
          G2C=$(grep -E '^ARG G2C_VERSION=' Dockerfile.base | head -1 | cut -d= -f2)
          TIMESTAMP=$(date +%s)
          TAG="wgrib2-${WGRIB2}-g2c-${G2C}-${TIMESTAMP}"
          echo "tag=${TAG}" >> $GITHUB_OUTPUT

      - name: Log in to Codeberg container registry
        run: |
          # Reuses the shared REGISTRY_URL / REGISTRY_USER /
          # REGISTRY_PASSWORD Forgejo Actions secrets (Codeberg
          # token must have `write:package` scope).
          attempt=1
          max_attempts=3
          while : ; do
            if echo "${{ secrets.REGISTRY_PASSWORD }}" | \
                docker login "${{ env.REGISTRY }}" \
                  -u "${{ secrets.REGISTRY_USER }}" \
                  --password-stdin; then
              exit 0
            fi
            if [ "$attempt" -ge "$max_attempts" ]; then
              echo "docker login failed after $attempt attempts" >&2
              exit 1
            fi
            delay=$((2 ** attempt))
            echo "docker login attempt $attempt failed; retrying in ${delay}s"
            sleep "$delay"
            attempt=$((attempt + 1))
          done

      - name: Build and push base image
        run: |
          IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
          TAG="${{ steps.tag.outputs.tag }}"
          # ISO year+week (e.g. 2026-W18). Same value all week, so a
          # cron-triggered rebuild on day 1 vs day 7 reuses the layer
          # cache; the next ISO week boundary forces apt-get update +
          # install to re-execute and pull fresh security patches.
          CACHE_BUST=$(date -u +%G-W%V)
          echo "CACHE_BUST=${CACHE_BUST}"

          attempt=1
          max_attempts=3
          while : ; do
            if docker buildx build \
                -f Dockerfile.base \
                --build-arg CACHE_BUST="${CACHE_BUST}" \
                -t "${IMAGE}:${TAG}" \
                -t "${IMAGE}:latest" \
                --push \
                .; then
              exit 0
            fi
            if [ "$attempt" -ge "$max_attempts" ]; then
              echo "docker buildx build failed after $attempt attempts" >&2
              exit 1
            fi
            delay=$((2 ** attempt))
            echo "docker buildx build attempt $attempt failed; retrying in ${delay}s"
            sleep "$delay"
            attempt=$((attempt + 1))
          done
