name: Publish Linux Repos

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "Release tag (e.g. v0.18.1). Leave empty for latest."
        required: false
        type: string
  workflow_run:
    workflows: ["Release"]
    types:
      - completed

permissions:
  contents: read

jobs:
  publish-repos:
    if: >
      github.repository == 'zhom/donutbrowser' &&
      (github.event_name == 'workflow_dispatch' ||
       github.event.workflow_run.conclusion == 'success')
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7.0.1

      - name: Determine release tag
        id: tag
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          INPUT_TAG: ${{ inputs.tag }}
          EVENT_NAME: ${{ github.event_name }}
          WORKFLOW_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
          REPOSITORY: ${{ github.repository }}
        run: |
          if [[ -n "${INPUT_TAG:-}" ]]; then
            TAG="$INPUT_TAG"
          elif [[ "$EVENT_NAME" == "workflow_run" ]]; then
            # The Release workflow is triggered by a tag push (v*),
            # so head_branch is the tag name
            TAG="$WORKFLOW_HEAD_BRANCH"
          else
            TAG=$(gh release view --repo "$REPOSITORY" --json tagName -q .tagName)
          fi
          if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Invalid release tag" >&2
            exit 1
          fi
          printf 'tag=%s\n' "$TAG" >> "$GITHUB_OUTPUT"

      - name: Install tools
        run: |
          # Mirror the local/Docker setup from CLAUDE.md exactly: the same apt
          # packages and the same pip-installed awscli the working local run uses.
          sudo apt-get update
          sudo apt-get install -y dpkg-dev createrepo-c python3-pip
          pip3 install --break-system-packages awscli
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"

      - name: Publish DEB & RPM repositories to R2
        env:
          R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
          R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
          R2_ENDPOINT_URL: ${{ secrets.R2_ENDPOINT_URL }}
          R2_BUCKET_NAME: ${{ secrets.R2_BUCKET_NAME }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          RELEASE_TAG: ${{ steps.tag.outputs.tag }}
        run: |
          # Normalize accidental quotes and whitespace in configured secrets.
          strip() { printf '%s' "$1" | tr -d '\r\n' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/"; }
          export R2_ACCESS_KEY_ID="$(strip "$R2_ACCESS_KEY_ID")"
          export R2_SECRET_ACCESS_KEY="$(strip "$R2_SECRET_ACCESS_KEY")"
          export R2_ENDPOINT_URL="$(strip "$R2_ENDPOINT_URL")"
          export R2_BUCKET_NAME="$(strip "$R2_BUCKET_NAME")"
          bash scripts/publish-repo.sh "$RELEASE_TAG"
