name: Publish Docker image (manual branch)

on:
  workflow_dispatch:
    inputs:
      branch:
        description: "Branch name to build (e.g. alpha, nightly)"
        required: true
        type: string

jobs:
  prepare:
    name: Prepare Docker tags
    runs-on: ubuntu-latest
    outputs:
      branch: ${{ steps.version.outputs.branch }}
      sha: ${{ steps.version.outputs.sha }}
      tag_prefix: ${{ steps.version.outputs.tag_prefix }}
      version: ${{ steps.version.outputs.version }}
    permissions:
      contents: read
    steps:
      - name: Check out branch
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 1
          ref: ${{ inputs.branch }}

      - name: Resolve Docker tags
        id: version
        env:
          BRANCH_NAME: ${{ inputs.branch }}
        run: |
          TAG_PREFIX=$(printf '%s' "$BRANCH_NAME" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9_.-]+/-/g; s/^[.-]+//; s/[.-]+$//')
          TAG_PREFIX=${TAG_PREFIX:0:105}
          TAG_PREFIX=$(printf '%s' "$TAG_PREFIX" | sed -E 's/[.-]+$//')
          if [ -z "$TAG_PREFIX" ]; then
            echo "::error::Branch '$BRANCH_NAME' cannot be converted to a valid Docker tag prefix"
            exit 1
          fi

          SHA=$(git rev-parse HEAD)
          SHORT_SHA=$(git rev-parse --short HEAD)
          VERSION="${TAG_PREFIX}-$(date +'%Y%m%d')-${SHORT_SHA}"

          echo "branch=$BRANCH_NAME" >> "$GITHUB_OUTPUT"
          echo "sha=$SHA" >> "$GITHUB_OUTPUT"
          echo "tag_prefix=$TAG_PREFIX" >> "$GITHUB_OUTPUT"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "Prepared Docker tags for $BRANCH_NAME at $SHORT_SHA"

  build_single_arch:
    name: Build & push (${{ matrix.arch }}) [native]
    needs: [prepare]
    strategy:
      fail-fast: false
      matrix:
        include:
          - arch: amd64
            platform: linux/amd64
            runner: ubuntu-latest
          - arch: arm64
            platform: linux/arm64
            runner: ubuntu-24.04-arm
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      id-token: write
    steps:
      - name: Check out branch
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 1
          ref: ${{ needs.prepare.outputs.sha }}

      - name: Write VERSION
        run: |
          echo "${{ needs.prepare.outputs.version }}" > VERSION
          echo "Publishing version: ${{ needs.prepare.outputs.version }} for ${{ matrix.arch }}"

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

      - name: Log in to Docker Hub
        uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Extract metadata (labels)
        id: meta
        uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
        with:
          images: |
            calciumion/new-api

      - name: Build & push single-arch
        id: build
        uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
        with:
          context: .
          platforms: ${{ matrix.platform }}
          push: true
          tags: |
            calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }}-${{ matrix.arch }}
            calciumion/new-api:${{ needs.prepare.outputs.version }}-${{ matrix.arch }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: mode=max
          sbom: true

      - name: Install cosign
        uses: sigstore/cosign-installer@398d4b0eeef1380460a10c8013a76f728fb906ac # v3

      - name: Sign image with cosign
        run: cosign sign --yes calciumion/new-api@${{ steps.build.outputs.digest }}

      - name: Output digest
        run: |
          echo "### Docker Image Digest (${{ matrix.arch }})" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          echo "calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }}-${{ matrix.arch }}" >> $GITHUB_STEP_SUMMARY
          echo "calciumion/new-api:${{ needs.prepare.outputs.version }}-${{ matrix.arch }}" >> $GITHUB_STEP_SUMMARY
          echo "${{ steps.build.outputs.digest }}" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY

  create_manifests:
    name: Create multi-arch manifests (Docker Hub)
    needs: [prepare, build_single_arch]
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - name: Log in to Docker Hub
        uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Create & push manifest (Docker Hub - branch)
        run: |
          docker buildx imagetools create \
            -t calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }} \
            calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }}-amd64 \
            calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }}-arm64

      - name: Create & push manifest (Docker Hub - versioned)
        run: |
          docker buildx imagetools create \
            -t calciumion/new-api:${{ needs.prepare.outputs.version }} \
            calciumion/new-api:${{ needs.prepare.outputs.version }}-amd64 \
            calciumion/new-api:${{ needs.prepare.outputs.version }}-arm64

      - name: Install cosign
        uses: sigstore/cosign-installer@398d4b0eeef1380460a10c8013a76f728fb906ac # v3

      - name: Sign manifests with cosign
        run: |
          cosign sign --yes calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }}
          cosign sign --yes calciumion/new-api:${{ needs.prepare.outputs.version }}

      - name: Output manifest digest
        run: |
          echo "### Multi-arch Manifest Digests" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          docker buildx imagetools inspect calciumion/new-api:${{ needs.prepare.outputs.tag_prefix }} >> $GITHUB_STEP_SUMMARY
          echo "---" >> $GITHUB_STEP_SUMMARY
          docker buildx imagetools inspect calciumion/new-api:${{ needs.prepare.outputs.version }} >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
