name: Android release build

on:
  workflow_dispatch:
    inputs:
      tramline-input:
        description: "Tramline input"
        required: false

jobs:
  signed-build:
    runs-on: ubuntu-latest
    steps:
      - name: Setup build environment
        uses: msfjarvis/compose-lobsters/.github/reusable-workflows/setup-gradle@main
        with:
          cache-read-only: true
          fetch-depth: 0

      - name: Configure Tramline
        id: tramline
        uses: tramlinehq/deploy-action@58cc98c188b9eda853e549ede6a8b2f58fe29516 # v0.1.7
        with:
          input: ${{ github.event.inputs.tramline-input }}

      - name: Calculate VCS info for Sentry
        shell: bash
        run: |
          # Get HEAD commit SHA
          HEAD_SHA=$(git rev-parse HEAD)
          echo "SENTRY_VCS_HEAD_SHA=${HEAD_SHA}" >> $GITHUB_ENV
          
          # Get parent info (format: commit parent1 [parent2...])
          PARENTS=$(git rev-list --parents -n 1 HEAD)
          PARENT_COUNT=$(echo "$PARENTS" | wc -w)
          
          if [ "$PARENT_COUNT" -ge 3 ]; then
            # Merge commit (commit + 2+ parents): use first parent
            BASE_SHA=$(echo "$PARENTS" | awk '{print $2}')
          else
            # Normal commit: use last release
            LAST_TAG=$(gh release list --limit 1 --json tagName -q '.[0].tagName' || echo "")
            if [ -n "$LAST_TAG" ]; then
              BASE_SHA=$(git rev-parse "${LAST_TAG}^{commit}")
            else
              BASE_SHA="${HEAD_SHA}"
            fi
          fi
          echo "SENTRY_VCS_BASE_SHA=${BASE_SHA}" >> $GITHUB_ENV
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Build release app
        run: |
          ./scripts/setup-age.sh
          ./scripts/signing-setup.sh "$AGE_SECRET_KEY"
          ./gradlew --no-configuration-cache --stacktrace assembleRelease uploadSentryProguardMappingsRelease collectReleaseBundle -PenableSentry
          ./scripts/signing-cleanup.sh
        env:
          ZIPLINE_SIGNING_KEY: ${{ secrets.ZIPLINE_SIGNING_KEY }}
          AGE_SECRET_KEY: ${{ secrets.AGE_SECRET_KEY }}
          SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          SENTRY_VCS_HEAD_SHA: ${{ env.SENTRY_VCS_HEAD_SHA }}
          SENTRY_VCS_BASE_SHA: ${{ env.SENTRY_VCS_BASE_SHA }}
          ORG_GRADLE_PROJECT_VERSION_NAME: ${{ steps.tramline.outputs.version_name }}
          ORG_GRADLE_PROJECT_VERSION_CODE: ${{ steps.tramline.outputs.version_code }}

      - name: Upload app bundle
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: release-aab
          path: android/build/outputs/bundle/release/android-release.aab
