name: Publish to packages.smallstep.com

# Independently publish packages to Red Hat (RPM) and Debian (DEB) repositories
# without running a full release. Downloads packages from GitHub releases,
# uploads to GCS, and imports to Artifact Registry.
#
# Usage (CLI):
#   gh workflow run publish-packages.yml -f tag=v0.28.0

on:
  workflow_dispatch:
    inputs:
      tag:
        description: 'Git tag to publish (e.g., v0.28.0)'
        required: true
        type: string

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          ref: ${{ inputs.tag }}
          fetch-depth: 0

      - name: Extract version
        id: version
        run: echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
        env:
          TAG: ${{ inputs.tag }}

      - name: Is Pre-release
        id: is_prerelease
        run: |
          if [[ "$TAG" == *"-rc"* ]]; then
            echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
          else
            echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
          fi
        env:
          TAG: ${{ inputs.tag }}

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
        with:
          workload_identity_provider: ${{ secrets.GOOGLE_CLOUD_WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.GOOGLE_CLOUD_GITHUB_SERVICE_ACCOUNT }}

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
        with:
          project_id: ${{ secrets.GOOGLE_CLOUD_PACKAGES_PROJECT_ID }}

      - name: Download packages from GitHub release
        run: |
          mkdir -p dist
          gh release download "$TAG" --pattern "*${VERSION}*.deb" --pattern "*${VERSION}*.rpm" --dir dist
        env:
          TAG: ${{ inputs.tag }}
          VERSION: ${{ steps.version.outputs.version }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload packages to GCS
        run: |
          for pkg in dist/*.deb dist/*.rpm; do
            ./scripts/package-upload.sh "$pkg" step-ca ${{ steps.version.outputs.version }}
          done

      - name: Import packages to Artifact Registry
        run: ./scripts/package-repo-import.sh step-ca ${{ steps.version.outputs.version }}
        env:
          IS_PRERELEASE: ${{ steps.is_prerelease.outputs.is_prerelease }}
