name: Build + deploy releases

# Cuts a channel/release bundle (./build alpha|beta|release [version])
# and rsyncs it to /srv/zddc/releases/ via ./deploy --releases. Runs on
# this host directly (label: host) — same shell environment the operator
# uses for manual cuts, so behavior is identical between the two paths.
#
# Triggers:
#   - workflow_dispatch — pick channel + optional version from the UI.
#   - push to a tag matching zddc-server-v[0-9]+.[0-9]+.[0-9]+ —
#     the canonical "stable cut" tag in our six-tag lockstep set
#     (one per tool: archive-vX.Y.Z, transmittal-vX.Y.Z, ..., zddc-server-vX.Y.Z).
#     Filtering on zddc-server-v* ensures exactly one workflow run per cut
#     even though six tags push together. Runner re-cuts from the tagged
#     commit for reproducibility — _promote_stable in shared/build-lib.sh
#     is idempotent re: tag creation, so rerunning at the same HEAD is a
#     no-op for the tags.

on:
  workflow_dispatch:
    inputs:
      channel:
        description: 'Channel to cut'
        required: true
        type: choice
        default: alpha
        options:
          - alpha
          - beta
          - release
      version:
        description: 'Stable version (e.g. 0.1.0). Leave blank for coordinated next-stable. Ignored for alpha/beta.'
        required: false
        default: ''
  push:
    tags:
      - 'zddc-server-v[0-9]+.[0-9]+.[0-9]+'

jobs:
  build-and-deploy:
    runs-on: host
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          # ./build's _coordinated_next_stable reads tags across all six
          # tools; full history + tags are required.
          fetch-depth: 0

      - name: Resolve channel + version
        id: meta
        run: |
          set -eu
          if [ "$GITHUB_EVENT_NAME" = "push" ]; then
              # Tag push: refs/tags/zddc-server-vX.Y.Z → channel=release, version=X.Y.Z
              VERSION="${GITHUB_REF#refs/tags/zddc-server-v}"
              echo "channel=release" >> "$GITHUB_OUTPUT"
              echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          else
              echo "channel=${{ inputs.channel }}" >> "$GITHUB_OUTPUT"
              echo "version=${{ inputs.version }}" >> "$GITHUB_OUTPUT"
          fi

      - name: Build
        run: |
          set -eu
          CH="${{ steps.meta.outputs.channel }}"
          VER="${{ steps.meta.outputs.version }}"
          if [ "$CH" = "release" ] && [ -n "$VER" ]; then
              ./build release "$VER"
          else
              ./build "$CH"
          fi

      - name: Deploy releases
        run: ./deploy --releases

      - name: Verify channel mirror resolves
        run: |
          set -eu
          CH="${{ steps.meta.outputs.channel }}"
          MIRROR=$([ "$CH" = "release" ] && echo stable || echo "$CH")
          # Runner is in a container on caddy-net; reach Caddy by container
          # name (`caddy`). --connect-to keeps the SNI / Host as the real
          # public hostname so the right vhost matches; -k skips cert
          # verify (Caddy uses a self-signed `tls internal` cert).
          curl -ksI --connect-to "zddc.varasys.io:8443:caddy:8443" \
              "https://zddc.varasys.io:8443/releases/archive_${MIRROR}.html" \
              | head -3

  # On a stable cut (tag push), auto-bump tnd-zddc-chart's appVersion to
  # match the new ZDDC version on BOTH chart branches:
  #
  #   main    → BMCD pipeline-prod fires → prod image rebuilt → prod rolled
  #   develop → BMCD pipeline-dev  fires → dev  image rebuilt → dev  rolled
  #
  # Dev tracking stable is the project invariant for "no active beta"
  # state — when stable advances, dev advances with it. The next beta
  # cut (./build beta on ZDDC main) advances develop ahead of main via
  # notify-chart-dev.yml; this stable cut catches develop back up.
  #
  # Net effect of one ZDDC stable cut: prod + dev + zddc.varasys.io all
  # roll automatically with zero manual steps on either repo. Dispatch-
  # only invocations of this workflow (workflow_dispatch with
  # channel=release) skip — the chart bump is only meaningful when the
  # actual git tag exists at refs/tags/.
  notify-chart-prod:
    needs: build-and-deploy
    if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zddc-server-v')
    runs-on: host
    env:
      # Push to Forgejo (BMCD/tnd-zddc-chart on git.varasys.io), NOT
      # directly to GitHub. The chart repo is mirrored Forgejo→GitHub
      # one-way; pushing directly to GitHub would be silently overwritten
      # the next time Forgejo's mirror syncs (force-push semantics).
      CHART_FORGEJO_TOKEN: ${{ secrets.CHART_FORGEJO_TOKEN }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Force-sync codeberg push-mirror + verify all 8 tags landed
        # The chart Dockerfile fetches zddc-server-v<X.Y.Z> from
        # codeberg (BMC AKS has no egress to git.varasys.io). The
        # varasys → codeberg push-mirror is sync_on_commit=true but
        # occasionally hits a codeberg 504 mid-push, leaving the tag
        # set partially replicated. When that happens, the bump in
        # the next step triggers BMC pipelines that immediately fail
        # at "git fetch refs/tags/zddc-server-v..." until the next
        # mirror interval (8h) catches up.
        #
        # Force a synchronous sync, then poll codeberg until every
        # tool's vX.Y.Z tag is visible. Fails the job (and prevents
        # the chart bump) if codeberg is genuinely unreachable after
        # 5 min — operator runs the sync API manually after.
        env:
          FORGEJO_TOKEN: ${{ github.token }}
        run: |
          set -eu
          TAG_VER="${GITHUB_REF#refs/tags/zddc-server-v}"
          echo "Triggering push-mirror sync for VARASYS/ZDDC..."
          curl -fsS -X POST \
              -H "Authorization: token $FORGEJO_TOKEN" \
              "https://git.varasys.io/api/v1/repos/${GITHUB_REPOSITORY}/push_mirrors-sync"
          echo "Sync triggered; polling codeberg for all 8 v${TAG_VER} tags..."
          TOOLS="archive transmittal classifier landing form tables browse zddc-server"
          for i in $(seq 1 60); do
              MISSING=""
              for T in $TOOLS; do
                  TAG="${T}-v${TAG_VER}"
                  if ! git ls-remote --tags https://codeberg.org/VARASYS/ZDDC.git \
                          "refs/tags/${TAG}" 2>/dev/null | grep -q "${TAG}$"; then
                      MISSING="${MISSING} ${TAG}"
                  fi
              done
              if [ -z "$MISSING" ]; then
                  echo "✓ all 8 tags present on codeberg"
                  exit 0
              fi
              echo "  (poll $i/60) still missing:${MISSING}"
              sleep 5
          done
          echo "::error::tags still missing from codeberg after 5 min:${MISSING}" >&2
          curl -sS -H "Authorization: token $FORGEJO_TOKEN" \
              "https://git.varasys.io/api/v1/repos/${GITHUB_REPOSITORY}/push_mirrors" \
              | head -c 800 >&2
          exit 1
      - name: Bump chart for stable cut
        # All bump logic lives in .forgejo/scripts/notify-chart-bump.sh
        # — same script the dev workflow uses. See its header for
        # behavior. Local invocation:
        #   CHART_FORGEJO_TOKEN=$FORGEJO_TOKEN \
        #     .forgejo/scripts/notify-chart-bump.sh stable X.Y.Z
        run: ./.forgejo/scripts/notify-chart-bump.sh stable "${GITHUB_REF#refs/tags/zddc-server-v}"
