name: Build & Publish Release App

on:
  push:
    tags: [ "v*.*.*" ]

concurrency:
  group: "release"
  cancel-in-progress: true

permissions:
  contents: write

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: 21
          distribution: zulu

      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v4
        with:
          cache-write-only: true

      - name: Build with Gradle
        env:
          SIGNING_KEY_ALIAS: ${{ secrets.keyAlias }}
          SIGNING_KEY_PASSWORD: ${{ secrets.keyPassword }}
          SIGNING_STORE_PASSWORD: ${{ secrets.keystorePassword }}
          SIGNING_STORE_FILE: ${{ github.workspace }}/release.keystore
          RELEASE: true
        run: |
          echo "${{ secrets.keystore }}" | base64 -d > release.keystore
          ./gradlew :app:packageRelease --stacktrace
          rm release.keystore

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: app
          if-no-files-found: error
          path: app/build/outputs/apk/release/app-release.apk

      - name: Publish Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          tag="${{ github.ref_name }}"
          apk_file="radiant-lyrics-manager-$tag.apk"
          mv -T ./app/build/outputs/apk/release/app-release.apk "./$apk_file"

          gh release create "$tag" \
            --title "$tag" \
            --generate-notes \
            --verify-tag \
            --fail-on-no-commits \
            "./$apk_file"
